cd4eb39839aa4a9270d0ac558814250a97ba647a
[dotfiles/.git] / tsserver.js
1 /*! *****************************************************************************
2 Copyright (c) Microsoft Corporation. All rights reserved.
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 this file except in compliance with the License. You may obtain a copy of the
5 License at http://www.apache.org/licenses/LICENSE-2.0
6
7 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10 MERCHANTABLITY OR NON-INFRINGEMENT.
11
12 See the Apache Version 2.0 License for specific language governing permissions
13 and limitations under the License.
14 ***************************************************************************** */
15
16
17 "use strict";
18 var __spreadArrays = (this && this.__spreadArrays) || function () {
19     for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
20     for (var r = Array(s), k = 0, i = 0; i < il; i++)
21         for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
22             r[k] = a[j];
23     return r;
24 };
25 var __assign = (this && this.__assign) || function () {
26     __assign = Object.assign || function(t) {
27         for (var s, i = 1, n = arguments.length; i < n; i++) {
28             s = arguments[i];
29             for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
30                 t[p] = s[p];
31         }
32         return t;
33     };
34     return __assign.apply(this, arguments);
35 };
36 var __generator = (this && this.__generator) || function (thisArg, body) {
37     var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
38     return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
39     function verb(n) { return function (v) { return step([n, v]); }; }
40     function step(op) {
41         if (f) throw new TypeError("Generator is already executing.");
42         while (_) try {
43             if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
44             if (y = 0, t) op = [op[0] & 2, t.value];
45             switch (op[0]) {
46                 case 0: case 1: t = op; break;
47                 case 4: _.label++; return { value: op[1], done: false };
48                 case 5: _.label++; y = op[1]; op = [0]; continue;
49                 case 7: op = _.ops.pop(); _.trys.pop(); continue;
50                 default:
51                     if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
52                     if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
53                     if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
54                     if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
55                     if (t[2]) _.ops.pop();
56                     _.trys.pop(); continue;
57             }
58             op = body.call(thisArg, _);
59         } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
60         if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
61     }
62 };
63 var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
64     if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
65     return cooked;
66 };
67 var __rest = (this && this.__rest) || function (s, e) {
68     var t = {};
69     for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
70         t[p] = s[p];
71     if (s != null && typeof Object.getOwnPropertySymbols === "function")
72         for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
73             if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
74                 t[p[i]] = s[p[i]];
75         }
76     return t;
77 };
78 var __extends = (this && this.__extends) || (function () {
79     var extendStatics = function (d, b) {
80         extendStatics = Object.setPrototypeOf ||
81             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
82             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
83         return extendStatics(d, b);
84     };
85     return function (d, b) {
86         extendStatics(d, b);
87         function __() { this.constructor = d; }
88         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
89     };
90 })();
91 var ts;
92 (function (ts) {
93     // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
94     // If changing the text in this section, be sure to test `configurePrerelease` too.
95     ts.versionMajorMinor = "3.9";
96     /** The version of the TypeScript compiler release */
97     ts.version = "3.9.6";
98     /**
99      * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
100      */
101     /* @internal */
102     function tryGetNativeMap() {
103         // eslint-disable-next-line no-in-operator
104         return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined;
105     }
106     ts.tryGetNativeMap = tryGetNativeMap;
107     /* @internal */
108     ts.Map = tryGetNativeMap() || (function () {
109         // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
110         if (typeof ts.createMapShim === "function") {
111             return ts.createMapShim();
112         }
113         throw new Error("TypeScript requires an environment that provides a compatible native Map implementation.");
114     })();
115     /* @internal */
116     var Comparison;
117     (function (Comparison) {
118         Comparison[Comparison["LessThan"] = -1] = "LessThan";
119         Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
120         Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
121     })(Comparison = ts.Comparison || (ts.Comparison = {}));
122 })(ts || (ts = {}));
123 /* @internal */
124 var ts;
125 (function (ts) {
126     ts.emptyArray = [];
127     /** Create a new map. */
128     function createMap() {
129         return new ts.Map();
130     }
131     ts.createMap = createMap;
132     /** Create a new map from an array of entries. */
133     function createMapFromEntries(entries) {
134         var map = createMap();
135         for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
136             var _a = entries_1[_i], key = _a[0], value = _a[1];
137             map.set(key, value);
138         }
139         return map;
140     }
141     ts.createMapFromEntries = createMapFromEntries;
142     /** Create a new map from a template object is provided, the map will copy entries from it. */
143     function createMapFromTemplate(template) {
144         var map = new ts.Map();
145         // Copies keys/values from template. Note that for..in will not throw if
146         // template is undefined, and instead will just exit the loop.
147         for (var key in template) {
148             if (hasOwnProperty.call(template, key)) {
149                 map.set(key, template[key]);
150             }
151         }
152         return map;
153     }
154     ts.createMapFromTemplate = createMapFromTemplate;
155     function length(array) {
156         return array ? array.length : 0;
157     }
158     ts.length = length;
159     /**
160      * Iterates through 'array' by index and performs the callback on each element of array until the callback
161      * returns a truthy value, then returns that value.
162      * If no such value is found, the callback is applied to each element of array and undefined is returned.
163      */
164     function forEach(array, callback) {
165         if (array) {
166             for (var i = 0; i < array.length; i++) {
167                 var result = callback(array[i], i);
168                 if (result) {
169                     return result;
170                 }
171             }
172         }
173         return undefined;
174     }
175     ts.forEach = forEach;
176     /**
177      * Like `forEach`, but iterates in reverse order.
178      */
179     function forEachRight(array, callback) {
180         if (array) {
181             for (var i = array.length - 1; i >= 0; i--) {
182                 var result = callback(array[i], i);
183                 if (result) {
184                     return result;
185                 }
186             }
187         }
188         return undefined;
189     }
190     ts.forEachRight = forEachRight;
191     /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
192     function firstDefined(array, callback) {
193         if (array === undefined) {
194             return undefined;
195         }
196         for (var i = 0; i < array.length; i++) {
197             var result = callback(array[i], i);
198             if (result !== undefined) {
199                 return result;
200             }
201         }
202         return undefined;
203     }
204     ts.firstDefined = firstDefined;
205     function firstDefinedIterator(iter, callback) {
206         while (true) {
207             var iterResult = iter.next();
208             if (iterResult.done) {
209                 return undefined;
210             }
211             var result = callback(iterResult.value);
212             if (result !== undefined) {
213                 return result;
214             }
215         }
216     }
217     ts.firstDefinedIterator = firstDefinedIterator;
218     function zipWith(arrayA, arrayB, callback) {
219         var result = [];
220         ts.Debug.assertEqual(arrayA.length, arrayB.length);
221         for (var i = 0; i < arrayA.length; i++) {
222             result.push(callback(arrayA[i], arrayB[i], i));
223         }
224         return result;
225     }
226     ts.zipWith = zipWith;
227     function zipToIterator(arrayA, arrayB) {
228         ts.Debug.assertEqual(arrayA.length, arrayB.length);
229         var i = 0;
230         return {
231             next: function () {
232                 if (i === arrayA.length) {
233                     return { value: undefined, done: true };
234                 }
235                 i++;
236                 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
237             }
238         };
239     }
240     ts.zipToIterator = zipToIterator;
241     function zipToMap(keys, values) {
242         ts.Debug.assert(keys.length === values.length);
243         var map = createMap();
244         for (var i = 0; i < keys.length; ++i) {
245             map.set(keys[i], values[i]);
246         }
247         return map;
248     }
249     ts.zipToMap = zipToMap;
250     /**
251      * Iterates through `array` by index and performs the callback on each element of array until the callback
252      * returns a falsey value, then returns false.
253      * If no such value is found, the callback is applied to each element of array and `true` is returned.
254      */
255     function every(array, callback) {
256         if (array) {
257             for (var i = 0; i < array.length; i++) {
258                 if (!callback(array[i], i)) {
259                     return false;
260                 }
261             }
262         }
263         return true;
264     }
265     ts.every = every;
266     function find(array, predicate) {
267         for (var i = 0; i < array.length; i++) {
268             var value = array[i];
269             if (predicate(value, i)) {
270                 return value;
271             }
272         }
273         return undefined;
274     }
275     ts.find = find;
276     function findLast(array, predicate) {
277         for (var i = array.length - 1; i >= 0; i--) {
278             var value = array[i];
279             if (predicate(value, i)) {
280                 return value;
281             }
282         }
283         return undefined;
284     }
285     ts.findLast = findLast;
286     /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
287     function findIndex(array, predicate, startIndex) {
288         for (var i = startIndex || 0; i < array.length; i++) {
289             if (predicate(array[i], i)) {
290                 return i;
291             }
292         }
293         return -1;
294     }
295     ts.findIndex = findIndex;
296     function findLastIndex(array, predicate, startIndex) {
297         for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
298             if (predicate(array[i], i)) {
299                 return i;
300             }
301         }
302         return -1;
303     }
304     ts.findLastIndex = findLastIndex;
305     /**
306      * Returns the first truthy result of `callback`, or else fails.
307      * This is like `forEach`, but never returns undefined.
308      */
309     function findMap(array, callback) {
310         for (var i = 0; i < array.length; i++) {
311             var result = callback(array[i], i);
312             if (result) {
313                 return result;
314             }
315         }
316         return ts.Debug.fail();
317     }
318     ts.findMap = findMap;
319     function contains(array, value, equalityComparer) {
320         if (equalityComparer === void 0) { equalityComparer = equateValues; }
321         if (array) {
322             for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
323                 var v = array_1[_i];
324                 if (equalityComparer(v, value)) {
325                     return true;
326                 }
327             }
328         }
329         return false;
330     }
331     ts.contains = contains;
332     function arraysEqual(a, b, equalityComparer) {
333         if (equalityComparer === void 0) { equalityComparer = equateValues; }
334         return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
335     }
336     ts.arraysEqual = arraysEqual;
337     function indexOfAnyCharCode(text, charCodes, start) {
338         for (var i = start || 0; i < text.length; i++) {
339             if (contains(charCodes, text.charCodeAt(i))) {
340                 return i;
341             }
342         }
343         return -1;
344     }
345     ts.indexOfAnyCharCode = indexOfAnyCharCode;
346     function countWhere(array, predicate) {
347         var count = 0;
348         if (array) {
349             for (var i = 0; i < array.length; i++) {
350                 var v = array[i];
351                 if (predicate(v, i)) {
352                     count++;
353                 }
354             }
355         }
356         return count;
357     }
358     ts.countWhere = countWhere;
359     function filter(array, f) {
360         if (array) {
361             var len = array.length;
362             var i = 0;
363             while (i < len && f(array[i]))
364                 i++;
365             if (i < len) {
366                 var result = array.slice(0, i);
367                 i++;
368                 while (i < len) {
369                     var item = array[i];
370                     if (f(item)) {
371                         result.push(item);
372                     }
373                     i++;
374                 }
375                 return result;
376             }
377         }
378         return array;
379     }
380     ts.filter = filter;
381     function filterMutate(array, f) {
382         var outIndex = 0;
383         for (var i = 0; i < array.length; i++) {
384             if (f(array[i], i, array)) {
385                 array[outIndex] = array[i];
386                 outIndex++;
387             }
388         }
389         array.length = outIndex;
390     }
391     ts.filterMutate = filterMutate;
392     function clear(array) {
393         array.length = 0;
394     }
395     ts.clear = clear;
396     function map(array, f) {
397         var result;
398         if (array) {
399             result = [];
400             for (var i = 0; i < array.length; i++) {
401                 result.push(f(array[i], i));
402             }
403         }
404         return result;
405     }
406     ts.map = map;
407     function mapIterator(iter, mapFn) {
408         return {
409             next: function () {
410                 var iterRes = iter.next();
411                 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
412             }
413         };
414     }
415     ts.mapIterator = mapIterator;
416     function sameMap(array, f) {
417         if (array) {
418             for (var i = 0; i < array.length; i++) {
419                 var item = array[i];
420                 var mapped = f(item, i);
421                 if (item !== mapped) {
422                     var result = array.slice(0, i);
423                     result.push(mapped);
424                     for (i++; i < array.length; i++) {
425                         result.push(f(array[i], i));
426                     }
427                     return result;
428                 }
429             }
430         }
431         return array;
432     }
433     ts.sameMap = sameMap;
434     /**
435      * Flattens an array containing a mix of array or non-array elements.
436      *
437      * @param array The array to flatten.
438      */
439     function flatten(array) {
440         var result = [];
441         for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
442             var v = array_2[_i];
443             if (v) {
444                 if (isArray(v)) {
445                     addRange(result, v);
446                 }
447                 else {
448                     result.push(v);
449                 }
450             }
451         }
452         return result;
453     }
454     ts.flatten = flatten;
455     /**
456      * Maps an array. If the mapped value is an array, it is spread into the result.
457      *
458      * @param array The array to map.
459      * @param mapfn The callback used to map the result into one or more values.
460      */
461     function flatMap(array, mapfn) {
462         var result;
463         if (array) {
464             for (var i = 0; i < array.length; i++) {
465                 var v = mapfn(array[i], i);
466                 if (v) {
467                     if (isArray(v)) {
468                         result = addRange(result, v);
469                     }
470                     else {
471                         result = append(result, v);
472                     }
473                 }
474             }
475         }
476         return result || ts.emptyArray;
477     }
478     ts.flatMap = flatMap;
479     function flatMapToMutable(array, mapfn) {
480         var result = [];
481         if (array) {
482             for (var i = 0; i < array.length; i++) {
483                 var v = mapfn(array[i], i);
484                 if (v) {
485                     if (isArray(v)) {
486                         addRange(result, v);
487                     }
488                     else {
489                         result.push(v);
490                     }
491                 }
492             }
493         }
494         return result;
495     }
496     ts.flatMapToMutable = flatMapToMutable;
497     function flatMapIterator(iter, mapfn) {
498         var first = iter.next();
499         if (first.done) {
500             return ts.emptyIterator;
501         }
502         var currentIter = getIterator(first.value);
503         return {
504             next: function () {
505                 while (true) {
506                     var currentRes = currentIter.next();
507                     if (!currentRes.done) {
508                         return currentRes;
509                     }
510                     var iterRes = iter.next();
511                     if (iterRes.done) {
512                         return iterRes;
513                     }
514                     currentIter = getIterator(iterRes.value);
515                 }
516             },
517         };
518         function getIterator(x) {
519             var res = mapfn(x);
520             return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
521         }
522     }
523     ts.flatMapIterator = flatMapIterator;
524     function sameFlatMap(array, mapfn) {
525         var result;
526         if (array) {
527             for (var i = 0; i < array.length; i++) {
528                 var item = array[i];
529                 var mapped = mapfn(item, i);
530                 if (result || item !== mapped || isArray(mapped)) {
531                     if (!result) {
532                         result = array.slice(0, i);
533                     }
534                     if (isArray(mapped)) {
535                         addRange(result, mapped);
536                     }
537                     else {
538                         result.push(mapped);
539                     }
540                 }
541             }
542         }
543         return result || array;
544     }
545     ts.sameFlatMap = sameFlatMap;
546     function mapAllOrFail(array, mapFn) {
547         var result = [];
548         for (var i = 0; i < array.length; i++) {
549             var mapped = mapFn(array[i], i);
550             if (mapped === undefined) {
551                 return undefined;
552             }
553             result.push(mapped);
554         }
555         return result;
556     }
557     ts.mapAllOrFail = mapAllOrFail;
558     function mapDefined(array, mapFn) {
559         var result = [];
560         if (array) {
561             for (var i = 0; i < array.length; i++) {
562                 var mapped = mapFn(array[i], i);
563                 if (mapped !== undefined) {
564                     result.push(mapped);
565                 }
566             }
567         }
568         return result;
569     }
570     ts.mapDefined = mapDefined;
571     function mapDefinedIterator(iter, mapFn) {
572         return {
573             next: function () {
574                 while (true) {
575                     var res = iter.next();
576                     if (res.done) {
577                         return res;
578                     }
579                     var value = mapFn(res.value);
580                     if (value !== undefined) {
581                         return { value: value, done: false };
582                     }
583                 }
584             }
585         };
586     }
587     ts.mapDefinedIterator = mapDefinedIterator;
588     function mapDefinedMap(map, mapValue, mapKey) {
589         if (mapKey === void 0) { mapKey = identity; }
590         var result = createMap();
591         map.forEach(function (value, key) {
592             var mapped = mapValue(value, key);
593             if (mapped !== undefined) {
594                 result.set(mapKey(key), mapped);
595             }
596         });
597         return result;
598     }
599     ts.mapDefinedMap = mapDefinedMap;
600     ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
601     function singleIterator(value) {
602         var done = false;
603         return {
604             next: function () {
605                 var wasDone = done;
606                 done = true;
607                 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
608             }
609         };
610     }
611     ts.singleIterator = singleIterator;
612     function spanMap(array, keyfn, mapfn) {
613         var result;
614         if (array) {
615             result = [];
616             var len = array.length;
617             var previousKey = void 0;
618             var key = void 0;
619             var start = 0;
620             var pos = 0;
621             while (start < len) {
622                 while (pos < len) {
623                     var value = array[pos];
624                     key = keyfn(value, pos);
625                     if (pos === 0) {
626                         previousKey = key;
627                     }
628                     else if (key !== previousKey) {
629                         break;
630                     }
631                     pos++;
632                 }
633                 if (start < pos) {
634                     var v = mapfn(array.slice(start, pos), previousKey, start, pos);
635                     if (v) {
636                         result.push(v);
637                     }
638                     start = pos;
639                 }
640                 previousKey = key;
641                 pos++;
642             }
643         }
644         return result;
645     }
646     ts.spanMap = spanMap;
647     function mapEntries(map, f) {
648         if (!map) {
649             return undefined;
650         }
651         var result = createMap();
652         map.forEach(function (value, key) {
653             var _a = f(key, value), newKey = _a[0], newValue = _a[1];
654             result.set(newKey, newValue);
655         });
656         return result;
657     }
658     ts.mapEntries = mapEntries;
659     function some(array, predicate) {
660         if (array) {
661             if (predicate) {
662                 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
663                     var v = array_3[_i];
664                     if (predicate(v)) {
665                         return true;
666                     }
667                 }
668             }
669             else {
670                 return array.length > 0;
671             }
672         }
673         return false;
674     }
675     ts.some = some;
676     /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
677     function getRangesWhere(arr, pred, cb) {
678         var start;
679         for (var i = 0; i < arr.length; i++) {
680             if (pred(arr[i])) {
681                 start = start === undefined ? i : start;
682             }
683             else {
684                 if (start !== undefined) {
685                     cb(start, i);
686                     start = undefined;
687                 }
688             }
689         }
690         if (start !== undefined)
691             cb(start, arr.length);
692     }
693     ts.getRangesWhere = getRangesWhere;
694     function concatenate(array1, array2) {
695         if (!some(array2))
696             return array1;
697         if (!some(array1))
698             return array2;
699         return __spreadArrays(array1, array2);
700     }
701     ts.concatenate = concatenate;
702     function selectIndex(_, i) {
703         return i;
704     }
705     function indicesOf(array) {
706         return array.map(selectIndex);
707     }
708     ts.indicesOf = indicesOf;
709     function deduplicateRelational(array, equalityComparer, comparer) {
710         // Perform a stable sort of the array. This ensures the first entry in a list of
711         // duplicates remains the first entry in the result.
712         var indices = indicesOf(array);
713         stableSortIndices(array, indices, comparer);
714         var last = array[indices[0]];
715         var deduplicated = [indices[0]];
716         for (var i = 1; i < indices.length; i++) {
717             var index = indices[i];
718             var item = array[index];
719             if (!equalityComparer(last, item)) {
720                 deduplicated.push(index);
721                 last = item;
722             }
723         }
724         // restore original order
725         deduplicated.sort();
726         return deduplicated.map(function (i) { return array[i]; });
727     }
728     function deduplicateEquality(array, equalityComparer) {
729         var result = [];
730         for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
731             var item = array_4[_i];
732             pushIfUnique(result, item, equalityComparer);
733         }
734         return result;
735     }
736     /**
737      * Deduplicates an unsorted array.
738      * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
739      * @param comparer An optional `Comparer` used to sort entries before comparison, though the
740      * result will remain in the original order in `array`.
741      */
742     function deduplicate(array, equalityComparer, comparer) {
743         return array.length === 0 ? [] :
744             array.length === 1 ? array.slice() :
745                 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
746                     deduplicateEquality(array, equalityComparer);
747     }
748     ts.deduplicate = deduplicate;
749     /**
750      * Deduplicates an array that has already been sorted.
751      */
752     function deduplicateSorted(array, comparer) {
753         if (array.length === 0)
754             return ts.emptyArray;
755         var last = array[0];
756         var deduplicated = [last];
757         for (var i = 1; i < array.length; i++) {
758             var next = array[i];
759             switch (comparer(next, last)) {
760                 // equality comparison
761                 case true:
762                 // relational comparison
763                 // falls through
764                 case 0 /* EqualTo */:
765                     continue;
766                 case -1 /* LessThan */:
767                     // If `array` is sorted, `next` should **never** be less than `last`.
768                     return ts.Debug.fail("Array is unsorted.");
769             }
770             deduplicated.push(last = next);
771         }
772         return deduplicated;
773     }
774     function insertSorted(array, insert, compare) {
775         if (array.length === 0) {
776             array.push(insert);
777             return;
778         }
779         var insertIndex = binarySearch(array, insert, identity, compare);
780         if (insertIndex < 0) {
781             array.splice(~insertIndex, 0, insert);
782         }
783     }
784     ts.insertSorted = insertSorted;
785     function sortAndDeduplicate(array, comparer, equalityComparer) {
786         return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
787     }
788     ts.sortAndDeduplicate = sortAndDeduplicate;
789     function arrayIsEqualTo(array1, array2, equalityComparer) {
790         if (equalityComparer === void 0) { equalityComparer = equateValues; }
791         if (!array1 || !array2) {
792             return array1 === array2;
793         }
794         if (array1.length !== array2.length) {
795             return false;
796         }
797         for (var i = 0; i < array1.length; i++) {
798             if (!equalityComparer(array1[i], array2[i], i)) {
799                 return false;
800             }
801         }
802         return true;
803     }
804     ts.arrayIsEqualTo = arrayIsEqualTo;
805     function compact(array) {
806         var result;
807         if (array) {
808             for (var i = 0; i < array.length; i++) {
809                 var v = array[i];
810                 if (result || !v) {
811                     if (!result) {
812                         result = array.slice(0, i);
813                     }
814                     if (v) {
815                         result.push(v);
816                     }
817                 }
818             }
819         }
820         return result || array;
821     }
822     ts.compact = compact;
823     /**
824      * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
825      * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
826      * based on the provided comparer.
827      */
828     function relativeComplement(arrayA, arrayB, comparer) {
829         if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
830             return arrayB;
831         var result = [];
832         loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
833             if (offsetB > 0) {
834                 // Ensure `arrayB` is properly sorted.
835                 ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
836             }
837             loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
838                 if (offsetA > startA) {
839                     // Ensure `arrayA` is properly sorted. We only need to perform this check if
840                     // `offsetA` has changed since we entered the loop.
841                     ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
842                 }
843                 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
844                     case -1 /* LessThan */:
845                         // If B is less than A, B does not exist in arrayA. Add B to the result and
846                         // move to the next element in arrayB without changing the current position
847                         // in arrayA.
848                         result.push(arrayB[offsetB]);
849                         continue loopB;
850                     case 0 /* EqualTo */:
851                         // If B is equal to A, B exists in arrayA. Move to the next element in
852                         // arrayB without adding B to the result or changing the current position
853                         // in arrayA.
854                         continue loopB;
855                     case 1 /* GreaterThan */:
856                         // If B is greater than A, we need to keep looking for B in arrayA. Move to
857                         // the next element in arrayA and recheck.
858                         continue loopA;
859                 }
860             }
861         }
862         return result;
863     }
864     ts.relativeComplement = relativeComplement;
865     function sum(array, prop) {
866         var result = 0;
867         for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
868             var v = array_5[_i];
869             result += v[prop];
870         }
871         return result;
872     }
873     ts.sum = sum;
874     function append(to, value) {
875         if (value === undefined)
876             return to;
877         if (to === undefined)
878             return [value];
879         to.push(value);
880         return to;
881     }
882     ts.append = append;
883     function combine(xs, ys) {
884         if (xs === undefined)
885             return ys;
886         if (ys === undefined)
887             return xs;
888         if (isArray(xs))
889             return isArray(ys) ? concatenate(xs, ys) : append(xs, ys);
890         if (isArray(ys))
891             return append(ys, xs);
892         return [xs, ys];
893     }
894     ts.combine = combine;
895     /**
896      * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
897      * position offset from the end of the array.
898      */
899     function toOffset(array, offset) {
900         return offset < 0 ? array.length + offset : offset;
901     }
902     function addRange(to, from, start, end) {
903         if (from === undefined || from.length === 0)
904             return to;
905         if (to === undefined)
906             return from.slice(start, end);
907         start = start === undefined ? 0 : toOffset(from, start);
908         end = end === undefined ? from.length : toOffset(from, end);
909         for (var i = start; i < end && i < from.length; i++) {
910             if (from[i] !== undefined) {
911                 to.push(from[i]);
912             }
913         }
914         return to;
915     }
916     ts.addRange = addRange;
917     /**
918      * @return Whether the value was added.
919      */
920     function pushIfUnique(array, toAdd, equalityComparer) {
921         if (contains(array, toAdd, equalityComparer)) {
922             return false;
923         }
924         else {
925             array.push(toAdd);
926             return true;
927         }
928     }
929     ts.pushIfUnique = pushIfUnique;
930     /**
931      * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
932      */
933     function appendIfUnique(array, toAdd, equalityComparer) {
934         if (array) {
935             pushIfUnique(array, toAdd, equalityComparer);
936             return array;
937         }
938         else {
939             return [toAdd];
940         }
941     }
942     ts.appendIfUnique = appendIfUnique;
943     function stableSortIndices(array, indices, comparer) {
944         // sort indices by value then position
945         indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
946     }
947     /**
948      * Returns a new sorted array.
949      */
950     function sort(array, comparer) {
951         return (array.length === 0 ? array : array.slice().sort(comparer));
952     }
953     ts.sort = sort;
954     function arrayIterator(array) {
955         var i = 0;
956         return { next: function () {
957                 if (i === array.length) {
958                     return { value: undefined, done: true };
959                 }
960                 else {
961                     i++;
962                     return { value: array[i - 1], done: false };
963                 }
964             } };
965     }
966     ts.arrayIterator = arrayIterator;
967     function arrayReverseIterator(array) {
968         var i = array.length;
969         return {
970             next: function () {
971                 if (i === 0) {
972                     return { value: undefined, done: true };
973                 }
974                 else {
975                     i--;
976                     return { value: array[i], done: false };
977                 }
978             }
979         };
980     }
981     ts.arrayReverseIterator = arrayReverseIterator;
982     /**
983      * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
984      */
985     function stableSort(array, comparer) {
986         var indices = indicesOf(array);
987         stableSortIndices(array, indices, comparer);
988         return indices.map(function (i) { return array[i]; });
989     }
990     ts.stableSort = stableSort;
991     function rangeEquals(array1, array2, pos, end) {
992         while (pos < end) {
993             if (array1[pos] !== array2[pos]) {
994                 return false;
995             }
996             pos++;
997         }
998         return true;
999     }
1000     ts.rangeEquals = rangeEquals;
1001     /**
1002      * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
1003      * A negative offset indicates the element should be retrieved from the end of the array.
1004      */
1005     function elementAt(array, offset) {
1006         if (array) {
1007             offset = toOffset(array, offset);
1008             if (offset < array.length) {
1009                 return array[offset];
1010             }
1011         }
1012         return undefined;
1013     }
1014     ts.elementAt = elementAt;
1015     /**
1016      * Returns the first element of an array if non-empty, `undefined` otherwise.
1017      */
1018     function firstOrUndefined(array) {
1019         return array.length === 0 ? undefined : array[0];
1020     }
1021     ts.firstOrUndefined = firstOrUndefined;
1022     function first(array) {
1023         ts.Debug.assert(array.length !== 0);
1024         return array[0];
1025     }
1026     ts.first = first;
1027     /**
1028      * Returns the last element of an array if non-empty, `undefined` otherwise.
1029      */
1030     function lastOrUndefined(array) {
1031         return array.length === 0 ? undefined : array[array.length - 1];
1032     }
1033     ts.lastOrUndefined = lastOrUndefined;
1034     function last(array) {
1035         ts.Debug.assert(array.length !== 0);
1036         return array[array.length - 1];
1037     }
1038     ts.last = last;
1039     /**
1040      * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1041      */
1042     function singleOrUndefined(array) {
1043         return array && array.length === 1
1044             ? array[0]
1045             : undefined;
1046     }
1047     ts.singleOrUndefined = singleOrUndefined;
1048     function singleOrMany(array) {
1049         return array && array.length === 1
1050             ? array[0]
1051             : array;
1052     }
1053     ts.singleOrMany = singleOrMany;
1054     function replaceElement(array, index, value) {
1055         var result = array.slice(0);
1056         result[index] = value;
1057         return result;
1058     }
1059     ts.replaceElement = replaceElement;
1060     /**
1061      * Performs a binary search, finding the index at which `value` occurs in `array`.
1062      * If no such index is found, returns the 2's-complement of first index at which
1063      * `array[index]` exceeds `value`.
1064      * @param array A sorted array whose first element must be no larger than number
1065      * @param value The value to be searched for in the array.
1066      * @param keySelector A callback used to select the search key from `value` and each element of
1067      * `array`.
1068      * @param keyComparer A callback used to compare two keys in a sorted array.
1069      * @param offset An offset into `array` at which to start the search.
1070      */
1071     function binarySearch(array, value, keySelector, keyComparer, offset) {
1072         return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1073     }
1074     ts.binarySearch = binarySearch;
1075     /**
1076      * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1077      * If no such index is found, returns the 2's-complement of first index at which
1078      * `array[index]` exceeds `key`.
1079      * @param array A sorted array whose first element must be no larger than number
1080      * @param key The key to be searched for in the array.
1081      * @param keySelector A callback used to select the search key from each element of `array`.
1082      * @param keyComparer A callback used to compare two keys in a sorted array.
1083      * @param offset An offset into `array` at which to start the search.
1084      */
1085     function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1086         if (!some(array)) {
1087             return -1;
1088         }
1089         var low = offset || 0;
1090         var high = array.length - 1;
1091         while (low <= high) {
1092             var middle = low + ((high - low) >> 1);
1093             var midKey = keySelector(array[middle]);
1094             switch (keyComparer(midKey, key)) {
1095                 case -1 /* LessThan */:
1096                     low = middle + 1;
1097                     break;
1098                 case 0 /* EqualTo */:
1099                     return middle;
1100                 case 1 /* GreaterThan */:
1101                     high = middle - 1;
1102                     break;
1103             }
1104         }
1105         return ~low;
1106     }
1107     ts.binarySearchKey = binarySearchKey;
1108     function reduceLeft(array, f, initial, start, count) {
1109         if (array && array.length > 0) {
1110             var size = array.length;
1111             if (size > 0) {
1112                 var pos = start === undefined || start < 0 ? 0 : start;
1113                 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1114                 var result = void 0;
1115                 if (arguments.length <= 2) {
1116                     result = array[pos];
1117                     pos++;
1118                 }
1119                 else {
1120                     result = initial;
1121                 }
1122                 while (pos <= end) {
1123                     result = f(result, array[pos], pos);
1124                     pos++;
1125                 }
1126                 return result;
1127             }
1128         }
1129         return initial;
1130     }
1131     ts.reduceLeft = reduceLeft;
1132     var hasOwnProperty = Object.prototype.hasOwnProperty;
1133     /**
1134      * Indicates whether a map-like contains an own property with the specified key.
1135      *
1136      * @param map A map-like.
1137      * @param key A property key.
1138      */
1139     function hasProperty(map, key) {
1140         return hasOwnProperty.call(map, key);
1141     }
1142     ts.hasProperty = hasProperty;
1143     /**
1144      * Gets the value of an owned property in a map-like.
1145      *
1146      * @param map A map-like.
1147      * @param key A property key.
1148      */
1149     function getProperty(map, key) {
1150         return hasOwnProperty.call(map, key) ? map[key] : undefined;
1151     }
1152     ts.getProperty = getProperty;
1153     /**
1154      * Gets the owned, enumerable property keys of a map-like.
1155      */
1156     function getOwnKeys(map) {
1157         var keys = [];
1158         for (var key in map) {
1159             if (hasOwnProperty.call(map, key)) {
1160                 keys.push(key);
1161             }
1162         }
1163         return keys;
1164     }
1165     ts.getOwnKeys = getOwnKeys;
1166     function getAllKeys(obj) {
1167         var result = [];
1168         do {
1169             var names = Object.getOwnPropertyNames(obj);
1170             for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
1171                 var name = names_1[_i];
1172                 pushIfUnique(result, name);
1173             }
1174         } while (obj = Object.getPrototypeOf(obj));
1175         return result;
1176     }
1177     ts.getAllKeys = getAllKeys;
1178     function getOwnValues(sparseArray) {
1179         var values = [];
1180         for (var key in sparseArray) {
1181             if (hasOwnProperty.call(sparseArray, key)) {
1182                 values.push(sparseArray[key]);
1183             }
1184         }
1185         return values;
1186     }
1187     ts.getOwnValues = getOwnValues;
1188     function arrayFrom(iterator, map) {
1189         var result = [];
1190         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1191             result.push(map ? map(iterResult.value) : iterResult.value);
1192         }
1193         return result;
1194     }
1195     ts.arrayFrom = arrayFrom;
1196     function assign(t) {
1197         var args = [];
1198         for (var _i = 1; _i < arguments.length; _i++) {
1199             args[_i - 1] = arguments[_i];
1200         }
1201         for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1202             var arg = args_1[_a];
1203             if (arg === undefined)
1204                 continue;
1205             for (var p in arg) {
1206                 if (hasProperty(arg, p)) {
1207                     t[p] = arg[p];
1208                 }
1209             }
1210         }
1211         return t;
1212     }
1213     ts.assign = assign;
1214     /**
1215      * Performs a shallow equality comparison of the contents of two map-likes.
1216      *
1217      * @param left A map-like whose properties should be compared.
1218      * @param right A map-like whose properties should be compared.
1219      */
1220     function equalOwnProperties(left, right, equalityComparer) {
1221         if (equalityComparer === void 0) { equalityComparer = equateValues; }
1222         if (left === right)
1223             return true;
1224         if (!left || !right)
1225             return false;
1226         for (var key in left) {
1227             if (hasOwnProperty.call(left, key)) {
1228                 if (!hasOwnProperty.call(right, key))
1229                     return false;
1230                 if (!equalityComparer(left[key], right[key]))
1231                     return false;
1232             }
1233         }
1234         for (var key in right) {
1235             if (hasOwnProperty.call(right, key)) {
1236                 if (!hasOwnProperty.call(left, key))
1237                     return false;
1238             }
1239         }
1240         return true;
1241     }
1242     ts.equalOwnProperties = equalOwnProperties;
1243     function arrayToMap(array, makeKey, makeValue) {
1244         if (makeValue === void 0) { makeValue = identity; }
1245         var result = createMap();
1246         for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1247             var value = array_6[_i];
1248             var key = makeKey(value);
1249             if (key !== undefined)
1250                 result.set(key, makeValue(value));
1251         }
1252         return result;
1253     }
1254     ts.arrayToMap = arrayToMap;
1255     function arrayToNumericMap(array, makeKey, makeValue) {
1256         if (makeValue === void 0) { makeValue = identity; }
1257         var result = [];
1258         for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1259             var value = array_7[_i];
1260             result[makeKey(value)] = makeValue(value);
1261         }
1262         return result;
1263     }
1264     ts.arrayToNumericMap = arrayToNumericMap;
1265     function arrayToMultiMap(values, makeKey, makeValue) {
1266         if (makeValue === void 0) { makeValue = identity; }
1267         var result = createMultiMap();
1268         for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1269             var value = values_1[_i];
1270             result.add(makeKey(value), makeValue(value));
1271         }
1272         return result;
1273     }
1274     ts.arrayToMultiMap = arrayToMultiMap;
1275     function group(values, getGroupId, resultSelector) {
1276         if (resultSelector === void 0) { resultSelector = identity; }
1277         return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1278     }
1279     ts.group = group;
1280     function clone(object) {
1281         var result = {};
1282         for (var id in object) {
1283             if (hasOwnProperty.call(object, id)) {
1284                 result[id] = object[id];
1285             }
1286         }
1287         return result;
1288     }
1289     ts.clone = clone;
1290     /**
1291      * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1292      *
1293      * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1294      */
1295     function extend(first, second) {
1296         var result = {};
1297         for (var id in second) {
1298             if (hasOwnProperty.call(second, id)) {
1299                 result[id] = second[id];
1300             }
1301         }
1302         for (var id in first) {
1303             if (hasOwnProperty.call(first, id)) {
1304                 result[id] = first[id];
1305             }
1306         }
1307         return result;
1308     }
1309     ts.extend = extend;
1310     function copyProperties(first, second) {
1311         for (var id in second) {
1312             if (hasOwnProperty.call(second, id)) {
1313                 first[id] = second[id];
1314             }
1315         }
1316     }
1317     ts.copyProperties = copyProperties;
1318     function maybeBind(obj, fn) {
1319         return fn ? fn.bind(obj) : undefined;
1320     }
1321     ts.maybeBind = maybeBind;
1322     function mapMap(map, f) {
1323         var result = createMap();
1324         map.forEach(function (t, key) { return result.set.apply(result, (f(t, key))); });
1325         return result;
1326     }
1327     ts.mapMap = mapMap;
1328     function createMultiMap() {
1329         var map = createMap();
1330         map.add = multiMapAdd;
1331         map.remove = multiMapRemove;
1332         return map;
1333     }
1334     ts.createMultiMap = createMultiMap;
1335     function multiMapAdd(key, value) {
1336         var values = this.get(key);
1337         if (values) {
1338             values.push(value);
1339         }
1340         else {
1341             this.set(key, values = [value]);
1342         }
1343         return values;
1344     }
1345     function multiMapRemove(key, value) {
1346         var values = this.get(key);
1347         if (values) {
1348             unorderedRemoveItem(values, value);
1349             if (!values.length) {
1350                 this.delete(key);
1351             }
1352         }
1353     }
1354     function createUnderscoreEscapedMultiMap() {
1355         return createMultiMap();
1356     }
1357     ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1358     /**
1359      * Tests whether a value is an array.
1360      */
1361     function isArray(value) {
1362         return Array.isArray ? Array.isArray(value) : value instanceof Array;
1363     }
1364     ts.isArray = isArray;
1365     function toArray(value) {
1366         return isArray(value) ? value : [value];
1367     }
1368     ts.toArray = toArray;
1369     /**
1370      * Tests whether a value is string
1371      */
1372     function isString(text) {
1373         return typeof text === "string";
1374     }
1375     ts.isString = isString;
1376     function isNumber(x) {
1377         return typeof x === "number";
1378     }
1379     ts.isNumber = isNumber;
1380     function tryCast(value, test) {
1381         return value !== undefined && test(value) ? value : undefined;
1382     }
1383     ts.tryCast = tryCast;
1384     function cast(value, test) {
1385         if (value !== undefined && test(value))
1386             return value;
1387         return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
1388     }
1389     ts.cast = cast;
1390     /** Does nothing. */
1391     function noop(_) { }
1392     ts.noop = noop;
1393     /** Do nothing and return false */
1394     function returnFalse() { return false; }
1395     ts.returnFalse = returnFalse;
1396     /** Do nothing and return true */
1397     function returnTrue() { return true; }
1398     ts.returnTrue = returnTrue;
1399     /** Do nothing and return undefined */
1400     function returnUndefined() { return undefined; }
1401     ts.returnUndefined = returnUndefined;
1402     /** Returns its argument. */
1403     function identity(x) { return x; }
1404     ts.identity = identity;
1405     /** Returns lower case string */
1406     function toLowerCase(x) { return x.toLowerCase(); }
1407     ts.toLowerCase = toLowerCase;
1408     // We convert the file names to lower case as key for file name on case insensitive file system
1409     // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1410     // it to lower case, fileName with its lowercase form can exist along side it.
1411     // Handle special characters and make those case sensitive instead
1412     //
1413     // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1414     // | 1. | i        | 105       | Ascii i                                                                |
1415     // | 2. | I        | 73        | Ascii I                                                                |
1416     // |-------- Special characters ------------------------------------------------------------------------|
1417     // | 3. | \u0130   | 304       | Uppper case I with dot above                                           |
1418     // | 4. | i,\u0307 | 105,775   | i, followed by 775: Lower case of (3rd item)                           |
1419     // | 5. | I,\u0307 | 73,775    | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1420     // | 6. | \u0131   | 305       | Lower case i without dot, upper case is I (2nd item)                   |
1421     // | 7. | \u00DF   | 223       | Lower case sharp s                                                     |
1422     //
1423     // Because item 3 is special where in its lowercase character has its own
1424     // upper case form we cant convert its case.
1425     // Rest special characters are either already in lower case format or
1426     // they have corresponding upper case character so they dont need special handling
1427     //
1428     // But to avoid having to do string building for most common cases, also ignore
1429     // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1430     var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1431     /**
1432      * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1433      * This function is used in places where we want to make file name as a key on these systems
1434      * It is possible on mac to be able to refer to file name with I with dot on top as a fileName with its lower case form
1435      * But on windows we cannot. Windows can have fileName with I with dot on top next to its lower case and they can not each be referred with the lowercase forms
1436      * Technically we would want this function to be platform sepcific as well but
1437      * our api has till now only taken caseSensitive as the only input and just for some characters we dont want to update API and ensure all customers use those api
1438      * We could use upper case and we would still need to deal with the descripencies but
1439      * we want to continue using lower case since in most cases filenames are lowercasewe and wont need any case changes and avoid having to store another string for the key
1440      * So for this function purpose, we go ahead and assume character I with dot on top it as case sensitive since its very unlikely to use lower case form of that special character
1441      */
1442     function toFileNameLowerCase(x) {
1443         return fileNameLowerCaseRegExp.test(x) ?
1444             x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1445             x;
1446     }
1447     ts.toFileNameLowerCase = toFileNameLowerCase;
1448     /** Throws an error because a function is not implemented. */
1449     function notImplemented() {
1450         throw new Error("Not implemented");
1451     }
1452     ts.notImplemented = notImplemented;
1453     function memoize(callback) {
1454         var value;
1455         return function () {
1456             if (callback) {
1457                 value = callback();
1458                 callback = undefined;
1459             }
1460             return value;
1461         };
1462     }
1463     ts.memoize = memoize;
1464     function compose(a, b, c, d, e) {
1465         if (!!e) {
1466             var args_2 = [];
1467             for (var i = 0; i < arguments.length; i++) {
1468                 args_2[i] = arguments[i];
1469             }
1470             return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1471         }
1472         else if (d) {
1473             return function (t) { return d(c(b(a(t)))); };
1474         }
1475         else if (c) {
1476             return function (t) { return c(b(a(t))); };
1477         }
1478         else if (b) {
1479             return function (t) { return b(a(t)); };
1480         }
1481         else if (a) {
1482             return function (t) { return a(t); };
1483         }
1484         else {
1485             return function (t) { return t; };
1486         }
1487     }
1488     ts.compose = compose;
1489     var AssertionLevel;
1490     (function (AssertionLevel) {
1491         AssertionLevel[AssertionLevel["None"] = 0] = "None";
1492         AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1493         AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1494         AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1495     })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1496     function equateValues(a, b) {
1497         return a === b;
1498     }
1499     ts.equateValues = equateValues;
1500     /**
1501      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1502      *
1503      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1504      * value of each code-point after applying `toUpperCase` to each string. We always map both
1505      * strings to their upper-case form as some unicode characters do not properly round-trip to
1506      * lowercase (such as `ẞ` (German sharp capital s)).
1507      */
1508     function equateStringsCaseInsensitive(a, b) {
1509         return a === b
1510             || a !== undefined
1511                 && b !== undefined
1512                 && a.toUpperCase() === b.toUpperCase();
1513     }
1514     ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1515     /**
1516      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1517      *
1518      * Case-sensitive comparisons compare both strings one code-point at a time using the
1519      * integer value of each code-point.
1520      */
1521     function equateStringsCaseSensitive(a, b) {
1522         return equateValues(a, b);
1523     }
1524     ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1525     function compareComparableValues(a, b) {
1526         return a === b ? 0 /* EqualTo */ :
1527             a === undefined ? -1 /* LessThan */ :
1528                 b === undefined ? 1 /* GreaterThan */ :
1529                     a < b ? -1 /* LessThan */ :
1530                         1 /* GreaterThan */;
1531     }
1532     /**
1533      * Compare two numeric values for their order relative to each other.
1534      * To compare strings, use any of the `compareStrings` functions.
1535      */
1536     function compareValues(a, b) {
1537         return compareComparableValues(a, b);
1538     }
1539     ts.compareValues = compareValues;
1540     /**
1541      * Compare two TextSpans, first by `start`, then by `length`.
1542      */
1543     function compareTextSpans(a, b) {
1544         return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length);
1545     }
1546     ts.compareTextSpans = compareTextSpans;
1547     function min(a, b, compare) {
1548         return compare(a, b) === -1 /* LessThan */ ? a : b;
1549     }
1550     ts.min = min;
1551     /**
1552      * Compare two strings using a case-insensitive ordinal comparison.
1553      *
1554      * Ordinal comparisons are based on the difference between the unicode code points of both
1555      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1556      * comparisons provide predictable ordering, but place "a" after "B".
1557      *
1558      * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1559      * value of each code-point after applying `toUpperCase` to each string. We always map both
1560      * strings to their upper-case form as some unicode characters do not properly round-trip to
1561      * lowercase (such as `ẞ` (German sharp capital s)).
1562      */
1563     function compareStringsCaseInsensitive(a, b) {
1564         if (a === b)
1565             return 0 /* EqualTo */;
1566         if (a === undefined)
1567             return -1 /* LessThan */;
1568         if (b === undefined)
1569             return 1 /* GreaterThan */;
1570         a = a.toUpperCase();
1571         b = b.toUpperCase();
1572         return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1573     }
1574     ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1575     /**
1576      * Compare two strings using a case-sensitive ordinal comparison.
1577      *
1578      * Ordinal comparisons are based on the difference between the unicode code points of both
1579      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1580      * comparisons provide predictable ordering, but place "a" after "B".
1581      *
1582      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1583      * value of each code-point.
1584      */
1585     function compareStringsCaseSensitive(a, b) {
1586         return compareComparableValues(a, b);
1587     }
1588     ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1589     function getStringComparer(ignoreCase) {
1590         return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1591     }
1592     ts.getStringComparer = getStringComparer;
1593     /**
1594      * Creates a string comparer for use with string collation in the UI.
1595      */
1596     var createUIStringComparer = (function () {
1597         var defaultComparer;
1598         var enUSComparer;
1599         var stringComparerFactory = getStringComparerFactory();
1600         return createStringComparer;
1601         function compareWithCallback(a, b, comparer) {
1602             if (a === b)
1603                 return 0 /* EqualTo */;
1604             if (a === undefined)
1605                 return -1 /* LessThan */;
1606             if (b === undefined)
1607                 return 1 /* GreaterThan */;
1608             var value = comparer(a, b);
1609             return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1610         }
1611         function createIntlCollatorStringComparer(locale) {
1612             // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1613             // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1614             var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1615             return function (a, b) { return compareWithCallback(a, b, comparer); };
1616         }
1617         function createLocaleCompareStringComparer(locale) {
1618             // if the locale is not the default locale (`undefined`), use the fallback comparer.
1619             if (locale !== undefined)
1620                 return createFallbackStringComparer();
1621             return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1622             function compareStrings(a, b) {
1623                 return a.localeCompare(b);
1624             }
1625         }
1626         function createFallbackStringComparer() {
1627             // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1628             // We first sort case insensitively.  So "Aaa" will come before "baa".
1629             // Then we sort case sensitively, so "aaa" will come before "Aaa".
1630             //
1631             // For case insensitive comparisons we always map both strings to their
1632             // upper-case form as some unicode characters do not properly round-trip to
1633             // lowercase (such as `ẞ` (German sharp capital s)).
1634             return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1635             function compareDictionaryOrder(a, b) {
1636                 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1637             }
1638             function compareStrings(a, b) {
1639                 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1640             }
1641         }
1642         function getStringComparerFactory() {
1643             // If the host supports Intl, we use it for comparisons using the default locale.
1644             if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1645                 return createIntlCollatorStringComparer;
1646             }
1647             // If the host does not support Intl, we fall back to localeCompare.
1648             // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1649             if (typeof String.prototype.localeCompare === "function" &&
1650                 typeof String.prototype.toLocaleUpperCase === "function" &&
1651                 "a".localeCompare("B") < 0) {
1652                 return createLocaleCompareStringComparer;
1653             }
1654             // Otherwise, fall back to ordinal comparison:
1655             return createFallbackStringComparer;
1656         }
1657         function createStringComparer(locale) {
1658             // Hold onto common string comparers. This avoids constantly reallocating comparers during
1659             // tests.
1660             if (locale === undefined) {
1661                 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1662             }
1663             else if (locale === "en-US") {
1664                 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1665             }
1666             else {
1667                 return stringComparerFactory(locale);
1668             }
1669         }
1670     })();
1671     var uiComparerCaseSensitive;
1672     var uiLocale;
1673     function getUILocale() {
1674         return uiLocale;
1675     }
1676     ts.getUILocale = getUILocale;
1677     function setUILocale(value) {
1678         if (uiLocale !== value) {
1679             uiLocale = value;
1680             uiComparerCaseSensitive = undefined;
1681         }
1682     }
1683     ts.setUILocale = setUILocale;
1684     /**
1685      * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1686      *
1687      * Ordering is not predictable between different host locales, but is best for displaying
1688      * ordered data for UI presentation. Characters with multiple unicode representations may
1689      * be considered equal.
1690      *
1691      * Case-sensitive comparisons compare strings that differ in base characters, or
1692      * accents/diacritic marks, or case as unequal.
1693      */
1694     function compareStringsCaseSensitiveUI(a, b) {
1695         var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1696         return comparer(a, b);
1697     }
1698     ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1699     function compareProperties(a, b, key, comparer) {
1700         return a === b ? 0 /* EqualTo */ :
1701             a === undefined ? -1 /* LessThan */ :
1702                 b === undefined ? 1 /* GreaterThan */ :
1703                     comparer(a[key], b[key]);
1704     }
1705     ts.compareProperties = compareProperties;
1706     /** True is greater than false. */
1707     function compareBooleans(a, b) {
1708         return compareValues(a ? 1 : 0, b ? 1 : 0);
1709     }
1710     ts.compareBooleans = compareBooleans;
1711     /**
1712      * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
1713      * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
1714      *
1715      * If there is a candidate that's the same except for case, return that.
1716      * If there is a candidate that's within one edit of the name, return that.
1717      * Otherwise, return the candidate with the smallest Levenshtein distance,
1718      *    except for candidates:
1719      *      * With no name
1720      *      * Whose length differs from the target name by more than 0.34 of the length of the name.
1721      *      * Whose levenshtein distance is more than 0.4 of the length of the name
1722      *        (0.4 allows 1 substitution/transposition for every 5 characters,
1723      *         and 1 insertion/deletion at 3 characters)
1724      */
1725     function getSpellingSuggestion(name, candidates, getName) {
1726         var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1727         var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
1728         var bestCandidate;
1729         var justCheckExactMatches = false;
1730         var nameLowerCase = name.toLowerCase();
1731         for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1732             var candidate = candidates_1[_i];
1733             var candidateName = getName(candidate);
1734             if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
1735                 var candidateNameLowerCase = candidateName.toLowerCase();
1736                 if (candidateNameLowerCase === nameLowerCase) {
1737                     if (candidateName === name) {
1738                         continue;
1739                     }
1740                     return candidate;
1741                 }
1742                 if (justCheckExactMatches) {
1743                     continue;
1744                 }
1745                 if (candidateName.length < 3) {
1746                     // Don't bother, user would have noticed a 2-character name having an extra character
1747                     continue;
1748                 }
1749                 // Only care about a result better than the best so far.
1750                 var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
1751                 if (distance === undefined) {
1752                     continue;
1753                 }
1754                 if (distance < 3) {
1755                     justCheckExactMatches = true;
1756                     bestCandidate = candidate;
1757                 }
1758                 else {
1759                     ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1760                     bestDistance = distance;
1761                     bestCandidate = candidate;
1762                 }
1763             }
1764         }
1765         return bestCandidate;
1766     }
1767     ts.getSpellingSuggestion = getSpellingSuggestion;
1768     function levenshteinWithMax(s1, s2, max) {
1769         var previous = new Array(s2.length + 1);
1770         var current = new Array(s2.length + 1);
1771         /** Represents any value > max. We don't care about the particular value. */
1772         var big = max + 1;
1773         for (var i = 0; i <= s2.length; i++) {
1774             previous[i] = i;
1775         }
1776         for (var i = 1; i <= s1.length; i++) {
1777             var c1 = s1.charCodeAt(i - 1);
1778             var minJ = i > max ? i - max : 1;
1779             var maxJ = s2.length > max + i ? max + i : s2.length;
1780             current[0] = i;
1781             /** Smallest value of the matrix in the ith column. */
1782             var colMin = i;
1783             for (var j = 1; j < minJ; j++) {
1784                 current[j] = big;
1785             }
1786             for (var j = minJ; j <= maxJ; j++) {
1787                 var dist = c1 === s2.charCodeAt(j - 1)
1788                     ? previous[j - 1]
1789                     : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
1790                 current[j] = dist;
1791                 colMin = Math.min(colMin, dist);
1792             }
1793             for (var j = maxJ + 1; j <= s2.length; j++) {
1794                 current[j] = big;
1795             }
1796             if (colMin > max) {
1797                 // Give up -- everything in this column is > max and it can't get better in future columns.
1798                 return undefined;
1799             }
1800             var temp = previous;
1801             previous = current;
1802             current = temp;
1803         }
1804         var res = previous[s2.length];
1805         return res > max ? undefined : res;
1806     }
1807     function endsWith(str, suffix) {
1808         var expectedPos = str.length - suffix.length;
1809         return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1810     }
1811     ts.endsWith = endsWith;
1812     function removeSuffix(str, suffix) {
1813         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1814     }
1815     ts.removeSuffix = removeSuffix;
1816     function tryRemoveSuffix(str, suffix) {
1817         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1818     }
1819     ts.tryRemoveSuffix = tryRemoveSuffix;
1820     function stringContains(str, substring) {
1821         return str.indexOf(substring) !== -1;
1822     }
1823     ts.stringContains = stringContains;
1824     /**
1825      * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1826      */
1827     function removeMinAndVersionNumbers(fileName) {
1828         // Match a "." or "-" followed by a version number or 'min' at the end of the name
1829         var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1830         // The "min" or version may both be present, in either order, so try applying the above twice.
1831         return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1832     }
1833     ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1834     /** Remove an item from an array, moving everything to its right one space left. */
1835     function orderedRemoveItem(array, item) {
1836         for (var i = 0; i < array.length; i++) {
1837             if (array[i] === item) {
1838                 orderedRemoveItemAt(array, i);
1839                 return true;
1840             }
1841         }
1842         return false;
1843     }
1844     ts.orderedRemoveItem = orderedRemoveItem;
1845     /** Remove an item by index from an array, moving everything to its right one space left. */
1846     function orderedRemoveItemAt(array, index) {
1847         // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1848         for (var i = index; i < array.length - 1; i++) {
1849             array[i] = array[i + 1];
1850         }
1851         array.pop();
1852     }
1853     ts.orderedRemoveItemAt = orderedRemoveItemAt;
1854     function unorderedRemoveItemAt(array, index) {
1855         // Fill in the "hole" left at `index`.
1856         array[index] = array[array.length - 1];
1857         array.pop();
1858     }
1859     ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
1860     /** Remove the *first* occurrence of `item` from the array. */
1861     function unorderedRemoveItem(array, item) {
1862         return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
1863     }
1864     ts.unorderedRemoveItem = unorderedRemoveItem;
1865     /** Remove the *first* element satisfying `predicate`. */
1866     function unorderedRemoveFirstItemWhere(array, predicate) {
1867         for (var i = 0; i < array.length; i++) {
1868             if (predicate(array[i])) {
1869                 unorderedRemoveItemAt(array, i);
1870                 return true;
1871             }
1872         }
1873         return false;
1874     }
1875     function createGetCanonicalFileName(useCaseSensitiveFileNames) {
1876         return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
1877     }
1878     ts.createGetCanonicalFileName = createGetCanonicalFileName;
1879     function patternText(_a) {
1880         var prefix = _a.prefix, suffix = _a.suffix;
1881         return prefix + "*" + suffix;
1882     }
1883     ts.patternText = patternText;
1884     /**
1885      * Given that candidate matches pattern, returns the text matching the '*'.
1886      * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
1887      */
1888     function matchedText(pattern, candidate) {
1889         ts.Debug.assert(isPatternMatch(pattern, candidate));
1890         return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
1891     }
1892     ts.matchedText = matchedText;
1893     /** Return the object corresponding to the best pattern to match `candidate`. */
1894     function findBestPatternMatch(values, getPattern, candidate) {
1895         var matchedValue;
1896         // use length of prefix as betterness criteria
1897         var longestMatchPrefixLength = -1;
1898         for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
1899             var v = values_2[_i];
1900             var pattern = getPattern(v);
1901             if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
1902                 longestMatchPrefixLength = pattern.prefix.length;
1903                 matchedValue = v;
1904             }
1905         }
1906         return matchedValue;
1907     }
1908     ts.findBestPatternMatch = findBestPatternMatch;
1909     function startsWith(str, prefix) {
1910         return str.lastIndexOf(prefix, 0) === 0;
1911     }
1912     ts.startsWith = startsWith;
1913     function removePrefix(str, prefix) {
1914         return startsWith(str, prefix) ? str.substr(prefix.length) : str;
1915     }
1916     ts.removePrefix = removePrefix;
1917     function tryRemovePrefix(str, prefix, getCanonicalFileName) {
1918         if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
1919         return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
1920     }
1921     ts.tryRemovePrefix = tryRemovePrefix;
1922     function isPatternMatch(_a, candidate) {
1923         var prefix = _a.prefix, suffix = _a.suffix;
1924         return candidate.length >= prefix.length + suffix.length &&
1925             startsWith(candidate, prefix) &&
1926             endsWith(candidate, suffix);
1927     }
1928     function and(f, g) {
1929         return function (arg) { return f(arg) && g(arg); };
1930     }
1931     ts.and = and;
1932     function or() {
1933         var fs = [];
1934         for (var _i = 0; _i < arguments.length; _i++) {
1935             fs[_i] = arguments[_i];
1936         }
1937         return function () {
1938             var args = [];
1939             for (var _i = 0; _i < arguments.length; _i++) {
1940                 args[_i] = arguments[_i];
1941             }
1942             for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
1943                 var f = fs_1[_a];
1944                 if (f.apply(void 0, args)) {
1945                     return true;
1946                 }
1947             }
1948             return false;
1949         };
1950     }
1951     ts.or = or;
1952     function not(fn) {
1953         return function () {
1954             var args = [];
1955             for (var _i = 0; _i < arguments.length; _i++) {
1956                 args[_i] = arguments[_i];
1957             }
1958             return !fn.apply(void 0, args);
1959         };
1960     }
1961     ts.not = not;
1962     function assertType(_) { }
1963     ts.assertType = assertType;
1964     function singleElementArray(t) {
1965         return t === undefined ? undefined : [t];
1966     }
1967     ts.singleElementArray = singleElementArray;
1968     function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
1969         unchanged = unchanged || noop;
1970         var newIndex = 0;
1971         var oldIndex = 0;
1972         var newLen = newItems.length;
1973         var oldLen = oldItems.length;
1974         while (newIndex < newLen && oldIndex < oldLen) {
1975             var newItem = newItems[newIndex];
1976             var oldItem = oldItems[oldIndex];
1977             var compareResult = comparer(newItem, oldItem);
1978             if (compareResult === -1 /* LessThan */) {
1979                 inserted(newItem);
1980                 newIndex++;
1981             }
1982             else if (compareResult === 1 /* GreaterThan */) {
1983                 deleted(oldItem);
1984                 oldIndex++;
1985             }
1986             else {
1987                 unchanged(oldItem, newItem);
1988                 newIndex++;
1989                 oldIndex++;
1990             }
1991         }
1992         while (newIndex < newLen) {
1993             inserted(newItems[newIndex++]);
1994         }
1995         while (oldIndex < oldLen) {
1996             deleted(oldItems[oldIndex++]);
1997         }
1998     }
1999     ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
2000     function fill(length, cb) {
2001         var result = Array(length);
2002         for (var i = 0; i < length; i++) {
2003             result[i] = cb(i);
2004         }
2005         return result;
2006     }
2007     ts.fill = fill;
2008     function cartesianProduct(arrays) {
2009         var result = [];
2010         cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2011         return result;
2012     }
2013     ts.cartesianProduct = cartesianProduct;
2014     function cartesianProductWorker(arrays, result, outer, index) {
2015         for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2016             var element = _a[_i];
2017             var inner = void 0;
2018             if (outer) {
2019                 inner = outer.slice();
2020                 inner.push(element);
2021             }
2022             else {
2023                 inner = [element];
2024             }
2025             if (index === arrays.length - 1) {
2026                 result.push(inner);
2027             }
2028             else {
2029                 cartesianProductWorker(arrays, result, inner, index + 1);
2030             }
2031         }
2032     }
2033     function padLeft(s, length) {
2034         while (s.length < length) {
2035             s = " " + s;
2036         }
2037         return s;
2038     }
2039     ts.padLeft = padLeft;
2040     function padRight(s, length) {
2041         while (s.length < length) {
2042             s = s + " ";
2043         }
2044         return s;
2045     }
2046     ts.padRight = padRight;
2047 })(ts || (ts = {}));
2048 /* @internal */
2049 var ts;
2050 (function (ts) {
2051     var Debug;
2052     (function (Debug) {
2053         var currentAssertionLevel = 0 /* None */;
2054         // eslint-disable-next-line prefer-const
2055         Debug.isDebugging = false;
2056         var assertionCache = {};
2057         function getAssertionLevel() {
2058             return currentAssertionLevel;
2059         }
2060         Debug.getAssertionLevel = getAssertionLevel;
2061         function setAssertionLevel(level) {
2062             var prevAssertionLevel = currentAssertionLevel;
2063             currentAssertionLevel = level;
2064             if (level > prevAssertionLevel) {
2065                 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2066                 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2067                     var key = _a[_i];
2068                     var cachedFunc = assertionCache[key];
2069                     if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2070                         Debug[key] = cachedFunc;
2071                         assertionCache[key] = undefined;
2072                     }
2073                 }
2074             }
2075         }
2076         Debug.setAssertionLevel = setAssertionLevel;
2077         function shouldAssert(level) {
2078             return currentAssertionLevel >= level;
2079         }
2080         Debug.shouldAssert = shouldAssert;
2081         /**
2082          * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2083          * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2084          * @param level The minimum assertion level required.
2085          * @param name The name of the current assertion function.
2086          */
2087         function shouldAssertFunction(level, name) {
2088             if (!shouldAssert(level)) {
2089                 assertionCache[name] = { level: level, assertion: Debug[name] };
2090                 Debug[name] = ts.noop;
2091                 return false;
2092             }
2093             return true;
2094         }
2095         function fail(message, stackCrawlMark) {
2096             debugger;
2097             var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
2098             if (Error.captureStackTrace) {
2099                 Error.captureStackTrace(e, stackCrawlMark || fail);
2100             }
2101             throw e;
2102         }
2103         Debug.fail = fail;
2104         function failBadSyntaxKind(node, message, stackCrawlMark) {
2105             return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
2106         }
2107         Debug.failBadSyntaxKind = failBadSyntaxKind;
2108         function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2109             if (!expression) {
2110                 message = message ? "False expression: " + message : "False expression.";
2111                 if (verboseDebugInfo) {
2112                     message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2113                 }
2114                 fail(message, stackCrawlMark || assert);
2115             }
2116         }
2117         Debug.assert = assert;
2118         function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2119             if (a !== b) {
2120                 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
2121                 fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
2122             }
2123         }
2124         Debug.assertEqual = assertEqual;
2125         function assertLessThan(a, b, msg, stackCrawlMark) {
2126             if (a >= b) {
2127                 fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
2128             }
2129         }
2130         Debug.assertLessThan = assertLessThan;
2131         function assertLessThanOrEqual(a, b, stackCrawlMark) {
2132             if (a > b) {
2133                 fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
2134             }
2135         }
2136         Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2137         function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2138             if (a < b) {
2139                 fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
2140             }
2141         }
2142         Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2143         function assertIsDefined(value, message, stackCrawlMark) {
2144             // eslint-disable-next-line no-null/no-null
2145             if (value === undefined || value === null) {
2146                 fail(message, stackCrawlMark || assertIsDefined);
2147             }
2148         }
2149         Debug.assertIsDefined = assertIsDefined;
2150         function checkDefined(value, message, stackCrawlMark) {
2151             assertIsDefined(value, message, stackCrawlMark || checkDefined);
2152             return value;
2153         }
2154         Debug.checkDefined = checkDefined;
2155         /**
2156          * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2157          * a value is defined at the statement level.
2158          */
2159         Debug.assertDefined = checkDefined;
2160         function assertEachIsDefined(value, message, stackCrawlMark) {
2161             for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2162                 var v = value_1[_i];
2163                 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2164             }
2165         }
2166         Debug.assertEachIsDefined = assertEachIsDefined;
2167         function checkEachDefined(value, message, stackCrawlMark) {
2168             assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2169             return value;
2170         }
2171         Debug.checkEachDefined = checkEachDefined;
2172         /**
2173          * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2174          * the elements of an array are defined at the statement level.
2175          */
2176         Debug.assertEachDefined = checkEachDefined;
2177         function assertNever(member, message, stackCrawlMark) {
2178             if (message === void 0) { message = "Illegal value:"; }
2179             var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2180             return fail(message + " " + detail, stackCrawlMark || assertNever);
2181         }
2182         Debug.assertNever = assertNever;
2183         function assertEachNode(nodes, test, message, stackCrawlMark) {
2184             if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2185                 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
2186             }
2187         }
2188         Debug.assertEachNode = assertEachNode;
2189         function assertNode(node, test, message, stackCrawlMark) {
2190             if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2191                 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
2192             }
2193         }
2194         Debug.assertNode = assertNode;
2195         function assertNotNode(node, test, message, stackCrawlMark) {
2196             if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2197                 assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " should not have passed test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNotNode);
2198             }
2199         }
2200         Debug.assertNotNode = assertNotNode;
2201         function assertOptionalNode(node, test, message, stackCrawlMark) {
2202             if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2203                 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
2204             }
2205         }
2206         Debug.assertOptionalNode = assertOptionalNode;
2207         function assertOptionalToken(node, kind, message, stackCrawlMark) {
2208             if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2209                 assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was not a '" + formatSyntaxKind(kind) + "' token."; }, stackCrawlMark || assertOptionalToken);
2210             }
2211         }
2212         Debug.assertOptionalToken = assertOptionalToken;
2213         function assertMissingNode(node, message, stackCrawlMark) {
2214             if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2215                 assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
2216             }
2217         }
2218         Debug.assertMissingNode = assertMissingNode;
2219         function getFunctionName(func) {
2220             if (typeof func !== "function") {
2221                 return "";
2222             }
2223             else if (func.hasOwnProperty("name")) {
2224                 return func.name;
2225             }
2226             else {
2227                 var text = Function.prototype.toString.call(func);
2228                 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2229                 return match ? match[1] : "";
2230             }
2231         }
2232         Debug.getFunctionName = getFunctionName;
2233         function formatSymbol(symbol) {
2234             return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
2235         }
2236         Debug.formatSymbol = formatSymbol;
2237         /**
2238          * Formats an enum value as a string for debugging and debug assertions.
2239          */
2240         function formatEnum(value, enumObject, isFlags) {
2241             if (value === void 0) { value = 0; }
2242             var members = getEnumMembers(enumObject);
2243             if (value === 0) {
2244                 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2245             }
2246             if (isFlags) {
2247                 var result = "";
2248                 var remainingFlags = value;
2249                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2250                     var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2251                     if (enumValue > value) {
2252                         break;
2253                     }
2254                     if (enumValue !== 0 && enumValue & value) {
2255                         result = "" + result + (result ? "|" : "") + enumName;
2256                         remainingFlags &= ~enumValue;
2257                     }
2258                 }
2259                 if (remainingFlags === 0) {
2260                     return result;
2261                 }
2262             }
2263             else {
2264                 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2265                     var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2266                     if (enumValue === value) {
2267                         return enumName;
2268                     }
2269                 }
2270             }
2271             return value.toString();
2272         }
2273         Debug.formatEnum = formatEnum;
2274         function getEnumMembers(enumObject) {
2275             var result = [];
2276             for (var name in enumObject) {
2277                 var value = enumObject[name];
2278                 if (typeof value === "number") {
2279                     result.push([value, name]);
2280                 }
2281             }
2282             return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2283         }
2284         function formatSyntaxKind(kind) {
2285             return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2286         }
2287         Debug.formatSyntaxKind = formatSyntaxKind;
2288         function formatNodeFlags(flags) {
2289             return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2290         }
2291         Debug.formatNodeFlags = formatNodeFlags;
2292         function formatModifierFlags(flags) {
2293             return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2294         }
2295         Debug.formatModifierFlags = formatModifierFlags;
2296         function formatTransformFlags(flags) {
2297             return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2298         }
2299         Debug.formatTransformFlags = formatTransformFlags;
2300         function formatEmitFlags(flags) {
2301             return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2302         }
2303         Debug.formatEmitFlags = formatEmitFlags;
2304         function formatSymbolFlags(flags) {
2305             return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2306         }
2307         Debug.formatSymbolFlags = formatSymbolFlags;
2308         function formatTypeFlags(flags) {
2309             return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2310         }
2311         Debug.formatTypeFlags = formatTypeFlags;
2312         function formatObjectFlags(flags) {
2313             return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2314         }
2315         Debug.formatObjectFlags = formatObjectFlags;
2316         var isDebugInfoEnabled = false;
2317         var extendedDebugModule;
2318         function extendedDebug() {
2319             enableDebugInfo();
2320             if (!extendedDebugModule) {
2321                 throw new Error("Debugging helpers could not be loaded.");
2322             }
2323             return extendedDebugModule;
2324         }
2325         function printControlFlowGraph(flowNode) {
2326             return console.log(formatControlFlowGraph(flowNode));
2327         }
2328         Debug.printControlFlowGraph = printControlFlowGraph;
2329         function formatControlFlowGraph(flowNode) {
2330             return extendedDebug().formatControlFlowGraph(flowNode);
2331         }
2332         Debug.formatControlFlowGraph = formatControlFlowGraph;
2333         function attachFlowNodeDebugInfo(flowNode) {
2334             if (isDebugInfoEnabled) {
2335                 if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2336                     Object.defineProperties(flowNode, {
2337                         __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2338                         __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2339                     });
2340                 }
2341             }
2342         }
2343         Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2344         /**
2345          * Injects debug information into frequently used types.
2346          */
2347         function enableDebugInfo() {
2348             if (isDebugInfoEnabled)
2349                 return;
2350             // Add additional properties in debug mode to assist with debugging.
2351             Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2352                 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2353             });
2354             Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2355                 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2356                 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2357                 __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
2358             });
2359             var nodeConstructors = [
2360                 ts.objectAllocator.getNodeConstructor(),
2361                 ts.objectAllocator.getIdentifierConstructor(),
2362                 ts.objectAllocator.getTokenConstructor(),
2363                 ts.objectAllocator.getSourceFileConstructor()
2364             ];
2365             for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2366                 var ctor = nodeConstructors_1[_i];
2367                 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2368                     Object.defineProperties(ctor.prototype, {
2369                         __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2370                         __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2371                         __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getModifierFlagsNoCache(this)); } },
2372                         __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2373                         __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2374                         __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2375                         __debugGetText: {
2376                             value: function (includeTrivia) {
2377                                 if (ts.nodeIsSynthesized(this))
2378                                     return "";
2379                                 var parseNode = ts.getParseTreeNode(this);
2380                                 var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2381                                 return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2382                             }
2383                         }
2384                     });
2385                 }
2386             }
2387             // attempt to load extended debugging information
2388             try {
2389                 if (ts.sys && ts.sys.require) {
2390                     var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2391                     var result = ts.sys.require(basePath, "./compiler-debug");
2392                     if (!result.error) {
2393                         result.module.init(ts);
2394                         extendedDebugModule = result.module;
2395                     }
2396                 }
2397             }
2398             catch (_a) {
2399                 // do nothing
2400             }
2401             isDebugInfoEnabled = true;
2402         }
2403         Debug.enableDebugInfo = enableDebugInfo;
2404     })(Debug = ts.Debug || (ts.Debug = {}));
2405 })(ts || (ts = {}));
2406 /*@internal*/
2407 var ts;
2408 (function (ts) {
2409     /** Gets a timestamp with (at least) ms resolution */
2410     ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
2411 })(ts || (ts = {}));
2412 /*@internal*/
2413 /** Performance measurements for the compiler. */
2414 var ts;
2415 (function (ts) {
2416     var performance;
2417     (function (performance) {
2418         // NOTE: cannot use ts.noop as core.ts loads after this
2419         var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
2420         var enabled = false;
2421         var profilerStart = 0;
2422         var counts;
2423         var marks;
2424         var measures;
2425         function createTimerIf(condition, measureName, startMarkName, endMarkName) {
2426             return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
2427         }
2428         performance.createTimerIf = createTimerIf;
2429         function createTimer(measureName, startMarkName, endMarkName) {
2430             var enterCount = 0;
2431             return {
2432                 enter: enter,
2433                 exit: exit
2434             };
2435             function enter() {
2436                 if (++enterCount === 1) {
2437                     mark(startMarkName);
2438                 }
2439             }
2440             function exit() {
2441                 if (--enterCount === 0) {
2442                     mark(endMarkName);
2443                     measure(measureName, startMarkName, endMarkName);
2444                 }
2445                 else if (enterCount < 0) {
2446                     ts.Debug.fail("enter/exit count does not match.");
2447                 }
2448             }
2449         }
2450         performance.createTimer = createTimer;
2451         performance.nullTimer = { enter: ts.noop, exit: ts.noop };
2452         /**
2453          * Marks a performance event.
2454          *
2455          * @param markName The name of the mark.
2456          */
2457         function mark(markName) {
2458             if (enabled) {
2459                 marks.set(markName, ts.timestamp());
2460                 counts.set(markName, (counts.get(markName) || 0) + 1);
2461                 profilerEvent(markName);
2462             }
2463         }
2464         performance.mark = mark;
2465         /**
2466          * Adds a performance measurement with the specified name.
2467          *
2468          * @param measureName The name of the performance measurement.
2469          * @param startMarkName The name of the starting mark. If not supplied, the point at which the
2470          *      profiler was enabled is used.
2471          * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
2472          *      used.
2473          */
2474         function measure(measureName, startMarkName, endMarkName) {
2475             if (enabled) {
2476                 var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
2477                 var start = startMarkName && marks.get(startMarkName) || profilerStart;
2478                 measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
2479             }
2480         }
2481         performance.measure = measure;
2482         /**
2483          * Gets the number of times a marker was encountered.
2484          *
2485          * @param markName The name of the mark.
2486          */
2487         function getCount(markName) {
2488             return counts && counts.get(markName) || 0;
2489         }
2490         performance.getCount = getCount;
2491         /**
2492          * Gets the total duration of all measurements with the supplied name.
2493          *
2494          * @param measureName The name of the measure whose durations should be accumulated.
2495          */
2496         function getDuration(measureName) {
2497             return measures && measures.get(measureName) || 0;
2498         }
2499         performance.getDuration = getDuration;
2500         /**
2501          * Iterate over each measure, performing some action
2502          *
2503          * @param cb The action to perform for each measure
2504          */
2505         function forEachMeasure(cb) {
2506             measures.forEach(function (measure, key) {
2507                 cb(key, measure);
2508             });
2509         }
2510         performance.forEachMeasure = forEachMeasure;
2511         /** Enables (and resets) performance measurements for the compiler. */
2512         function enable() {
2513             counts = ts.createMap();
2514             marks = ts.createMap();
2515             measures = ts.createMap();
2516             enabled = true;
2517             profilerStart = ts.timestamp();
2518         }
2519         performance.enable = enable;
2520         /** Disables performance measurements for the compiler. */
2521         function disable() {
2522             enabled = false;
2523         }
2524         performance.disable = disable;
2525     })(performance = ts.performance || (ts.performance = {}));
2526 })(ts || (ts = {}));
2527 /* @internal */
2528 var ts;
2529 (function (ts) {
2530     var nullLogger = {
2531         logEvent: ts.noop,
2532         logErrEvent: ts.noop,
2533         logPerfEvent: ts.noop,
2534         logInfoEvent: ts.noop,
2535         logStartCommand: ts.noop,
2536         logStopCommand: ts.noop,
2537         logStartUpdateProgram: ts.noop,
2538         logStopUpdateProgram: ts.noop,
2539         logStartUpdateGraph: ts.noop,
2540         logStopUpdateGraph: ts.noop,
2541         logStartResolveModule: ts.noop,
2542         logStopResolveModule: ts.noop,
2543         logStartParseSourceFile: ts.noop,
2544         logStopParseSourceFile: ts.noop,
2545         logStartReadFile: ts.noop,
2546         logStopReadFile: ts.noop,
2547         logStartBindFile: ts.noop,
2548         logStopBindFile: ts.noop,
2549         logStartScheduledOperation: ts.noop,
2550         logStopScheduledOperation: ts.noop,
2551     };
2552     // Load optional module to enable Event Tracing for Windows
2553     // See https://github.com/microsoft/typescript-etw for more information
2554     var etwModule;
2555     try {
2556         // require() will throw an exception if the module is not installed
2557         // It may also return undefined if not installed properly
2558         etwModule = require("@microsoft/typescript-etw");
2559     }
2560     catch (e) {
2561         etwModule = undefined;
2562     }
2563     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
2564     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
2565 })(ts || (ts = {}));
2566 /* @internal */
2567 var ts;
2568 (function (ts) {
2569     // https://semver.org/#spec-item-2
2570     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2571     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2572     // > version, and Z is the patch version. Each element MUST increase numerically.
2573     //
2574     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2575     // value of `0`.
2576     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2577     // https://semver.org/#spec-item-9
2578     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2579     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2580     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2581     // > MUST NOT include leading zeroes.
2582     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2583     // https://semver.org/#spec-item-10
2584     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2585     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2586     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2587     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2588     // https://semver.org/#spec-item-9
2589     // > Numeric identifiers MUST NOT include leading zeroes.
2590     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2591     /**
2592      * Describes a precise semantic version number, https://semver.org
2593      */
2594     var Version = /** @class */ (function () {
2595         function Version(major, minor, patch, prerelease, build) {
2596             if (minor === void 0) { minor = 0; }
2597             if (patch === void 0) { patch = 0; }
2598             if (prerelease === void 0) { prerelease = ""; }
2599             if (build === void 0) { build = ""; }
2600             if (typeof major === "string") {
2601                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2602                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2603             }
2604             ts.Debug.assert(major >= 0, "Invalid argument: major");
2605             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2606             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2607             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2608             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2609             this.major = major;
2610             this.minor = minor;
2611             this.patch = patch;
2612             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2613             this.build = build ? build.split(".") : ts.emptyArray;
2614         }
2615         Version.tryParse = function (text) {
2616             var result = tryParseComponents(text);
2617             if (!result)
2618                 return undefined;
2619             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2620             return new Version(major, minor, patch, prerelease, build);
2621         };
2622         Version.prototype.compareTo = function (other) {
2623             // https://semver.org/#spec-item-11
2624             // > Precedence is determined by the first difference when comparing each of these
2625             // > identifiers from left to right as follows: Major, minor, and patch versions are
2626             // > always compared numerically.
2627             //
2628             // https://semver.org/#spec-item-11
2629             // > Precedence for two pre-release versions with the same major, minor, and patch version
2630             // > MUST be determined by comparing each dot separated identifier from left to right until
2631             // > a difference is found [...]
2632             //
2633             // https://semver.org/#spec-item-11
2634             // > Build metadata does not figure into precedence
2635             if (this === other)
2636                 return 0 /* EqualTo */;
2637             if (other === undefined)
2638                 return 1 /* GreaterThan */;
2639             return ts.compareValues(this.major, other.major)
2640                 || ts.compareValues(this.minor, other.minor)
2641                 || ts.compareValues(this.patch, other.patch)
2642                 || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
2643         };
2644         Version.prototype.increment = function (field) {
2645             switch (field) {
2646                 case "major": return new Version(this.major + 1, 0, 0);
2647                 case "minor": return new Version(this.major, this.minor + 1, 0);
2648                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2649                 default: return ts.Debug.assertNever(field);
2650             }
2651         };
2652         Version.prototype.toString = function () {
2653             var result = this.major + "." + this.minor + "." + this.patch;
2654             if (ts.some(this.prerelease))
2655                 result += "-" + this.prerelease.join(".");
2656             if (ts.some(this.build))
2657                 result += "+" + this.build.join(".");
2658             return result;
2659         };
2660         Version.zero = new Version(0, 0, 0);
2661         return Version;
2662     }());
2663     ts.Version = Version;
2664     function tryParseComponents(text) {
2665         var match = versionRegExp.exec(text);
2666         if (!match)
2667             return undefined;
2668         var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d;
2669         if (prerelease && !prereleaseRegExp.test(prerelease))
2670             return undefined;
2671         if (build && !buildRegExp.test(build))
2672             return undefined;
2673         return {
2674             major: parseInt(major, 10),
2675             minor: parseInt(minor, 10),
2676             patch: parseInt(patch, 10),
2677             prerelease: prerelease,
2678             build: build
2679         };
2680     }
2681     function comparePrerelaseIdentifiers(left, right) {
2682         // https://semver.org/#spec-item-11
2683         // > When major, minor, and patch are equal, a pre-release version has lower precedence
2684         // > than a normal version.
2685         if (left === right)
2686             return 0 /* EqualTo */;
2687         if (left.length === 0)
2688             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2689         if (right.length === 0)
2690             return -1 /* LessThan */;
2691         // https://semver.org/#spec-item-11
2692         // > Precedence for two pre-release versions with the same major, minor, and patch version
2693         // > MUST be determined by comparing each dot separated identifier from left to right until
2694         // > a difference is found [...]
2695         var length = Math.min(left.length, right.length);
2696         for (var i = 0; i < length; i++) {
2697             var leftIdentifier = left[i];
2698             var rightIdentifier = right[i];
2699             if (leftIdentifier === rightIdentifier)
2700                 continue;
2701             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2702             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2703             if (leftIsNumeric || rightIsNumeric) {
2704                 // https://semver.org/#spec-item-11
2705                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2706                 if (leftIsNumeric !== rightIsNumeric)
2707                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2708                 // https://semver.org/#spec-item-11
2709                 // > identifiers consisting of only digits are compared numerically
2710                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2711                 if (result)
2712                     return result;
2713             }
2714             else {
2715                 // https://semver.org/#spec-item-11
2716                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2717                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2718                 if (result)
2719                     return result;
2720             }
2721         }
2722         // https://semver.org/#spec-item-11
2723         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2724         // > of the preceding identifiers are equal.
2725         return ts.compareValues(left.length, right.length);
2726     }
2727     /**
2728      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2729      */
2730     var VersionRange = /** @class */ (function () {
2731         function VersionRange(spec) {
2732             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2733         }
2734         VersionRange.tryParse = function (text) {
2735             var sets = parseRange(text);
2736             if (sets) {
2737                 var range = new VersionRange("");
2738                 range._alternatives = sets;
2739                 return range;
2740             }
2741             return undefined;
2742         };
2743         VersionRange.prototype.test = function (version) {
2744             if (typeof version === "string")
2745                 version = new Version(version);
2746             return testDisjunction(version, this._alternatives);
2747         };
2748         VersionRange.prototype.toString = function () {
2749             return formatDisjunction(this._alternatives);
2750         };
2751         return VersionRange;
2752     }());
2753     ts.VersionRange = VersionRange;
2754     // https://github.com/npm/node-semver#range-grammar
2755     //
2756     // range-set    ::= range ( logical-or range ) *
2757     // range        ::= hyphen | simple ( ' ' simple ) * | ''
2758     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
2759     var logicalOrRegExp = /\s*\|\|\s*/g;
2760     var whitespaceRegExp = /\s+/g;
2761     // https://github.com/npm/node-semver#range-grammar
2762     //
2763     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
2764     // xr           ::= 'x' | 'X' | '*' | nr
2765     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
2766     // qualifier    ::= ( '-' pre )? ( '+' build )?
2767     // pre          ::= parts
2768     // build        ::= parts
2769     // parts        ::= part ( '.' part ) *
2770     // part         ::= nr | [-0-9A-Za-z]+
2771     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2772     // https://github.com/npm/node-semver#range-grammar
2773     //
2774     // hyphen       ::= partial ' - ' partial
2775     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
2776     // https://github.com/npm/node-semver#range-grammar
2777     //
2778     // simple       ::= primitive | partial | tilde | caret
2779     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
2780     // tilde        ::= '~' partial
2781     // caret        ::= '^' partial
2782     var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
2783     function parseRange(text) {
2784         var alternatives = [];
2785         for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
2786             var range = _a[_i];
2787             if (!range)
2788                 continue;
2789             var comparators = [];
2790             var match = hyphenRegExp.exec(range);
2791             if (match) {
2792                 if (!parseHyphen(match[1], match[2], comparators))
2793                     return undefined;
2794             }
2795             else {
2796                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
2797                     var simple = _c[_b];
2798                     var match_1 = rangeRegExp.exec(simple);
2799                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
2800                         return undefined;
2801                 }
2802             }
2803             alternatives.push(comparators);
2804         }
2805         return alternatives;
2806     }
2807     function parsePartial(text) {
2808         var match = partialRegExp.exec(text);
2809         if (!match)
2810             return undefined;
2811         var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5];
2812         var version = 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, build);
2813         return { version: version, major: major, minor: minor, patch: patch };
2814     }
2815     function parseHyphen(left, right, comparators) {
2816         var leftResult = parsePartial(left);
2817         if (!leftResult)
2818             return false;
2819         var rightResult = parsePartial(right);
2820         if (!rightResult)
2821             return false;
2822         if (!isWildcard(leftResult.major)) {
2823             comparators.push(createComparator(">=", leftResult.version));
2824         }
2825         if (!isWildcard(rightResult.major)) {
2826             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
2827                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
2828                     createComparator("<=", rightResult.version));
2829         }
2830         return true;
2831     }
2832     function parseComparator(operator, text, comparators) {
2833         var result = parsePartial(text);
2834         if (!result)
2835             return false;
2836         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
2837         if (!isWildcard(major)) {
2838             switch (operator) {
2839                 case "~":
2840                     comparators.push(createComparator(">=", version));
2841                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
2842                         "minor")));
2843                     break;
2844                 case "^":
2845                     comparators.push(createComparator(">=", version));
2846                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
2847                         version.minor > 0 || isWildcard(patch) ? "minor" :
2848                             "patch")));
2849                     break;
2850                 case "<":
2851                 case ">=":
2852                     comparators.push(createComparator(operator, version));
2853                     break;
2854                 case "<=":
2855                 case ">":
2856                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
2857                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
2858                             createComparator(operator, version));
2859                     break;
2860                 case "=":
2861                 case undefined:
2862                     if (isWildcard(minor) || isWildcard(patch)) {
2863                         comparators.push(createComparator(">=", version));
2864                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
2865                     }
2866                     else {
2867                         comparators.push(createComparator("=", version));
2868                     }
2869                     break;
2870                 default:
2871                     // unrecognized
2872                     return false;
2873             }
2874         }
2875         else if (operator === "<" || operator === ">") {
2876             comparators.push(createComparator("<", Version.zero));
2877         }
2878         return true;
2879     }
2880     function isWildcard(part) {
2881         return part === "*" || part === "x" || part === "X";
2882     }
2883     function createComparator(operator, operand) {
2884         return { operator: operator, operand: operand };
2885     }
2886     function testDisjunction(version, alternatives) {
2887         // an empty disjunction is treated as "*" (all versions)
2888         if (alternatives.length === 0)
2889             return true;
2890         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
2891             var alternative = alternatives_1[_i];
2892             if (testAlternative(version, alternative))
2893                 return true;
2894         }
2895         return false;
2896     }
2897     function testAlternative(version, comparators) {
2898         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
2899             var comparator = comparators_1[_i];
2900             if (!testComparator(version, comparator.operator, comparator.operand))
2901                 return false;
2902         }
2903         return true;
2904     }
2905     function testComparator(version, operator, operand) {
2906         var cmp = version.compareTo(operand);
2907         switch (operator) {
2908             case "<": return cmp < 0;
2909             case "<=": return cmp <= 0;
2910             case ">": return cmp > 0;
2911             case ">=": return cmp >= 0;
2912             case "=": return cmp === 0;
2913             default: return ts.Debug.assertNever(operator);
2914         }
2915     }
2916     function formatDisjunction(alternatives) {
2917         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
2918     }
2919     function formatAlternative(comparators) {
2920         return ts.map(comparators, formatComparator).join(" ");
2921     }
2922     function formatComparator(comparator) {
2923         return "" + comparator.operator + comparator.operand;
2924     }
2925 })(ts || (ts = {}));
2926 var ts;
2927 (function (ts) {
2928     // token > SyntaxKind.Identifier => token is a keyword
2929     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
2930     var SyntaxKind;
2931     (function (SyntaxKind) {
2932         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
2933         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
2934         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
2935         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
2936         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
2937         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
2938         // We detect and preserve #! on the first line
2939         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
2940         // We detect and provide better error recovery when we encounter a git merge marker.  This
2941         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
2942         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
2943         // Literals
2944         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
2945         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
2946         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
2947         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
2948         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
2949         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
2950         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
2951         // Pseudo-literals
2952         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
2953         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
2954         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
2955         // Punctuation
2956         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
2957         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
2958         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
2959         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
2960         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
2961         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
2962         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
2963         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
2964         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
2965         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
2966         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
2967         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
2968         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
2969         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
2970         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
2971         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
2972         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
2973         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
2974         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
2975         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
2976         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
2977         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
2978         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
2979         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
2980         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
2981         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
2982         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
2983         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
2984         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
2985         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
2986         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
2987         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
2988         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
2989         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
2990         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
2991         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
2992         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
2993         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
2994         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
2995         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
2996         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
2997         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
2998         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
2999         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
3000         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
3001         // Assignments
3002         SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
3003         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
3004         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
3005         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
3006         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
3007         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
3008         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
3009         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
3010         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3011         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3012         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3013         SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3014         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 74] = "CaretEqualsToken";
3015         // Identifiers and PrivateIdentifiers
3016         SyntaxKind[SyntaxKind["Identifier"] = 75] = "Identifier";
3017         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 76] = "PrivateIdentifier";
3018         // Reserved words
3019         SyntaxKind[SyntaxKind["BreakKeyword"] = 77] = "BreakKeyword";
3020         SyntaxKind[SyntaxKind["CaseKeyword"] = 78] = "CaseKeyword";
3021         SyntaxKind[SyntaxKind["CatchKeyword"] = 79] = "CatchKeyword";
3022         SyntaxKind[SyntaxKind["ClassKeyword"] = 80] = "ClassKeyword";
3023         SyntaxKind[SyntaxKind["ConstKeyword"] = 81] = "ConstKeyword";
3024         SyntaxKind[SyntaxKind["ContinueKeyword"] = 82] = "ContinueKeyword";
3025         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 83] = "DebuggerKeyword";
3026         SyntaxKind[SyntaxKind["DefaultKeyword"] = 84] = "DefaultKeyword";
3027         SyntaxKind[SyntaxKind["DeleteKeyword"] = 85] = "DeleteKeyword";
3028         SyntaxKind[SyntaxKind["DoKeyword"] = 86] = "DoKeyword";
3029         SyntaxKind[SyntaxKind["ElseKeyword"] = 87] = "ElseKeyword";
3030         SyntaxKind[SyntaxKind["EnumKeyword"] = 88] = "EnumKeyword";
3031         SyntaxKind[SyntaxKind["ExportKeyword"] = 89] = "ExportKeyword";
3032         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 90] = "ExtendsKeyword";
3033         SyntaxKind[SyntaxKind["FalseKeyword"] = 91] = "FalseKeyword";
3034         SyntaxKind[SyntaxKind["FinallyKeyword"] = 92] = "FinallyKeyword";
3035         SyntaxKind[SyntaxKind["ForKeyword"] = 93] = "ForKeyword";
3036         SyntaxKind[SyntaxKind["FunctionKeyword"] = 94] = "FunctionKeyword";
3037         SyntaxKind[SyntaxKind["IfKeyword"] = 95] = "IfKeyword";
3038         SyntaxKind[SyntaxKind["ImportKeyword"] = 96] = "ImportKeyword";
3039         SyntaxKind[SyntaxKind["InKeyword"] = 97] = "InKeyword";
3040         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 98] = "InstanceOfKeyword";
3041         SyntaxKind[SyntaxKind["NewKeyword"] = 99] = "NewKeyword";
3042         SyntaxKind[SyntaxKind["NullKeyword"] = 100] = "NullKeyword";
3043         SyntaxKind[SyntaxKind["ReturnKeyword"] = 101] = "ReturnKeyword";
3044         SyntaxKind[SyntaxKind["SuperKeyword"] = 102] = "SuperKeyword";
3045         SyntaxKind[SyntaxKind["SwitchKeyword"] = 103] = "SwitchKeyword";
3046         SyntaxKind[SyntaxKind["ThisKeyword"] = 104] = "ThisKeyword";
3047         SyntaxKind[SyntaxKind["ThrowKeyword"] = 105] = "ThrowKeyword";
3048         SyntaxKind[SyntaxKind["TrueKeyword"] = 106] = "TrueKeyword";
3049         SyntaxKind[SyntaxKind["TryKeyword"] = 107] = "TryKeyword";
3050         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 108] = "TypeOfKeyword";
3051         SyntaxKind[SyntaxKind["VarKeyword"] = 109] = "VarKeyword";
3052         SyntaxKind[SyntaxKind["VoidKeyword"] = 110] = "VoidKeyword";
3053         SyntaxKind[SyntaxKind["WhileKeyword"] = 111] = "WhileKeyword";
3054         SyntaxKind[SyntaxKind["WithKeyword"] = 112] = "WithKeyword";
3055         // Strict mode reserved words
3056         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 113] = "ImplementsKeyword";
3057         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 114] = "InterfaceKeyword";
3058         SyntaxKind[SyntaxKind["LetKeyword"] = 115] = "LetKeyword";
3059         SyntaxKind[SyntaxKind["PackageKeyword"] = 116] = "PackageKeyword";
3060         SyntaxKind[SyntaxKind["PrivateKeyword"] = 117] = "PrivateKeyword";
3061         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 118] = "ProtectedKeyword";
3062         SyntaxKind[SyntaxKind["PublicKeyword"] = 119] = "PublicKeyword";
3063         SyntaxKind[SyntaxKind["StaticKeyword"] = 120] = "StaticKeyword";
3064         SyntaxKind[SyntaxKind["YieldKeyword"] = 121] = "YieldKeyword";
3065         // Contextual keywords
3066         SyntaxKind[SyntaxKind["AbstractKeyword"] = 122] = "AbstractKeyword";
3067         SyntaxKind[SyntaxKind["AsKeyword"] = 123] = "AsKeyword";
3068         SyntaxKind[SyntaxKind["AssertsKeyword"] = 124] = "AssertsKeyword";
3069         SyntaxKind[SyntaxKind["AnyKeyword"] = 125] = "AnyKeyword";
3070         SyntaxKind[SyntaxKind["AsyncKeyword"] = 126] = "AsyncKeyword";
3071         SyntaxKind[SyntaxKind["AwaitKeyword"] = 127] = "AwaitKeyword";
3072         SyntaxKind[SyntaxKind["BooleanKeyword"] = 128] = "BooleanKeyword";
3073         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 129] = "ConstructorKeyword";
3074         SyntaxKind[SyntaxKind["DeclareKeyword"] = 130] = "DeclareKeyword";
3075         SyntaxKind[SyntaxKind["GetKeyword"] = 131] = "GetKeyword";
3076         SyntaxKind[SyntaxKind["InferKeyword"] = 132] = "InferKeyword";
3077         SyntaxKind[SyntaxKind["IsKeyword"] = 133] = "IsKeyword";
3078         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 134] = "KeyOfKeyword";
3079         SyntaxKind[SyntaxKind["ModuleKeyword"] = 135] = "ModuleKeyword";
3080         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 136] = "NamespaceKeyword";
3081         SyntaxKind[SyntaxKind["NeverKeyword"] = 137] = "NeverKeyword";
3082         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 138] = "ReadonlyKeyword";
3083         SyntaxKind[SyntaxKind["RequireKeyword"] = 139] = "RequireKeyword";
3084         SyntaxKind[SyntaxKind["NumberKeyword"] = 140] = "NumberKeyword";
3085         SyntaxKind[SyntaxKind["ObjectKeyword"] = 141] = "ObjectKeyword";
3086         SyntaxKind[SyntaxKind["SetKeyword"] = 142] = "SetKeyword";
3087         SyntaxKind[SyntaxKind["StringKeyword"] = 143] = "StringKeyword";
3088         SyntaxKind[SyntaxKind["SymbolKeyword"] = 144] = "SymbolKeyword";
3089         SyntaxKind[SyntaxKind["TypeKeyword"] = 145] = "TypeKeyword";
3090         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 146] = "UndefinedKeyword";
3091         SyntaxKind[SyntaxKind["UniqueKeyword"] = 147] = "UniqueKeyword";
3092         SyntaxKind[SyntaxKind["UnknownKeyword"] = 148] = "UnknownKeyword";
3093         SyntaxKind[SyntaxKind["FromKeyword"] = 149] = "FromKeyword";
3094         SyntaxKind[SyntaxKind["GlobalKeyword"] = 150] = "GlobalKeyword";
3095         SyntaxKind[SyntaxKind["BigIntKeyword"] = 151] = "BigIntKeyword";
3096         SyntaxKind[SyntaxKind["OfKeyword"] = 152] = "OfKeyword";
3097         // Parse tree nodes
3098         // Names
3099         SyntaxKind[SyntaxKind["QualifiedName"] = 153] = "QualifiedName";
3100         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 154] = "ComputedPropertyName";
3101         // Signature elements
3102         SyntaxKind[SyntaxKind["TypeParameter"] = 155] = "TypeParameter";
3103         SyntaxKind[SyntaxKind["Parameter"] = 156] = "Parameter";
3104         SyntaxKind[SyntaxKind["Decorator"] = 157] = "Decorator";
3105         // TypeMember
3106         SyntaxKind[SyntaxKind["PropertySignature"] = 158] = "PropertySignature";
3107         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 159] = "PropertyDeclaration";
3108         SyntaxKind[SyntaxKind["MethodSignature"] = 160] = "MethodSignature";
3109         SyntaxKind[SyntaxKind["MethodDeclaration"] = 161] = "MethodDeclaration";
3110         SyntaxKind[SyntaxKind["Constructor"] = 162] = "Constructor";
3111         SyntaxKind[SyntaxKind["GetAccessor"] = 163] = "GetAccessor";
3112         SyntaxKind[SyntaxKind["SetAccessor"] = 164] = "SetAccessor";
3113         SyntaxKind[SyntaxKind["CallSignature"] = 165] = "CallSignature";
3114         SyntaxKind[SyntaxKind["ConstructSignature"] = 166] = "ConstructSignature";
3115         SyntaxKind[SyntaxKind["IndexSignature"] = 167] = "IndexSignature";
3116         // Type
3117         SyntaxKind[SyntaxKind["TypePredicate"] = 168] = "TypePredicate";
3118         SyntaxKind[SyntaxKind["TypeReference"] = 169] = "TypeReference";
3119         SyntaxKind[SyntaxKind["FunctionType"] = 170] = "FunctionType";
3120         SyntaxKind[SyntaxKind["ConstructorType"] = 171] = "ConstructorType";
3121         SyntaxKind[SyntaxKind["TypeQuery"] = 172] = "TypeQuery";
3122         SyntaxKind[SyntaxKind["TypeLiteral"] = 173] = "TypeLiteral";
3123         SyntaxKind[SyntaxKind["ArrayType"] = 174] = "ArrayType";
3124         SyntaxKind[SyntaxKind["TupleType"] = 175] = "TupleType";
3125         SyntaxKind[SyntaxKind["OptionalType"] = 176] = "OptionalType";
3126         SyntaxKind[SyntaxKind["RestType"] = 177] = "RestType";
3127         SyntaxKind[SyntaxKind["UnionType"] = 178] = "UnionType";
3128         SyntaxKind[SyntaxKind["IntersectionType"] = 179] = "IntersectionType";
3129         SyntaxKind[SyntaxKind["ConditionalType"] = 180] = "ConditionalType";
3130         SyntaxKind[SyntaxKind["InferType"] = 181] = "InferType";
3131         SyntaxKind[SyntaxKind["ParenthesizedType"] = 182] = "ParenthesizedType";
3132         SyntaxKind[SyntaxKind["ThisType"] = 183] = "ThisType";
3133         SyntaxKind[SyntaxKind["TypeOperator"] = 184] = "TypeOperator";
3134         SyntaxKind[SyntaxKind["IndexedAccessType"] = 185] = "IndexedAccessType";
3135         SyntaxKind[SyntaxKind["MappedType"] = 186] = "MappedType";
3136         SyntaxKind[SyntaxKind["LiteralType"] = 187] = "LiteralType";
3137         SyntaxKind[SyntaxKind["ImportType"] = 188] = "ImportType";
3138         // Binding patterns
3139         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 189] = "ObjectBindingPattern";
3140         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 190] = "ArrayBindingPattern";
3141         SyntaxKind[SyntaxKind["BindingElement"] = 191] = "BindingElement";
3142         // Expression
3143         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 192] = "ArrayLiteralExpression";
3144         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 193] = "ObjectLiteralExpression";
3145         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 194] = "PropertyAccessExpression";
3146         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 195] = "ElementAccessExpression";
3147         SyntaxKind[SyntaxKind["CallExpression"] = 196] = "CallExpression";
3148         SyntaxKind[SyntaxKind["NewExpression"] = 197] = "NewExpression";
3149         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 198] = "TaggedTemplateExpression";
3150         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 199] = "TypeAssertionExpression";
3151         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 200] = "ParenthesizedExpression";
3152         SyntaxKind[SyntaxKind["FunctionExpression"] = 201] = "FunctionExpression";
3153         SyntaxKind[SyntaxKind["ArrowFunction"] = 202] = "ArrowFunction";
3154         SyntaxKind[SyntaxKind["DeleteExpression"] = 203] = "DeleteExpression";
3155         SyntaxKind[SyntaxKind["TypeOfExpression"] = 204] = "TypeOfExpression";
3156         SyntaxKind[SyntaxKind["VoidExpression"] = 205] = "VoidExpression";
3157         SyntaxKind[SyntaxKind["AwaitExpression"] = 206] = "AwaitExpression";
3158         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 207] = "PrefixUnaryExpression";
3159         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 208] = "PostfixUnaryExpression";
3160         SyntaxKind[SyntaxKind["BinaryExpression"] = 209] = "BinaryExpression";
3161         SyntaxKind[SyntaxKind["ConditionalExpression"] = 210] = "ConditionalExpression";
3162         SyntaxKind[SyntaxKind["TemplateExpression"] = 211] = "TemplateExpression";
3163         SyntaxKind[SyntaxKind["YieldExpression"] = 212] = "YieldExpression";
3164         SyntaxKind[SyntaxKind["SpreadElement"] = 213] = "SpreadElement";
3165         SyntaxKind[SyntaxKind["ClassExpression"] = 214] = "ClassExpression";
3166         SyntaxKind[SyntaxKind["OmittedExpression"] = 215] = "OmittedExpression";
3167         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 216] = "ExpressionWithTypeArguments";
3168         SyntaxKind[SyntaxKind["AsExpression"] = 217] = "AsExpression";
3169         SyntaxKind[SyntaxKind["NonNullExpression"] = 218] = "NonNullExpression";
3170         SyntaxKind[SyntaxKind["MetaProperty"] = 219] = "MetaProperty";
3171         SyntaxKind[SyntaxKind["SyntheticExpression"] = 220] = "SyntheticExpression";
3172         // Misc
3173         SyntaxKind[SyntaxKind["TemplateSpan"] = 221] = "TemplateSpan";
3174         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 222] = "SemicolonClassElement";
3175         // Element
3176         SyntaxKind[SyntaxKind["Block"] = 223] = "Block";
3177         SyntaxKind[SyntaxKind["EmptyStatement"] = 224] = "EmptyStatement";
3178         SyntaxKind[SyntaxKind["VariableStatement"] = 225] = "VariableStatement";
3179         SyntaxKind[SyntaxKind["ExpressionStatement"] = 226] = "ExpressionStatement";
3180         SyntaxKind[SyntaxKind["IfStatement"] = 227] = "IfStatement";
3181         SyntaxKind[SyntaxKind["DoStatement"] = 228] = "DoStatement";
3182         SyntaxKind[SyntaxKind["WhileStatement"] = 229] = "WhileStatement";
3183         SyntaxKind[SyntaxKind["ForStatement"] = 230] = "ForStatement";
3184         SyntaxKind[SyntaxKind["ForInStatement"] = 231] = "ForInStatement";
3185         SyntaxKind[SyntaxKind["ForOfStatement"] = 232] = "ForOfStatement";
3186         SyntaxKind[SyntaxKind["ContinueStatement"] = 233] = "ContinueStatement";
3187         SyntaxKind[SyntaxKind["BreakStatement"] = 234] = "BreakStatement";
3188         SyntaxKind[SyntaxKind["ReturnStatement"] = 235] = "ReturnStatement";
3189         SyntaxKind[SyntaxKind["WithStatement"] = 236] = "WithStatement";
3190         SyntaxKind[SyntaxKind["SwitchStatement"] = 237] = "SwitchStatement";
3191         SyntaxKind[SyntaxKind["LabeledStatement"] = 238] = "LabeledStatement";
3192         SyntaxKind[SyntaxKind["ThrowStatement"] = 239] = "ThrowStatement";
3193         SyntaxKind[SyntaxKind["TryStatement"] = 240] = "TryStatement";
3194         SyntaxKind[SyntaxKind["DebuggerStatement"] = 241] = "DebuggerStatement";
3195         SyntaxKind[SyntaxKind["VariableDeclaration"] = 242] = "VariableDeclaration";
3196         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 243] = "VariableDeclarationList";
3197         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 244] = "FunctionDeclaration";
3198         SyntaxKind[SyntaxKind["ClassDeclaration"] = 245] = "ClassDeclaration";
3199         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 246] = "InterfaceDeclaration";
3200         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 247] = "TypeAliasDeclaration";
3201         SyntaxKind[SyntaxKind["EnumDeclaration"] = 248] = "EnumDeclaration";
3202         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 249] = "ModuleDeclaration";
3203         SyntaxKind[SyntaxKind["ModuleBlock"] = 250] = "ModuleBlock";
3204         SyntaxKind[SyntaxKind["CaseBlock"] = 251] = "CaseBlock";
3205         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 252] = "NamespaceExportDeclaration";
3206         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 253] = "ImportEqualsDeclaration";
3207         SyntaxKind[SyntaxKind["ImportDeclaration"] = 254] = "ImportDeclaration";
3208         SyntaxKind[SyntaxKind["ImportClause"] = 255] = "ImportClause";
3209         SyntaxKind[SyntaxKind["NamespaceImport"] = 256] = "NamespaceImport";
3210         SyntaxKind[SyntaxKind["NamedImports"] = 257] = "NamedImports";
3211         SyntaxKind[SyntaxKind["ImportSpecifier"] = 258] = "ImportSpecifier";
3212         SyntaxKind[SyntaxKind["ExportAssignment"] = 259] = "ExportAssignment";
3213         SyntaxKind[SyntaxKind["ExportDeclaration"] = 260] = "ExportDeclaration";
3214         SyntaxKind[SyntaxKind["NamedExports"] = 261] = "NamedExports";
3215         SyntaxKind[SyntaxKind["NamespaceExport"] = 262] = "NamespaceExport";
3216         SyntaxKind[SyntaxKind["ExportSpecifier"] = 263] = "ExportSpecifier";
3217         SyntaxKind[SyntaxKind["MissingDeclaration"] = 264] = "MissingDeclaration";
3218         // Module references
3219         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 265] = "ExternalModuleReference";
3220         // JSX
3221         SyntaxKind[SyntaxKind["JsxElement"] = 266] = "JsxElement";
3222         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 267] = "JsxSelfClosingElement";
3223         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 268] = "JsxOpeningElement";
3224         SyntaxKind[SyntaxKind["JsxClosingElement"] = 269] = "JsxClosingElement";
3225         SyntaxKind[SyntaxKind["JsxFragment"] = 270] = "JsxFragment";
3226         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 271] = "JsxOpeningFragment";
3227         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 272] = "JsxClosingFragment";
3228         SyntaxKind[SyntaxKind["JsxAttribute"] = 273] = "JsxAttribute";
3229         SyntaxKind[SyntaxKind["JsxAttributes"] = 274] = "JsxAttributes";
3230         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 275] = "JsxSpreadAttribute";
3231         SyntaxKind[SyntaxKind["JsxExpression"] = 276] = "JsxExpression";
3232         // Clauses
3233         SyntaxKind[SyntaxKind["CaseClause"] = 277] = "CaseClause";
3234         SyntaxKind[SyntaxKind["DefaultClause"] = 278] = "DefaultClause";
3235         SyntaxKind[SyntaxKind["HeritageClause"] = 279] = "HeritageClause";
3236         SyntaxKind[SyntaxKind["CatchClause"] = 280] = "CatchClause";
3237         // Property assignments
3238         SyntaxKind[SyntaxKind["PropertyAssignment"] = 281] = "PropertyAssignment";
3239         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 282] = "ShorthandPropertyAssignment";
3240         SyntaxKind[SyntaxKind["SpreadAssignment"] = 283] = "SpreadAssignment";
3241         // Enum
3242         SyntaxKind[SyntaxKind["EnumMember"] = 284] = "EnumMember";
3243         // Unparsed
3244         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 285] = "UnparsedPrologue";
3245         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 286] = "UnparsedPrepend";
3246         SyntaxKind[SyntaxKind["UnparsedText"] = 287] = "UnparsedText";
3247         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 288] = "UnparsedInternalText";
3248         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 289] = "UnparsedSyntheticReference";
3249         // Top-level nodes
3250         SyntaxKind[SyntaxKind["SourceFile"] = 290] = "SourceFile";
3251         SyntaxKind[SyntaxKind["Bundle"] = 291] = "Bundle";
3252         SyntaxKind[SyntaxKind["UnparsedSource"] = 292] = "UnparsedSource";
3253         SyntaxKind[SyntaxKind["InputFiles"] = 293] = "InputFiles";
3254         // JSDoc nodes
3255         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 294] = "JSDocTypeExpression";
3256         // The * type
3257         SyntaxKind[SyntaxKind["JSDocAllType"] = 295] = "JSDocAllType";
3258         // The ? type
3259         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 296] = "JSDocUnknownType";
3260         SyntaxKind[SyntaxKind["JSDocNullableType"] = 297] = "JSDocNullableType";
3261         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 298] = "JSDocNonNullableType";
3262         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 299] = "JSDocOptionalType";
3263         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 300] = "JSDocFunctionType";
3264         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 301] = "JSDocVariadicType";
3265         // https://jsdoc.app/about-namepaths.html
3266         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 302] = "JSDocNamepathType";
3267         SyntaxKind[SyntaxKind["JSDocComment"] = 303] = "JSDocComment";
3268         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 304] = "JSDocTypeLiteral";
3269         SyntaxKind[SyntaxKind["JSDocSignature"] = 305] = "JSDocSignature";
3270         SyntaxKind[SyntaxKind["JSDocTag"] = 306] = "JSDocTag";
3271         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 307] = "JSDocAugmentsTag";
3272         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 308] = "JSDocImplementsTag";
3273         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 309] = "JSDocAuthorTag";
3274         SyntaxKind[SyntaxKind["JSDocClassTag"] = 310] = "JSDocClassTag";
3275         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 311] = "JSDocPublicTag";
3276         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 312] = "JSDocPrivateTag";
3277         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 313] = "JSDocProtectedTag";
3278         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 314] = "JSDocReadonlyTag";
3279         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 315] = "JSDocCallbackTag";
3280         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 316] = "JSDocEnumTag";
3281         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 317] = "JSDocParameterTag";
3282         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 318] = "JSDocReturnTag";
3283         SyntaxKind[SyntaxKind["JSDocThisTag"] = 319] = "JSDocThisTag";
3284         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 320] = "JSDocTypeTag";
3285         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 321] = "JSDocTemplateTag";
3286         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 322] = "JSDocTypedefTag";
3287         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 323] = "JSDocPropertyTag";
3288         // Synthesized list
3289         SyntaxKind[SyntaxKind["SyntaxList"] = 324] = "SyntaxList";
3290         // Transformation nodes
3291         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 325] = "NotEmittedStatement";
3292         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 326] = "PartiallyEmittedExpression";
3293         SyntaxKind[SyntaxKind["CommaListExpression"] = 327] = "CommaListExpression";
3294         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 328] = "MergeDeclarationMarker";
3295         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 329] = "EndOfDeclarationMarker";
3296         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 330] = "SyntheticReferenceExpression";
3297         // Enum value count
3298         SyntaxKind[SyntaxKind["Count"] = 331] = "Count";
3299         // Markers
3300         SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
3301         SyntaxKind[SyntaxKind["LastAssignment"] = 74] = "LastAssignment";
3302         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
3303         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 74] = "LastCompoundAssignment";
3304         SyntaxKind[SyntaxKind["FirstReservedWord"] = 77] = "FirstReservedWord";
3305         SyntaxKind[SyntaxKind["LastReservedWord"] = 112] = "LastReservedWord";
3306         SyntaxKind[SyntaxKind["FirstKeyword"] = 77] = "FirstKeyword";
3307         SyntaxKind[SyntaxKind["LastKeyword"] = 152] = "LastKeyword";
3308         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 113] = "FirstFutureReservedWord";
3309         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 121] = "LastFutureReservedWord";
3310         SyntaxKind[SyntaxKind["FirstTypeNode"] = 168] = "FirstTypeNode";
3311         SyntaxKind[SyntaxKind["LastTypeNode"] = 188] = "LastTypeNode";
3312         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
3313         SyntaxKind[SyntaxKind["LastPunctuation"] = 74] = "LastPunctuation";
3314         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
3315         SyntaxKind[SyntaxKind["LastToken"] = 152] = "LastToken";
3316         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
3317         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
3318         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
3319         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
3320         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
3321         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
3322         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
3323         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 74] = "LastBinaryOperator";
3324         SyntaxKind[SyntaxKind["FirstStatement"] = 225] = "FirstStatement";
3325         SyntaxKind[SyntaxKind["LastStatement"] = 241] = "LastStatement";
3326         SyntaxKind[SyntaxKind["FirstNode"] = 153] = "FirstNode";
3327         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 294] = "FirstJSDocNode";
3328         SyntaxKind[SyntaxKind["LastJSDocNode"] = 323] = "LastJSDocNode";
3329         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 306] = "FirstJSDocTagNode";
3330         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 323] = "LastJSDocTagNode";
3331         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 122] = "FirstContextualKeyword";
3332         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 152] = "LastContextualKeyword";
3333     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
3334     var NodeFlags;
3335     (function (NodeFlags) {
3336         NodeFlags[NodeFlags["None"] = 0] = "None";
3337         NodeFlags[NodeFlags["Let"] = 1] = "Let";
3338         NodeFlags[NodeFlags["Const"] = 2] = "Const";
3339         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
3340         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
3341         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
3342         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
3343         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
3344         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
3345         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
3346         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
3347         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
3348         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
3349         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
3350         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
3351         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
3352         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
3353         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
3354         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
3355         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
3356         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
3357         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
3358         // walking the tree if the flags are not set. However, these flags are just a approximation
3359         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
3360         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
3361         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
3362         // However, the removal operation should not occur often and in the case of the
3363         // removal, it is likely that users will add the import anyway.
3364         // The advantage of this approach is its simplicity. For the case of batch compilation,
3365         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
3366         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
3367         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
3368         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
3369         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
3370         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
3371         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
3372         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
3373         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
3374         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
3375         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
3376         // Parsing context flags
3377         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
3378         // Exclude these flags when parsing a Type
3379         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
3380         // Represents all flags that are potentially set once and
3381         // never cleared on SourceFiles which get re-used in between incremental parses.
3382         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
3383         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
3384     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
3385     var ModifierFlags;
3386     (function (ModifierFlags) {
3387         ModifierFlags[ModifierFlags["None"] = 0] = "None";
3388         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
3389         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
3390         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
3391         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
3392         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
3393         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
3394         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
3395         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
3396         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
3397         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
3398         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
3399         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
3400         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
3401         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
3402         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
3403         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
3404         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
3405         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
3406         ModifierFlags[ModifierFlags["All"] = 3071] = "All";
3407     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
3408     var JsxFlags;
3409     (function (JsxFlags) {
3410         JsxFlags[JsxFlags["None"] = 0] = "None";
3411         /** An element from a named property of the JSX.IntrinsicElements interface */
3412         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
3413         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
3414         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
3415         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
3416     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
3417     /* @internal */
3418     var RelationComparisonResult;
3419     (function (RelationComparisonResult) {
3420         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
3421         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
3422         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
3423         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
3424         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
3425         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
3426     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
3427     /*@internal*/
3428     var GeneratedIdentifierFlags;
3429     (function (GeneratedIdentifierFlags) {
3430         // Kinds
3431         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
3432         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
3433         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
3434         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
3435         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
3436         GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
3437         // Flags
3438         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
3439         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
3440         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
3441     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
3442     var TokenFlags;
3443     (function (TokenFlags) {
3444         TokenFlags[TokenFlags["None"] = 0] = "None";
3445         /* @internal */
3446         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
3447         /* @internal */
3448         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
3449         /* @internal */
3450         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
3451         /* @internal */
3452         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
3453         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
3454         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
3455         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
3456         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
3457         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
3458         /* @internal */
3459         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
3460         /* @internal */
3461         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
3462         /* @internal */
3463         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
3464         /* @internal */
3465         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
3466         /* @internal */
3467         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
3468     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
3469     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
3470     var FlowFlags;
3471     (function (FlowFlags) {
3472         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
3473         FlowFlags[FlowFlags["Start"] = 2] = "Start";
3474         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
3475         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
3476         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
3477         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
3478         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
3479         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
3480         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
3481         FlowFlags[FlowFlags["Call"] = 512] = "Call";
3482         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
3483         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
3484         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
3485         FlowFlags[FlowFlags["Label"] = 12] = "Label";
3486         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
3487     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
3488     /* @internal */
3489     var CommentDirectiveType;
3490     (function (CommentDirectiveType) {
3491         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
3492         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
3493     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
3494     var OperationCanceledException = /** @class */ (function () {
3495         function OperationCanceledException() {
3496         }
3497         return OperationCanceledException;
3498     }());
3499     ts.OperationCanceledException = OperationCanceledException;
3500     /*@internal*/
3501     var RefFileKind;
3502     (function (RefFileKind) {
3503         RefFileKind[RefFileKind["Import"] = 0] = "Import";
3504         RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
3505         RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
3506     })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
3507     /* @internal */
3508     var StructureIsReused;
3509     (function (StructureIsReused) {
3510         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
3511         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
3512         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
3513     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
3514     /** Return code used by getEmitOutput function to indicate status of the function */
3515     var ExitStatus;
3516     (function (ExitStatus) {
3517         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
3518         // when -version or -help was provided, or this was a normal compilation, no diagnostics
3519         // were produced, and all outputs were generated successfully.
3520         ExitStatus[ExitStatus["Success"] = 0] = "Success";
3521         // Diagnostics were produced and because of them no code was generated.
3522         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
3523         // Diagnostics were produced and outputs were generated in spite of them.
3524         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
3525         // When build skipped because passed in project is invalid
3526         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
3527         // When build is skipped because project references form cycle
3528         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
3529         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
3530         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
3531     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
3532     /* @internal */
3533     var UnionReduction;
3534     (function (UnionReduction) {
3535         UnionReduction[UnionReduction["None"] = 0] = "None";
3536         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
3537         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
3538     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
3539     /* @internal */
3540     var ContextFlags;
3541     (function (ContextFlags) {
3542         ContextFlags[ContextFlags["None"] = 0] = "None";
3543         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
3544         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
3545         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
3546     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
3547     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
3548     var NodeBuilderFlags;
3549     (function (NodeBuilderFlags) {
3550         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
3551         // Options
3552         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
3553         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3554         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
3555         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3556         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
3557         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3558         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3559         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
3560         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3561         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
3562         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3563         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3564         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3565         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3566         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3567         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3568         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3569         // Error handling
3570         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
3571         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
3572         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
3573         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
3574         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
3575         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3576         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
3577         // Errors (cont.)
3578         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
3579         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
3580         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
3581         // State
3582         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
3583         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3584         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
3585         NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
3586     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
3587     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
3588     var TypeFormatFlags;
3589     (function (TypeFormatFlags) {
3590         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
3591         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
3592         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3593         // hole because there's a hole in node builder flags
3594         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3595         // hole because there's a hole in node builder flags
3596         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3597         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3598         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
3599         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3600         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
3601         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3602         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3603         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3604         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3605         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3606         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3607         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3608         // Error Handling
3609         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3610         // TypeFormatFlags exclusive
3611         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
3612         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
3613         // State
3614         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
3615         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
3616         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
3617         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3618         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
3619         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
3620     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
3621     var SymbolFormatFlags;
3622     (function (SymbolFormatFlags) {
3623         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
3624         // Write symbols's type argument if it is instantiated symbol
3625         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
3626         //     var a: C<number>;
3627         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
3628         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
3629         // Use only external alias information to get the symbol name in the given context
3630         // eg.  module m { export class c { } } import x = m.c;
3631         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
3632         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
3633         // Build symbol name using any nodes needed, instead of just components of an entity name
3634         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
3635         // Prefer aliases which are not directly visible
3636         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
3637         // Skip building an accessible symbol chain
3638         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
3639     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
3640     /* @internal */
3641     var SymbolAccessibility;
3642     (function (SymbolAccessibility) {
3643         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
3644         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
3645         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
3646     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
3647     /* @internal */
3648     var SyntheticSymbolKind;
3649     (function (SyntheticSymbolKind) {
3650         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
3651         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
3652     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
3653     var TypePredicateKind;
3654     (function (TypePredicateKind) {
3655         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
3656         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
3657         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
3658         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
3659     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
3660     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
3661     /* @internal */
3662     var TypeReferenceSerializationKind;
3663     (function (TypeReferenceSerializationKind) {
3664         // The TypeReferenceNode could not be resolved.
3665         // The type name should be emitted using a safe fallback.
3666         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
3667         // The TypeReferenceNode resolves to a type with a constructor
3668         // function that can be reached at runtime (e.g. a `class`
3669         // declaration or a `var` declaration for the static side
3670         // of a type, such as the global `Promise` type in lib.d.ts).
3671         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
3672         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
3673         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
3674         // The TypeReferenceNode resolves to a Number-like type.
3675         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
3676         // The TypeReferenceNode resolves to a BigInt-like type.
3677         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
3678         // The TypeReferenceNode resolves to a String-like type.
3679         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
3680         // The TypeReferenceNode resolves to a Boolean-like type.
3681         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
3682         // The TypeReferenceNode resolves to an Array-like type.
3683         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
3684         // The TypeReferenceNode resolves to the ESSymbol type.
3685         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
3686         // The TypeReferenceNode resolved to the global Promise constructor symbol.
3687         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
3688         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
3689         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
3690         // The TypeReferenceNode resolves to any other type.
3691         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
3692     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
3693     var SymbolFlags;
3694     (function (SymbolFlags) {
3695         SymbolFlags[SymbolFlags["None"] = 0] = "None";
3696         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
3697         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
3698         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
3699         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
3700         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
3701         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
3702         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
3703         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
3704         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
3705         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
3706         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
3707         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
3708         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
3709         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
3710         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
3711         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
3712         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
3713         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
3714         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
3715         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
3716         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
3717         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
3718         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
3719         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
3720         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
3721         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
3722         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
3723         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
3724         /* @internal */
3725         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
3726         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
3727         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
3728         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
3729         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
3730         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
3731         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
3732         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
3733         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
3734         // same name, or any other value that is not a variable, e.g. ValueModule or Class
3735         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
3736         // Block-scoped declarations are not allowed to be re-declared
3737         // they can not merge with anything in the value space
3738         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
3739         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
3740         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
3741         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
3742         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
3743         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
3744         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
3745         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
3746         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
3747         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
3748         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
3749         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
3750         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
3751         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
3752         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
3753         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
3754         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
3755         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
3756         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
3757         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
3758         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
3759         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
3760         /* @internal */
3761         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
3762         /* @internal */
3763         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
3764         /* @internal */
3765         // The set of things we consider semantically classifiable.  Used to speed up the LS during
3766         // classification.
3767         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
3768         /* @internal */
3769         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
3770     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
3771     /* @internal */
3772     var EnumKind;
3773     (function (EnumKind) {
3774         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
3775         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
3776     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
3777     /* @internal */
3778     var CheckFlags;
3779     (function (CheckFlags) {
3780         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
3781         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
3782         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
3783         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
3784         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
3785         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
3786         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
3787         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
3788         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
3789         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
3790         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
3791         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
3792         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
3793         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
3794         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
3795         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
3796         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
3797         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
3798         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
3799         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
3800         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
3801         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
3802         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
3803     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
3804     var InternalSymbolName;
3805     (function (InternalSymbolName) {
3806         InternalSymbolName["Call"] = "__call";
3807         InternalSymbolName["Constructor"] = "__constructor";
3808         InternalSymbolName["New"] = "__new";
3809         InternalSymbolName["Index"] = "__index";
3810         InternalSymbolName["ExportStar"] = "__export";
3811         InternalSymbolName["Global"] = "__global";
3812         InternalSymbolName["Missing"] = "__missing";
3813         InternalSymbolName["Type"] = "__type";
3814         InternalSymbolName["Object"] = "__object";
3815         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
3816         InternalSymbolName["Class"] = "__class";
3817         InternalSymbolName["Function"] = "__function";
3818         InternalSymbolName["Computed"] = "__computed";
3819         InternalSymbolName["Resolving"] = "__resolving__";
3820         InternalSymbolName["ExportEquals"] = "export=";
3821         InternalSymbolName["Default"] = "default";
3822         InternalSymbolName["This"] = "this";
3823     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
3824     /* @internal */
3825     var NodeCheckFlags;
3826     (function (NodeCheckFlags) {
3827         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
3828         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
3829         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
3830         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
3831         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
3832         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
3833         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
3834         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
3835         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
3836         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
3837         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
3838         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
3839         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
3840         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
3841         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
3842         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
3843         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
3844         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
3845         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
3846         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
3847         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
3848         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
3849         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
3850     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
3851     var TypeFlags;
3852     (function (TypeFlags) {
3853         TypeFlags[TypeFlags["Any"] = 1] = "Any";
3854         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
3855         TypeFlags[TypeFlags["String"] = 4] = "String";
3856         TypeFlags[TypeFlags["Number"] = 8] = "Number";
3857         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
3858         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
3859         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
3860         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
3861         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
3862         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
3863         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
3864         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
3865         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
3866         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
3867         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
3868         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
3869         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
3870         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
3871         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
3872         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
3873         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
3874         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
3875         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
3876         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
3877         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
3878         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
3879         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
3880         /* @internal */
3881         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
3882         /* @internal */
3883         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
3884         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
3885         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
3886         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
3887         /* @internal */
3888         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
3889         /* @internal */
3890         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
3891         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
3892         /* @internal */
3893         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
3894         /* @internal */
3895         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
3896         TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
3897         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
3898         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
3899         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
3900         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
3901         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
3902         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
3903         /* @internal */
3904         TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
3905         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
3906         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
3907         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
3908         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
3909         TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
3910         TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
3911         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
3912         /* @internal */
3913         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
3914         /* @internal */
3915         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
3916         /* @internal */
3917         TypeFlags[TypeFlags["Substructure"] = 66584576] = "Substructure";
3918         // 'Narrowable' types are types where narrowing actually narrows.
3919         // This *should* be every type other than null, undefined, void, and never
3920         TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
3921         TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
3922         /* @internal */
3923         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
3924         // The following flags are aggregated during union and intersection type construction
3925         /* @internal */
3926         TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask";
3927         // The following flags are used for different purposes during union and intersection type construction
3928         /* @internal */
3929         TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
3930         /* @internal */
3931         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
3932         /* @internal */
3933         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
3934         /* @internal */
3935         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
3936     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
3937     var ObjectFlags;
3938     (function (ObjectFlags) {
3939         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
3940         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
3941         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
3942         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
3943         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
3944         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
3945         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
3946         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
3947         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
3948         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
3949         ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
3950         ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
3951         ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
3952         ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
3953         ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
3954         ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
3955         ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
3956         ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
3957         /* @internal */
3958         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
3959         /* @internal */
3960         ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
3961         /* @internal */
3962         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
3963         /* @internal */
3964         ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
3965         /* @internal */
3966         ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
3967         /* @internal */
3968         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
3969         /* @internal */
3970         ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
3971         /* @internal */
3972         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
3973         /* @internal */
3974         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
3975         /* @internal */
3976         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
3977         /* @internal */
3978         ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
3979         /* @internal */
3980         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
3981         /* @internal */
3982         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
3983         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
3984         /* @internal */
3985         ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
3986         /* @internal */
3987         ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
3988     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
3989     /* @internal */
3990     var VarianceFlags;
3991     (function (VarianceFlags) {
3992         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
3993         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
3994         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
3995         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
3996         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
3997         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
3998         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
3999         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
4000         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
4001     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
4002     /* @internal */
4003     var JsxReferenceKind;
4004     (function (JsxReferenceKind) {
4005         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
4006         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
4007         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
4008     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4009     var SignatureKind;
4010     (function (SignatureKind) {
4011         SignatureKind[SignatureKind["Call"] = 0] = "Call";
4012         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4013     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4014     /* @internal */
4015     var SignatureFlags;
4016     (function (SignatureFlags) {
4017         SignatureFlags[SignatureFlags["None"] = 0] = "None";
4018         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4019         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4020         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
4021         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
4022         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
4023         // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
4024         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4025         // instantiating the return type.
4026         SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags";
4027         SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
4028     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4029     var IndexKind;
4030     (function (IndexKind) {
4031         IndexKind[IndexKind["String"] = 0] = "String";
4032         IndexKind[IndexKind["Number"] = 1] = "Number";
4033     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4034     /* @internal */
4035     var TypeMapKind;
4036     (function (TypeMapKind) {
4037         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4038         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4039         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4040         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4041         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4042     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4043     var InferencePriority;
4044     (function (InferencePriority) {
4045         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4046         InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
4047         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 4] = "PartialHomomorphicMappedType";
4048         InferencePriority[InferencePriority["MappedTypeConstraint"] = 8] = "MappedTypeConstraint";
4049         InferencePriority[InferencePriority["ContravariantConditional"] = 16] = "ContravariantConditional";
4050         InferencePriority[InferencePriority["ReturnType"] = 32] = "ReturnType";
4051         InferencePriority[InferencePriority["LiteralKeyof"] = 64] = "LiteralKeyof";
4052         InferencePriority[InferencePriority["NoConstraints"] = 128] = "NoConstraints";
4053         InferencePriority[InferencePriority["AlwaysStrict"] = 256] = "AlwaysStrict";
4054         InferencePriority[InferencePriority["MaxValue"] = 512] = "MaxValue";
4055         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 104] = "PriorityImpliesCombination";
4056         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4057     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4058     /* @internal */
4059     var InferenceFlags;
4060     (function (InferenceFlags) {
4061         InferenceFlags[InferenceFlags["None"] = 0] = "None";
4062         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4063         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4064         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4065     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4066     /**
4067      * Ternary values are defined such that
4068      * x & y is False if either x or y is False.
4069      * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
4070      * x & y is True if both x and y are True.
4071      * x | y is False if both x and y are False.
4072      * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
4073      * x | y is True if either x or y is True.
4074      */
4075     /* @internal */
4076     var Ternary;
4077     (function (Ternary) {
4078         Ternary[Ternary["False"] = 0] = "False";
4079         Ternary[Ternary["Maybe"] = 1] = "Maybe";
4080         Ternary[Ternary["True"] = -1] = "True";
4081     })(Ternary = ts.Ternary || (ts.Ternary = {}));
4082     /* @internal */
4083     var AssignmentDeclarationKind;
4084     (function (AssignmentDeclarationKind) {
4085         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4086         /// exports.name = expr
4087         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4088         /// module.exports = expr
4089         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4090         /// className.prototype.name = expr
4091         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4092         /// this.name = expr
4093         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4094         // F.name = expr
4095         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4096         // F.prototype = { ... }
4097         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4098         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4099         // Object.defineProperty(x, 'name', { get: Function, set: Function });
4100         // Object.defineProperty(x, 'name', { get: Function });
4101         // Object.defineProperty(x, 'name', { set: Function });
4102         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4103         // Object.defineProperty(exports || module.exports, 'name', ...);
4104         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4105         // Object.defineProperty(Foo.prototype, 'name', ...);
4106         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4107     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4108     var DiagnosticCategory;
4109     (function (DiagnosticCategory) {
4110         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4111         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4112         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4113         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4114     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4115     /* @internal */
4116     function diagnosticCategoryName(d, lowerCase) {
4117         if (lowerCase === void 0) { lowerCase = true; }
4118         var name = DiagnosticCategory[d.category];
4119         return lowerCase ? name.toLowerCase() : name;
4120     }
4121     ts.diagnosticCategoryName = diagnosticCategoryName;
4122     var ModuleResolutionKind;
4123     (function (ModuleResolutionKind) {
4124         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4125         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4126     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4127     var WatchFileKind;
4128     (function (WatchFileKind) {
4129         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4130         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4131         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4132         WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4133         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4134     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4135     var WatchDirectoryKind;
4136     (function (WatchDirectoryKind) {
4137         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4138         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4139         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4140     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4141     var PollingWatchKind;
4142     (function (PollingWatchKind) {
4143         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4144         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4145         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4146     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4147     var ModuleKind;
4148     (function (ModuleKind) {
4149         ModuleKind[ModuleKind["None"] = 0] = "None";
4150         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4151         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4152         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4153         ModuleKind[ModuleKind["System"] = 4] = "System";
4154         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4155         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4156         //       module kind).
4157         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4158         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4159         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4160     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4161     var JsxEmit;
4162     (function (JsxEmit) {
4163         JsxEmit[JsxEmit["None"] = 0] = "None";
4164         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4165         JsxEmit[JsxEmit["React"] = 2] = "React";
4166         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4167     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4168     var ImportsNotUsedAsValues;
4169     (function (ImportsNotUsedAsValues) {
4170         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4171         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
4172         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
4173     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
4174     var NewLineKind;
4175     (function (NewLineKind) {
4176         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
4177         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
4178     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
4179     var ScriptKind;
4180     (function (ScriptKind) {
4181         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
4182         ScriptKind[ScriptKind["JS"] = 1] = "JS";
4183         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
4184         ScriptKind[ScriptKind["TS"] = 3] = "TS";
4185         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
4186         ScriptKind[ScriptKind["External"] = 5] = "External";
4187         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
4188         /**
4189          * Used on extensions that doesn't define the ScriptKind but the content defines it.
4190          * Deferred extensions are going to be included in all project contexts.
4191          */
4192         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
4193     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
4194     var ScriptTarget;
4195     (function (ScriptTarget) {
4196         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
4197         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
4198         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
4199         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
4200         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
4201         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
4202         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
4203         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
4204         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
4205         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
4206         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
4207     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
4208     var LanguageVariant;
4209     (function (LanguageVariant) {
4210         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
4211         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
4212     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
4213     var WatchDirectoryFlags;
4214     (function (WatchDirectoryFlags) {
4215         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
4216         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
4217     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
4218     /* @internal */
4219     var CharacterCodes;
4220     (function (CharacterCodes) {
4221         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
4222         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
4223         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
4224         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
4225         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
4226         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
4227         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
4228         // Unicode 3.0 space characters
4229         CharacterCodes[CharacterCodes["space"] = 32] = "space";
4230         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
4231         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
4232         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
4233         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
4234         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
4235         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
4236         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
4237         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
4238         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
4239         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
4240         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
4241         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
4242         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
4243         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
4244         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
4245         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
4246         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
4247         CharacterCodes[CharacterCodes["_"] = 95] = "_";
4248         CharacterCodes[CharacterCodes["$"] = 36] = "$";
4249         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
4250         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
4251         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
4252         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
4253         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
4254         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
4255         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
4256         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
4257         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
4258         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
4259         CharacterCodes[CharacterCodes["a"] = 97] = "a";
4260         CharacterCodes[CharacterCodes["b"] = 98] = "b";
4261         CharacterCodes[CharacterCodes["c"] = 99] = "c";
4262         CharacterCodes[CharacterCodes["d"] = 100] = "d";
4263         CharacterCodes[CharacterCodes["e"] = 101] = "e";
4264         CharacterCodes[CharacterCodes["f"] = 102] = "f";
4265         CharacterCodes[CharacterCodes["g"] = 103] = "g";
4266         CharacterCodes[CharacterCodes["h"] = 104] = "h";
4267         CharacterCodes[CharacterCodes["i"] = 105] = "i";
4268         CharacterCodes[CharacterCodes["j"] = 106] = "j";
4269         CharacterCodes[CharacterCodes["k"] = 107] = "k";
4270         CharacterCodes[CharacterCodes["l"] = 108] = "l";
4271         CharacterCodes[CharacterCodes["m"] = 109] = "m";
4272         CharacterCodes[CharacterCodes["n"] = 110] = "n";
4273         CharacterCodes[CharacterCodes["o"] = 111] = "o";
4274         CharacterCodes[CharacterCodes["p"] = 112] = "p";
4275         CharacterCodes[CharacterCodes["q"] = 113] = "q";
4276         CharacterCodes[CharacterCodes["r"] = 114] = "r";
4277         CharacterCodes[CharacterCodes["s"] = 115] = "s";
4278         CharacterCodes[CharacterCodes["t"] = 116] = "t";
4279         CharacterCodes[CharacterCodes["u"] = 117] = "u";
4280         CharacterCodes[CharacterCodes["v"] = 118] = "v";
4281         CharacterCodes[CharacterCodes["w"] = 119] = "w";
4282         CharacterCodes[CharacterCodes["x"] = 120] = "x";
4283         CharacterCodes[CharacterCodes["y"] = 121] = "y";
4284         CharacterCodes[CharacterCodes["z"] = 122] = "z";
4285         CharacterCodes[CharacterCodes["A"] = 65] = "A";
4286         CharacterCodes[CharacterCodes["B"] = 66] = "B";
4287         CharacterCodes[CharacterCodes["C"] = 67] = "C";
4288         CharacterCodes[CharacterCodes["D"] = 68] = "D";
4289         CharacterCodes[CharacterCodes["E"] = 69] = "E";
4290         CharacterCodes[CharacterCodes["F"] = 70] = "F";
4291         CharacterCodes[CharacterCodes["G"] = 71] = "G";
4292         CharacterCodes[CharacterCodes["H"] = 72] = "H";
4293         CharacterCodes[CharacterCodes["I"] = 73] = "I";
4294         CharacterCodes[CharacterCodes["J"] = 74] = "J";
4295         CharacterCodes[CharacterCodes["K"] = 75] = "K";
4296         CharacterCodes[CharacterCodes["L"] = 76] = "L";
4297         CharacterCodes[CharacterCodes["M"] = 77] = "M";
4298         CharacterCodes[CharacterCodes["N"] = 78] = "N";
4299         CharacterCodes[CharacterCodes["O"] = 79] = "O";
4300         CharacterCodes[CharacterCodes["P"] = 80] = "P";
4301         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
4302         CharacterCodes[CharacterCodes["R"] = 82] = "R";
4303         CharacterCodes[CharacterCodes["S"] = 83] = "S";
4304         CharacterCodes[CharacterCodes["T"] = 84] = "T";
4305         CharacterCodes[CharacterCodes["U"] = 85] = "U";
4306         CharacterCodes[CharacterCodes["V"] = 86] = "V";
4307         CharacterCodes[CharacterCodes["W"] = 87] = "W";
4308         CharacterCodes[CharacterCodes["X"] = 88] = "X";
4309         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
4310         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
4311         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
4312         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
4313         CharacterCodes[CharacterCodes["at"] = 64] = "at";
4314         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
4315         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
4316         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
4317         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
4318         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
4319         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
4320         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
4321         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
4322         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
4323         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
4324         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
4325         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
4326         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
4327         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
4328         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
4329         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
4330         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
4331         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
4332         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
4333         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
4334         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
4335         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
4336         CharacterCodes[CharacterCodes["question"] = 63] = "question";
4337         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
4338         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
4339         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
4340         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
4341         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
4342         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
4343         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
4344         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
4345         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
4346     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
4347     var Extension;
4348     (function (Extension) {
4349         Extension["Ts"] = ".ts";
4350         Extension["Tsx"] = ".tsx";
4351         Extension["Dts"] = ".d.ts";
4352         Extension["Js"] = ".js";
4353         Extension["Jsx"] = ".jsx";
4354         Extension["Json"] = ".json";
4355         Extension["TsBuildInfo"] = ".tsbuildinfo";
4356     })(Extension = ts.Extension || (ts.Extension = {}));
4357     /* @internal */
4358     var TransformFlags;
4359     (function (TransformFlags) {
4360         TransformFlags[TransformFlags["None"] = 0] = "None";
4361         // Facts
4362         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
4363         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
4364         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
4365         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
4366         TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
4367         TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
4368         TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
4369         TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
4370         TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
4371         TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
4372         TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
4373         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
4374         // Markers
4375         // - Flags used to indicate that a subtree contains a specific transformation.
4376         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
4377         TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
4378         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
4379         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
4380         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
4381         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
4382         TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
4383         TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
4384         TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
4385         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
4386         TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
4387         TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
4388         // Please leave this as 1 << 29.
4389         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
4390         // It is a good reminder of how much room we have left
4391         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4392         // Assertions
4393         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
4394         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
4395         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
4396         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
4397         TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
4398         TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
4399         TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
4400         TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
4401         TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
4402         TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
4403         TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
4404         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
4405         // Scope Exclusions
4406         // - Bitmasks that exclude flags from propagating out of a specific context
4407         //   into the subtree flags of their container.
4408         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
4409         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
4410         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
4411         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 538920960] = "ArrowFunctionExcludes";
4412         TransformFlags[TransformFlags["FunctionExcludes"] = 538925056] = "FunctionExcludes";
4413         TransformFlags[TransformFlags["ConstructorExcludes"] = 538923008] = "ConstructorExcludes";
4414         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
4415         TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
4416         TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
4417         TransformFlags[TransformFlags["ModuleExcludes"] = 537991168] = "ModuleExcludes";
4418         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
4419         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
4420         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
4421         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
4422         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
4423         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
4424         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
4425         // Propagating flags
4426         // - Bitmasks for flags that should propagate from a child
4427         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
4428         // Masks
4429         // - Additional bitmasks
4430     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
4431     var EmitFlags;
4432     (function (EmitFlags) {
4433         EmitFlags[EmitFlags["None"] = 0] = "None";
4434         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
4435         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
4436         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
4437         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
4438         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
4439         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
4440         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
4441         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
4442         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
4443         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
4444         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
4445         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
4446         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
4447         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
4448         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
4449         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
4450         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
4451         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
4452         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
4453         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
4454         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
4455         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
4456         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
4457         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
4458         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
4459         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
4460         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
4461         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
4462         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
4463         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
4464         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
4465     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
4466     /**
4467      * Used by the checker, this enum keeps track of external emit helpers that should be type
4468      * checked.
4469      */
4470     /* @internal */
4471     var ExternalEmitHelpers;
4472     (function (ExternalEmitHelpers) {
4473         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
4474         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
4475         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
4476         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
4477         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
4478         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
4479         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
4480         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
4481         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
4482         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
4483         ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
4484         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
4485         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
4486         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
4487         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
4488         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
4489         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
4490         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 131072] = "MakeTemplateObject";
4491         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 262144] = "ClassPrivateFieldGet";
4492         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 524288] = "ClassPrivateFieldSet";
4493         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 1048576] = "CreateBinding";
4494         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
4495         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 1048576] = "LastEmitHelper";
4496         // Helpers included by ES2015 for..of
4497         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
4498         // Helpers included by ES2017 for..await..of
4499         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
4500         // Helpers included by ES2017 async generators
4501         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
4502         // Helpers included by yield* in ES2017 async generators
4503         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
4504         // Helpers included by ES2015 spread
4505         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
4506     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
4507     var EmitHint;
4508     (function (EmitHint) {
4509         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
4510         EmitHint[EmitHint["Expression"] = 1] = "Expression";
4511         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
4512         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
4513         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
4514         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
4515         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
4516     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
4517     /* @internal */
4518     var LexicalEnvironmentFlags;
4519     (function (LexicalEnvironmentFlags) {
4520         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
4521         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
4522         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
4523     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
4524     /*@internal*/
4525     var BundleFileSectionKind;
4526     (function (BundleFileSectionKind) {
4527         BundleFileSectionKind["Prologue"] = "prologue";
4528         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
4529         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
4530         BundleFileSectionKind["Reference"] = "reference";
4531         BundleFileSectionKind["Type"] = "type";
4532         BundleFileSectionKind["Lib"] = "lib";
4533         BundleFileSectionKind["Prepend"] = "prepend";
4534         BundleFileSectionKind["Text"] = "text";
4535         BundleFileSectionKind["Internal"] = "internal";
4536         // comments?
4537     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
4538     var ListFormat;
4539     (function (ListFormat) {
4540         ListFormat[ListFormat["None"] = 0] = "None";
4541         // Line separators
4542         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
4543         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
4544         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
4545         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
4546         // Delimiters
4547         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
4548         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
4549         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
4550         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
4551         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
4552         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
4553         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
4554         // Whitespace
4555         ListFormat[ListFormat["Indented"] = 128] = "Indented";
4556         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
4557         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
4558         // Brackets/Braces
4559         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
4560         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
4561         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
4562         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
4563         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
4564         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
4565         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
4566         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
4567         // Other
4568         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
4569         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
4570         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
4571         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
4572         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
4573         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
4574         // Precomputed Formats
4575         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
4576         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
4577         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
4578         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
4579         ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
4580         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
4581         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
4582         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
4583         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
4584         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
4585         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
4586         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
4587         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
4588         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
4589         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
4590         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
4591         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
4592         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
4593         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
4594         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
4595         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
4596         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
4597         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
4598         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
4599         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
4600         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
4601         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
4602         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
4603         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
4604         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
4605         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
4606         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
4607         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
4608         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
4609         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
4610         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
4611         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
4612     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
4613     /* @internal */
4614     var PragmaKindFlags;
4615     (function (PragmaKindFlags) {
4616         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
4617         /**
4618          * Triple slash comment of the form
4619          * /// <pragma-name argname="value" />
4620          */
4621         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
4622         /**
4623          * Single line comment of the form
4624          * // @pragma-name argval1 argval2
4625          * or
4626          * /// @pragma-name argval1 argval2
4627          */
4628         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
4629         /**
4630          * Multiline non-jsdoc pragma of the form
4631          * /* @pragma-name argval1 argval2 * /
4632          */
4633         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
4634         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
4635         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
4636     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
4637     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
4638     //  fancy effectively defining it twice, once in value-space and once in type-space
4639     /* @internal */
4640     ts.commentPragmas = {
4641         "reference": {
4642             args: [
4643                 { name: "types", optional: true, captureSpan: true },
4644                 { name: "lib", optional: true, captureSpan: true },
4645                 { name: "path", optional: true, captureSpan: true },
4646                 { name: "no-default-lib", optional: true }
4647             ],
4648             kind: 1 /* TripleSlashXML */
4649         },
4650         "amd-dependency": {
4651             args: [{ name: "path" }, { name: "name", optional: true }],
4652             kind: 1 /* TripleSlashXML */
4653         },
4654         "amd-module": {
4655             args: [{ name: "name" }],
4656             kind: 1 /* TripleSlashXML */
4657         },
4658         "ts-check": {
4659             kind: 2 /* SingleLine */
4660         },
4661         "ts-nocheck": {
4662             kind: 2 /* SingleLine */
4663         },
4664         "jsx": {
4665             args: [{ name: "factory" }],
4666             kind: 4 /* MultiLine */
4667         },
4668     };
4669 })(ts || (ts = {}));
4670 var ts;
4671 (function (ts) {
4672     /**
4673      * djb2 hashing algorithm
4674      * http://www.cse.yorku.ca/~oz/hash.html
4675      */
4676     /* @internal */
4677     function generateDjb2Hash(data) {
4678         var acc = 5381;
4679         for (var i = 0; i < data.length; i++) {
4680             acc = ((acc << 5) + acc) + data.charCodeAt(i);
4681         }
4682         return acc.toString();
4683     }
4684     ts.generateDjb2Hash = generateDjb2Hash;
4685     /**
4686      * Set a high stack trace limit to provide more information in case of an error.
4687      * Called for command-line and server use cases.
4688      * Not called if TypeScript is used as a library.
4689      */
4690     /* @internal */
4691     function setStackTraceLimit() {
4692         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
4693             Error.stackTraceLimit = 100;
4694         }
4695     }
4696     ts.setStackTraceLimit = setStackTraceLimit;
4697     var FileWatcherEventKind;
4698     (function (FileWatcherEventKind) {
4699         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
4700         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
4701         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
4702     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
4703     /* @internal */
4704     var PollingInterval;
4705     (function (PollingInterval) {
4706         PollingInterval[PollingInterval["High"] = 2000] = "High";
4707         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
4708         PollingInterval[PollingInterval["Low"] = 250] = "Low";
4709     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
4710     /* @internal */
4711     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
4712     function createPollingIntervalBasedLevels(levels) {
4713         var _a;
4714         return _a = {},
4715             _a[PollingInterval.Low] = levels.Low,
4716             _a[PollingInterval.Medium] = levels.Medium,
4717             _a[PollingInterval.High] = levels.High,
4718             _a;
4719     }
4720     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
4721     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
4722     /* @internal */
4723     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
4724     /* @internal */
4725     function setCustomPollingValues(system) {
4726         if (!system.getEnvironmentVariable) {
4727             return;
4728         }
4729         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
4730         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
4731         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
4732         function getLevel(envVar, level) {
4733             return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
4734         }
4735         function getCustomLevels(baseVariable) {
4736             var customLevels;
4737             setCustomLevel("Low");
4738             setCustomLevel("Medium");
4739             setCustomLevel("High");
4740             return customLevels;
4741             function setCustomLevel(level) {
4742                 var customLevel = getLevel(baseVariable, level);
4743                 if (customLevel) {
4744                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
4745                 }
4746             }
4747         }
4748         function setCustomLevels(baseVariable, levels) {
4749             var customLevels = getCustomLevels(baseVariable);
4750             if (customLevels) {
4751                 setLevel("Low");
4752                 setLevel("Medium");
4753                 setLevel("High");
4754                 return true;
4755             }
4756             return false;
4757             function setLevel(level) {
4758                 levels[level] = customLevels[level] || levels[level];
4759             }
4760         }
4761         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
4762             var customLevels = getCustomLevels(baseVariable);
4763             return (pollingIntervalChanged || customLevels) &&
4764                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
4765         }
4766     }
4767     ts.setCustomPollingValues = setCustomPollingValues;
4768     /* @internal */
4769     function createDynamicPriorityPollingWatchFile(host) {
4770         var watchedFiles = [];
4771         var changedFilesInLastPoll = [];
4772         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
4773         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
4774         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
4775         return watchFile;
4776         function watchFile(fileName, callback, defaultPollingInterval) {
4777             var file = {
4778                 fileName: fileName,
4779                 callback: callback,
4780                 unchangedPolls: 0,
4781                 mtime: getModifiedTime(fileName)
4782             };
4783             watchedFiles.push(file);
4784             addToPollingIntervalQueue(file, defaultPollingInterval);
4785             return {
4786                 close: function () {
4787                     file.isClosed = true;
4788                     // Remove from watchedFiles
4789                     ts.unorderedRemoveItem(watchedFiles, file);
4790                     // Do not update polling interval queue since that will happen as part of polling
4791                 }
4792             };
4793         }
4794         function createPollingIntervalQueue(pollingInterval) {
4795             var queue = [];
4796             queue.pollingInterval = pollingInterval;
4797             queue.pollIndex = 0;
4798             queue.pollScheduled = false;
4799             return queue;
4800         }
4801         function pollPollingIntervalQueue(queue) {
4802             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
4803             // Set the next polling index and timeout
4804             if (queue.length) {
4805                 scheduleNextPoll(queue.pollingInterval);
4806             }
4807             else {
4808                 ts.Debug.assert(queue.pollIndex === 0);
4809                 queue.pollScheduled = false;
4810             }
4811         }
4812         function pollLowPollingIntervalQueue(queue) {
4813             // Always poll complete list of changedFilesInLastPoll
4814             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
4815             // Finally do the actual polling of the queue
4816             pollPollingIntervalQueue(queue);
4817             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
4818             // as pollPollingIntervalQueue wont schedule for next poll
4819             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
4820                 scheduleNextPoll(PollingInterval.Low);
4821             }
4822         }
4823         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
4824             // Max visit would be all elements of the queue
4825             var needsVisit = queue.length;
4826             var definedValueCopyToIndex = pollIndex;
4827             for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
4828                 var watchedFile = queue[pollIndex];
4829                 if (!watchedFile) {
4830                     continue;
4831                 }
4832                 else if (watchedFile.isClosed) {
4833                     queue[pollIndex] = undefined;
4834                     continue;
4835                 }
4836                 polled++;
4837                 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
4838                 if (watchedFile.isClosed) {
4839                     // Closed watcher as part of callback
4840                     queue[pollIndex] = undefined;
4841                 }
4842                 else if (fileChanged) {
4843                     watchedFile.unchangedPolls = 0;
4844                     // Changed files go to changedFilesInLastPoll queue
4845                     if (queue !== changedFilesInLastPoll) {
4846                         queue[pollIndex] = undefined;
4847                         addChangedFileToLowPollingIntervalQueue(watchedFile);
4848                     }
4849                 }
4850                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
4851                     watchedFile.unchangedPolls++;
4852                 }
4853                 else if (queue === changedFilesInLastPoll) {
4854                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
4855                     watchedFile.unchangedPolls = 1;
4856                     queue[pollIndex] = undefined;
4857                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
4858                 }
4859                 else if (pollingInterval !== PollingInterval.High) {
4860                     watchedFile.unchangedPolls++;
4861                     queue[pollIndex] = undefined;
4862                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
4863                 }
4864                 if (queue[pollIndex]) {
4865                     // Copy this file to the non hole location
4866                     if (definedValueCopyToIndex < pollIndex) {
4867                         queue[definedValueCopyToIndex] = watchedFile;
4868                         queue[pollIndex] = undefined;
4869                     }
4870                     definedValueCopyToIndex++;
4871                 }
4872             }
4873             // Return next poll index
4874             return pollIndex;
4875             function nextPollIndex() {
4876                 pollIndex++;
4877                 if (pollIndex === queue.length) {
4878                     if (definedValueCopyToIndex < pollIndex) {
4879                         // There are holes from nextDefinedValueIndex to end of queue, change queue size
4880                         queue.length = definedValueCopyToIndex;
4881                     }
4882                     pollIndex = 0;
4883                     definedValueCopyToIndex = 0;
4884                 }
4885             }
4886         }
4887         function pollingIntervalQueue(pollingInterval) {
4888             switch (pollingInterval) {
4889                 case PollingInterval.Low:
4890                     return lowPollingIntervalQueue;
4891                 case PollingInterval.Medium:
4892                     return mediumPollingIntervalQueue;
4893                 case PollingInterval.High:
4894                     return highPollingIntervalQueue;
4895             }
4896         }
4897         function addToPollingIntervalQueue(file, pollingInterval) {
4898             pollingIntervalQueue(pollingInterval).push(file);
4899             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
4900         }
4901         function addChangedFileToLowPollingIntervalQueue(file) {
4902             changedFilesInLastPoll.push(file);
4903             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
4904         }
4905         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
4906             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
4907                 scheduleNextPoll(pollingInterval);
4908             }
4909         }
4910         function scheduleNextPoll(pollingInterval) {
4911             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
4912         }
4913         function getModifiedTime(fileName) {
4914             return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
4915         }
4916     }
4917     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
4918     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
4919         // One file can have multiple watchers
4920         var fileWatcherCallbacks = ts.createMultiMap();
4921         var dirWatchers = ts.createMap();
4922         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4923         return nonPollingWatchFile;
4924         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
4925             var filePath = toCanonicalName(fileName);
4926             fileWatcherCallbacks.add(filePath, callback);
4927             var dirPath = ts.getDirectoryPath(filePath) || ".";
4928             var watcher = dirWatchers.get(dirPath) ||
4929                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
4930             watcher.referenceCount++;
4931             return {
4932                 close: function () {
4933                     if (watcher.referenceCount === 1) {
4934                         watcher.close();
4935                         dirWatchers.delete(dirPath);
4936                     }
4937                     else {
4938                         watcher.referenceCount--;
4939                     }
4940                     fileWatcherCallbacks.remove(filePath, callback);
4941                 }
4942             };
4943         }
4944         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
4945             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
4946                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
4947                 if (!ts.isString(relativeFileName)) {
4948                     return;
4949                 }
4950                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
4951                 // Some applications save a working file via rename operations
4952                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
4953                 if (callbacks) {
4954                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
4955                         var fileCallback = callbacks_1[_i];
4956                         fileCallback(fileName, FileWatcherEventKind.Changed);
4957                     }
4958                 }
4959             }, 
4960             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
4961             watcher.referenceCount = 0;
4962             dirWatchers.set(dirPath, watcher);
4963             return watcher;
4964         }
4965     }
4966     /* @internal */
4967     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
4968         var cache = ts.createMap();
4969         var callbacksCache = ts.createMultiMap();
4970         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4971         return function (fileName, callback, pollingInterval, options) {
4972             var path = toCanonicalFileName(fileName);
4973             var existing = cache.get(path);
4974             if (existing) {
4975                 existing.refCount++;
4976             }
4977             else {
4978                 cache.set(path, {
4979                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
4980                     refCount: 1
4981                 });
4982             }
4983             callbacksCache.add(path, callback);
4984             return {
4985                 close: function () {
4986                     var watcher = ts.Debug.checkDefined(cache.get(path));
4987                     callbacksCache.remove(path, callback);
4988                     watcher.refCount--;
4989                     if (watcher.refCount)
4990                         return;
4991                     cache.delete(path);
4992                     ts.closeFileWatcherOf(watcher);
4993                 }
4994             };
4995         };
4996     }
4997     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
4998     /**
4999      * Returns true if file status changed
5000      */
5001     /*@internal*/
5002     function onWatchedFileStat(watchedFile, modifiedTime) {
5003         var oldTime = watchedFile.mtime.getTime();
5004         var newTime = modifiedTime.getTime();
5005         if (oldTime !== newTime) {
5006             watchedFile.mtime = modifiedTime;
5007             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
5008             return true;
5009         }
5010         return false;
5011     }
5012     ts.onWatchedFileStat = onWatchedFileStat;
5013     /*@internal*/
5014     function getFileWatcherEventKind(oldTime, newTime) {
5015         return oldTime === 0
5016             ? FileWatcherEventKind.Created
5017             : newTime === 0
5018                 ? FileWatcherEventKind.Deleted
5019                 : FileWatcherEventKind.Changed;
5020     }
5021     ts.getFileWatcherEventKind = getFileWatcherEventKind;
5022     /*@internal*/
5023     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
5024     /*@internal*/
5025     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
5026     /*@internal*/
5027     function setSysLog(logger) {
5028         ts.sysLog = logger;
5029     }
5030     ts.setSysLog = setSysLog;
5031     /**
5032      * Watch the directory recursively using host provided method to watch child directories
5033      * that means if this is recursive watcher, watch the children directories as well
5034      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
5035      */
5036     /*@internal*/
5037     function createDirectoryWatcherSupportingRecursive(host) {
5038         var cache = ts.createMap();
5039         var callbackCache = ts.createMultiMap();
5040         var cacheToUpdateChildWatches = ts.createMap();
5041         var timerToUpdateChildWatches;
5042         var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
5043         var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
5044         return function (dirName, callback, recursive, options) { return recursive ?
5045             createDirectoryWatcher(dirName, options, callback) :
5046             host.watchDirectory(dirName, callback, recursive, options); };
5047         /**
5048          * Create the directory watcher for the dirPath.
5049          */
5050         function createDirectoryWatcher(dirName, options, callback) {
5051             var dirPath = toCanonicalFilePath(dirName);
5052             var directoryWatcher = cache.get(dirPath);
5053             if (directoryWatcher) {
5054                 directoryWatcher.refCount++;
5055             }
5056             else {
5057                 directoryWatcher = {
5058                     watcher: host.watchDirectory(dirName, function (fileName) {
5059                         if (isIgnoredPath(fileName))
5060                             return;
5061                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
5062                             // Call the actual callback
5063                             invokeCallbacks(dirPath, fileName);
5064                             // Iterate through existing children and update the watches if needed
5065                             updateChildWatches(dirName, dirPath, options);
5066                         }
5067                         else {
5068                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
5069                         }
5070                     }, /*recursive*/ false, options),
5071                     refCount: 1,
5072                     childWatches: ts.emptyArray
5073                 };
5074                 cache.set(dirPath, directoryWatcher);
5075                 updateChildWatches(dirName, dirPath, options);
5076             }
5077             var callbackToAdd = callback && { dirName: dirName, callback: callback };
5078             if (callbackToAdd) {
5079                 callbackCache.add(dirPath, callbackToAdd);
5080             }
5081             return {
5082                 dirName: dirName,
5083                 close: function () {
5084                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
5085                     if (callbackToAdd)
5086                         callbackCache.remove(dirPath, callbackToAdd);
5087                     directoryWatcher.refCount--;
5088                     if (directoryWatcher.refCount)
5089                         return;
5090                     cache.delete(dirPath);
5091                     ts.closeFileWatcherOf(directoryWatcher);
5092                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
5093                 }
5094             };
5095         }
5096         function invokeCallbacks(dirPath, fileNameOrInvokeMap) {
5097             var fileName;
5098             var invokeMap;
5099             if (ts.isString(fileNameOrInvokeMap)) {
5100                 fileName = fileNameOrInvokeMap;
5101             }
5102             else {
5103                 invokeMap = fileNameOrInvokeMap;
5104             }
5105             // Call the actual callback
5106             callbackCache.forEach(function (callbacks, rootDirName) {
5107                 if (invokeMap && invokeMap.has(rootDirName))
5108                     return;
5109                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
5110                     if (invokeMap) {
5111                         invokeMap.set(rootDirName, true);
5112                     }
5113                     else {
5114                         callbacks.forEach(function (_a) {
5115                             var callback = _a.callback;
5116                             return callback(fileName);
5117                         });
5118                     }
5119                 }
5120             });
5121         }
5122         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
5123             // Iterate through existing children and update the watches if needed
5124             var parentWatcher = cache.get(dirPath);
5125             if (parentWatcher && host.directoryExists(dirName)) {
5126                 // Schedule the update and postpone invoke for callbacks
5127                 scheduleUpdateChildWatches(dirName, dirPath, options);
5128                 return;
5129             }
5130             // Call the actual callbacks and remove child watches
5131             invokeCallbacks(dirPath, fileName);
5132             removeChildWatches(parentWatcher);
5133         }
5134         function scheduleUpdateChildWatches(dirName, dirPath, options) {
5135             if (!cacheToUpdateChildWatches.has(dirPath)) {
5136                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options });
5137             }
5138             if (timerToUpdateChildWatches) {
5139                 host.clearTimeout(timerToUpdateChildWatches);
5140                 timerToUpdateChildWatches = undefined;
5141             }
5142             timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
5143         }
5144         function onTimerToUpdateChildWatches() {
5145             timerToUpdateChildWatches = undefined;
5146             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
5147             var start = ts.timestamp();
5148             var invokeMap = ts.createMap();
5149             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
5150                 var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, done = _a.done;
5151                 ts.Debug.assert(!done);
5152                 cacheToUpdateChildWatches.delete(dirPath);
5153                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
5154                 // to ensure that all the changes are reflected at this time
5155                 invokeCallbacks(dirPath, invokeMap);
5156                 updateChildWatches(dirName, dirPath, options);
5157             }
5158             ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
5159             callbackCache.forEach(function (callbacks, rootDirName) {
5160                 if (invokeMap.has(rootDirName)) {
5161                     callbacks.forEach(function (_a) {
5162                         var callback = _a.callback, dirName = _a.dirName;
5163                         return callback(dirName);
5164                     });
5165                 }
5166             });
5167             var elapsed = ts.timestamp() - start;
5168             ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
5169         }
5170         function removeChildWatches(parentWatcher) {
5171             if (!parentWatcher)
5172                 return;
5173             var existingChildWatches = parentWatcher.childWatches;
5174             parentWatcher.childWatches = ts.emptyArray;
5175             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
5176                 var childWatcher = existingChildWatches_1[_i];
5177                 childWatcher.close();
5178                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
5179             }
5180         }
5181         function updateChildWatches(dirName, dirPath, options) {
5182             // Iterate through existing children and update the watches if needed
5183             var parentWatcher = cache.get(dirPath);
5184             if (parentWatcher) {
5185                 parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches, options);
5186             }
5187         }
5188         /**
5189          * Watch the directories in the parentDir
5190          */
5191         function watchChildDirectories(parentDir, existingChildWatches, options) {
5192             var newChildWatches;
5193             ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
5194                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
5195                 // Filter our the symbolic link directories since those arent included in recursive watch
5196                 // which is same behaviour when recursive: true is passed to fs.watch
5197                 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
5198             }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
5199             return newChildWatches || ts.emptyArray;
5200             /**
5201              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
5202              */
5203             function createAndAddChildDirectoryWatcher(childName) {
5204                 var result = createDirectoryWatcher(childName, options);
5205                 addChildDirectoryWatcher(result);
5206             }
5207             /**
5208              * Add child directory watcher to the new ChildDirectoryWatcher list
5209              */
5210             function addChildDirectoryWatcher(childWatcher) {
5211                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
5212             }
5213         }
5214         function isIgnoredPath(path) {
5215             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
5216         }
5217         function isInPath(path, searchPath) {
5218             if (ts.stringContains(path, searchPath))
5219                 return true;
5220             if (host.useCaseSensitiveFileNames)
5221                 return false;
5222             return ts.stringContains(toCanonicalFilePath(path), searchPath);
5223         }
5224     }
5225     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
5226     /*@internal*/
5227     var FileSystemEntryKind;
5228     (function (FileSystemEntryKind) {
5229         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
5230         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
5231     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
5232     /*@internal*/
5233     function createFileWatcherCallback(callback) {
5234         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
5235     }
5236     ts.createFileWatcherCallback = createFileWatcherCallback;
5237     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
5238         return function (eventName) {
5239             if (eventName === "rename") {
5240                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
5241             }
5242             else {
5243                 // Change
5244                 callback(fileName, FileWatcherEventKind.Changed);
5245             }
5246         };
5247     }
5248     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
5249         return function (eventName, relativeFileName) {
5250             // In watchDirectory we only care about adding and removing files (when event name is
5251             // "rename"); changes made within files are handled by corresponding fileWatchers (when
5252             // event name is "change")
5253             if (eventName === "rename") {
5254                 // When deleting a file, the passed baseFileName is null
5255                 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
5256             }
5257         };
5258     }
5259     /*@internal*/
5260     function createSystemWatchFunctions(_a) {
5261         var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory;
5262         var dynamicPollingWatchFile;
5263         var nonPollingWatchFile;
5264         var hostRecursiveDirectoryWatcher;
5265         return {
5266             watchFile: watchFile,
5267             watchDirectory: watchDirectory
5268         };
5269         function watchFile(fileName, callback, pollingInterval, options) {
5270             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
5271             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
5272             switch (watchFileKind) {
5273                 case ts.WatchFileKind.FixedPollingInterval:
5274                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
5275                 case ts.WatchFileKind.PriorityPollingInterval:
5276                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
5277                 case ts.WatchFileKind.DynamicPriorityPolling:
5278                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
5279                 case ts.WatchFileKind.UseFsEvents:
5280                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
5281                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
5282                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
5283                     if (!nonPollingWatchFile) {
5284                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
5285                     }
5286                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
5287                 default:
5288                     ts.Debug.assertNever(watchFileKind);
5289             }
5290         }
5291         function ensureDynamicPollingWatchFile() {
5292             return dynamicPollingWatchFile ||
5293                 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
5294         }
5295         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
5296             if (options && options.watchFile !== undefined)
5297                 return options;
5298             switch (tscWatchFile) {
5299                 case "PriorityPollingInterval":
5300                     // Use polling interval based on priority when create watch using host.watchFile
5301                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
5302                 case "DynamicPriorityPolling":
5303                     // Use polling interval but change the interval depending on file changes and their default polling interval
5304                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
5305                 case "UseFsEvents":
5306                     // Use notifications from FS to watch with falling back to fs.watchFile
5307                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
5308                 case "UseFsEventsWithFallbackDynamicPolling":
5309                     // Use notifications from FS to watch with falling back to dynamic watch file
5310                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
5311                 case "UseFsEventsOnParentDirectory":
5312                     useNonPollingWatchers = true;
5313                 // fall through
5314                 default:
5315                     return useNonPollingWatchers ?
5316                         // Use notifications from FS to watch with falling back to fs.watchFile
5317                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
5318                         // Default to do not use fixed polling interval
5319                         { watchFile: ts.WatchFileKind.FixedPollingInterval };
5320             }
5321         }
5322         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
5323             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5324             return {
5325                 watchFile: watchFile,
5326                 fallbackPolling: defaultFallbackPolling === undefined ?
5327                     fallbackPolling :
5328                     defaultFallbackPolling
5329             };
5330         }
5331         function watchDirectory(directoryName, callback, recursive, options) {
5332             if (fsSupportsRecursiveFsWatch) {
5333                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5334             }
5335             if (!hostRecursiveDirectoryWatcher) {
5336                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
5337                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5338                     directoryExists: directoryExists,
5339                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
5340                     watchDirectory: nonRecursiveWatchDirectory,
5341                     realpath: realpath,
5342                     setTimeout: setTimeout,
5343                     clearTimeout: clearTimeout
5344                 });
5345             }
5346             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
5347         }
5348         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
5349             ts.Debug.assert(!recursive);
5350             options = updateOptionsForWatchDirectory(options);
5351             var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
5352             switch (watchDirectoryKind) {
5353                 case ts.WatchDirectoryKind.FixedPollingInterval:
5354                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5355                     /*options*/ undefined);
5356                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
5357                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5358                     /*options*/ undefined);
5359                 case ts.WatchDirectoryKind.UseFsEvents:
5360                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5361                 default:
5362                     ts.Debug.assertNever(watchDirectoryKind);
5363             }
5364         }
5365         function updateOptionsForWatchDirectory(options) {
5366             if (options && options.watchDirectory !== undefined)
5367                 return options;
5368             switch (tscWatchDirectory) {
5369                 case "RecursiveDirectoryUsingFsWatchFile":
5370                     // Use polling interval based on priority when create watch using host.watchFile
5371                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
5372                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
5373                     // Use polling interval but change the interval depending on file changes and their default polling interval
5374                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
5375                 default:
5376                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5377                     return {
5378                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
5379                         fallbackPolling: defaultFallbackPolling !== undefined ?
5380                             defaultFallbackPolling :
5381                             undefined
5382                     };
5383             }
5384         }
5385     }
5386     ts.createSystemWatchFunctions = createSystemWatchFunctions;
5387     /**
5388      * patch writefile to create folder before writing the file
5389      */
5390     /*@internal*/
5391     function patchWriteFileEnsuringDirectory(sys) {
5392         // patch writefile to create folder before writing the file
5393         var originalWriteFile = sys.writeFile;
5394         sys.writeFile = function (path, data, writeBom) {
5395             return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); });
5396         };
5397     }
5398     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
5399     function getNodeMajorVersion() {
5400         if (typeof process === "undefined") {
5401             return undefined;
5402         }
5403         var version = process.version;
5404         if (!version) {
5405             return undefined;
5406         }
5407         var dot = version.indexOf(".");
5408         if (dot === -1) {
5409             return undefined;
5410         }
5411         return parseInt(version.substring(1, dot));
5412     }
5413     ts.getNodeMajorVersion = getNodeMajorVersion;
5414     // TODO: GH#18217 this is used as if it's certainly defined in many places.
5415     // eslint-disable-next-line prefer-const
5416     ts.sys = (function () {
5417         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
5418         // byte order mark from the specified encoding. Using any other byte order mark does
5419         // not actually work.
5420         var byteOrderMarkIndicator = "\uFEFF";
5421         function getNodeSystem() {
5422             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
5423             var _fs = require("fs");
5424             var _path = require("path");
5425             var _os = require("os");
5426             // crypto can be absent on reduced node installations
5427             var _crypto;
5428             try {
5429                 _crypto = require("crypto");
5430             }
5431             catch (_a) {
5432                 _crypto = undefined;
5433             }
5434             var activeSession;
5435             var profilePath = "./profile.cpuprofile";
5436             var Buffer = require("buffer").Buffer;
5437             var nodeVersion = getNodeMajorVersion();
5438             var isNode4OrLater = nodeVersion >= 4;
5439             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
5440             var platform = _os.platform();
5441             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
5442             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
5443             var _b = createSystemWatchFunctions({
5444                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
5445                 getModifiedTime: getModifiedTime,
5446                 setTimeout: setTimeout,
5447                 clearTimeout: clearTimeout,
5448                 fsWatch: fsWatch,
5449                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5450                 fileExists: fileExists,
5451                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5452                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5453                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
5454                 directoryExists: directoryExists,
5455                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
5456                 realpath: realpath,
5457                 tscWatchFile: process.env.TSC_WATCHFILE,
5458                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
5459                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
5460             }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
5461             var nodeSystem = {
5462                 args: process.argv.slice(2),
5463                 newLine: _os.EOL,
5464                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5465                 write: function (s) {
5466                     process.stdout.write(s);
5467                 },
5468                 writeOutputIsTTY: function () {
5469                     return process.stdout.isTTY;
5470                 },
5471                 readFile: readFile,
5472                 writeFile: writeFile,
5473                 watchFile: watchFile,
5474                 watchDirectory: watchDirectory,
5475                 resolvePath: function (path) { return _path.resolve(path); },
5476                 fileExists: fileExists,
5477                 directoryExists: directoryExists,
5478                 createDirectory: function (directoryName) {
5479                     if (!nodeSystem.directoryExists(directoryName)) {
5480                         // Wrapped in a try-catch to prevent crashing if we are in a race
5481                         // with another copy of ourselves to create the same directory
5482                         try {
5483                             _fs.mkdirSync(directoryName);
5484                         }
5485                         catch (e) {
5486                             if (e.code !== "EEXIST") {
5487                                 // Failed for some other reason (access denied?); still throw
5488                                 throw e;
5489                             }
5490                         }
5491                     }
5492                 },
5493                 getExecutingFilePath: function () {
5494                     return __filename;
5495                 },
5496                 getCurrentDirectory: function () {
5497                     return process.cwd();
5498                 },
5499                 getDirectories: getDirectories,
5500                 getEnvironmentVariable: function (name) {
5501                     return process.env[name] || "";
5502                 },
5503                 readDirectory: readDirectory,
5504                 getModifiedTime: getModifiedTime,
5505                 setModifiedTime: setModifiedTime,
5506                 deleteFile: deleteFile,
5507                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
5508                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
5509                 getMemoryUsage: function () {
5510                     if (global.gc) {
5511                         global.gc();
5512                     }
5513                     return process.memoryUsage().heapUsed;
5514                 },
5515                 getFileSize: function (path) {
5516                     try {
5517                         var stat = _fs.statSync(path);
5518                         if (stat.isFile()) {
5519                             return stat.size;
5520                         }
5521                     }
5522                     catch ( /*ignore*/_a) { /*ignore*/ }
5523                     return 0;
5524                 },
5525                 exit: function (exitCode) {
5526                     disableCPUProfiler(function () { return process.exit(exitCode); });
5527                 },
5528                 enableCPUProfiler: enableCPUProfiler,
5529                 disableCPUProfiler: disableCPUProfiler,
5530                 realpath: realpath,
5531                 debugMode: !!process.env.NODE_INSPECTOR_IPC || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
5532                 tryEnableSourceMapsForHost: function () {
5533                     try {
5534                         require("source-map-support").install();
5535                     }
5536                     catch (_a) {
5537                         // Could not enable source maps.
5538                     }
5539                 },
5540                 setTimeout: setTimeout,
5541                 clearTimeout: clearTimeout,
5542                 clearScreen: function () {
5543                     process.stdout.write("\x1Bc");
5544                 },
5545                 setBlocking: function () {
5546                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
5547                         process.stdout._handle.setBlocking(true);
5548                     }
5549                 },
5550                 bufferFrom: bufferFrom,
5551                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
5552                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
5553                 require: function (baseDir, moduleName) {
5554                     try {
5555                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
5556                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
5557                     }
5558                     catch (error) {
5559                         return { module: undefined, modulePath: undefined, error: error };
5560                     }
5561                 }
5562             };
5563             return nodeSystem;
5564             /**
5565              * Uses the builtin inspector APIs to capture a CPU profile
5566              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
5567              */
5568             function enableCPUProfiler(path, cb) {
5569                 if (activeSession) {
5570                     cb();
5571                     return false;
5572                 }
5573                 var inspector = require("inspector");
5574                 if (!inspector || !inspector.Session) {
5575                     cb();
5576                     return false;
5577                 }
5578                 var session = new inspector.Session();
5579                 session.connect();
5580                 session.post("Profiler.enable", function () {
5581                     session.post("Profiler.start", function () {
5582                         activeSession = session;
5583                         profilePath = path;
5584                         cb();
5585                     });
5586                 });
5587                 return true;
5588             }
5589             /**
5590              * Strips non-TS paths from the profile, so users with private projects shouldn't
5591              * need to worry about leaking paths by submitting a cpu profile to us
5592              */
5593             function cleanupPaths(profile) {
5594                 var externalFileCounter = 0;
5595                 var remappedPaths = ts.createMap();
5596                 var normalizedDir = ts.normalizeSlashes(__dirname);
5597                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
5598                 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
5599                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
5600                     var node = _a[_i];
5601                     if (node.callFrame.url) {
5602                         var url = ts.normalizeSlashes(node.callFrame.url);
5603                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
5604                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
5605                         }
5606                         else if (!nativePattern.test(url)) {
5607                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
5608                             externalFileCounter++;
5609                         }
5610                     }
5611                 }
5612                 return profile;
5613             }
5614             function disableCPUProfiler(cb) {
5615                 if (activeSession && activeSession !== "stopping") {
5616                     var s_1 = activeSession;
5617                     activeSession.post("Profiler.stop", function (err, _a) {
5618                         var profile = _a.profile;
5619                         if (!err) {
5620                             try {
5621                                 if (_fs.statSync(profilePath).isDirectory()) {
5622                                     profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
5623                                 }
5624                             }
5625                             catch (_b) {
5626                                 // do nothing and ignore fallible fs operation
5627                             }
5628                             try {
5629                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
5630                             }
5631                             catch (_c) {
5632                                 // do nothing and ignore fallible fs operation
5633                             }
5634                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
5635                         }
5636                         activeSession = undefined;
5637                         s_1.disconnect();
5638                         cb();
5639                     });
5640                     activeSession = "stopping";
5641                     return true;
5642                 }
5643                 else {
5644                     cb();
5645                     return false;
5646                 }
5647             }
5648             function bufferFrom(input, encoding) {
5649                 // See https://github.com/Microsoft/TypeScript/issues/25652
5650                 return Buffer.from && Buffer.from !== Int8Array.from
5651                     ? Buffer.from(input, encoding)
5652                     : new Buffer(input, encoding);
5653             }
5654             function isFileSystemCaseSensitive() {
5655                 // win32\win64 are case insensitive platforms
5656                 if (platform === "win32" || platform === "win64") {
5657                     return false;
5658                 }
5659                 // If this file exists under a different case, we must be case-insensitve.
5660                 return !fileExists(swapCase(__filename));
5661             }
5662             /** Convert all lowercase chars to uppercase, and vice-versa */
5663             function swapCase(s) {
5664                 return s.replace(/\w/g, function (ch) {
5665                     var up = ch.toUpperCase();
5666                     return ch === up ? ch.toLowerCase() : up;
5667                 });
5668             }
5669             function fsWatchFileWorker(fileName, callback, pollingInterval) {
5670                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
5671                 var eventKind;
5672                 return {
5673                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
5674                 };
5675                 function fileChanged(curr, prev) {
5676                     // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears)
5677                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
5678                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
5679                     if (+curr.mtime === 0) {
5680                         if (isPreviouslyDeleted) {
5681                             // Already deleted file, no need to callback again
5682                             return;
5683                         }
5684                         eventKind = FileWatcherEventKind.Deleted;
5685                     }
5686                     else if (isPreviouslyDeleted) {
5687                         eventKind = FileWatcherEventKind.Created;
5688                     }
5689                     // If there is no change in modified time, ignore the event
5690                     else if (+curr.mtime === +prev.mtime) {
5691                         return;
5692                     }
5693                     else {
5694                         // File changed
5695                         eventKind = FileWatcherEventKind.Changed;
5696                     }
5697                     callback(fileName, eventKind);
5698                 }
5699             }
5700             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
5701                 var options;
5702                 var lastDirectoryPartWithDirectorySeparator;
5703                 var lastDirectoryPart;
5704                 if (isLinuxOrMacOs) {
5705                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
5706                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
5707                 }
5708                 /** Watcher for the file system entry depending on whether it is missing or present */
5709                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5710                     watchMissingFileSystemEntry() :
5711                     watchPresentFileSystemEntry();
5712                 return {
5713                     close: function () {
5714                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
5715                         watcher.close();
5716                         watcher = undefined;
5717                     }
5718                 };
5719                 /**
5720                  * Invoke the callback with rename and update the watcher if not closed
5721                  * @param createWatcher
5722                  */
5723                 function invokeCallbackAndUpdateWatcher(createWatcher) {
5724                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
5725                     // Call the callback for current directory
5726                     callback("rename", "");
5727                     // If watcher is not closed, update it
5728                     if (watcher) {
5729                         watcher.close();
5730                         watcher = createWatcher();
5731                     }
5732                 }
5733                 /**
5734                  * Watch the file or directory that is currently present
5735                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
5736                  */
5737                 function watchPresentFileSystemEntry() {
5738                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5739                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5740                     if (options === undefined) {
5741                         if (fsSupportsRecursiveFsWatch) {
5742                             options = { persistent: true, recursive: !!recursive };
5743                         }
5744                         else {
5745                             options = { persistent: true };
5746                         }
5747                     }
5748                     try {
5749                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
5750                             callbackChangingToMissingFileSystemEntry :
5751                             callback);
5752                         // Watch the missing file or directory or error
5753                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
5754                         return presentWatcher;
5755                     }
5756                     catch (e) {
5757                         // Catch the exception and use polling instead
5758                         // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point
5759                         // so instead of throwing error, use fs.watchFile
5760                         return watchPresentFileSystemEntryWithFsWatchFile();
5761                     }
5762                 }
5763                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
5764                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
5765                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
5766                     return event === "rename" &&
5767                         (!relativeName ||
5768                             relativeName === lastDirectoryPart ||
5769                             relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
5770                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5771                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
5772                         callback(event, relativeName);
5773                 }
5774                 /**
5775                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
5776                  * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point
5777                  */
5778                 function watchPresentFileSystemEntryWithFsWatchFile() {
5779                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
5780                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
5781                 }
5782                 /**
5783                  * Watch the file or directory that is missing
5784                  * and switch to existing file or directory when the missing filesystem entry is created
5785                  */
5786                 function watchMissingFileSystemEntry() {
5787                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
5788                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
5789                             // Call the callback for current file or directory
5790                             // For now it could be callback for the inner directory creation,
5791                             // but just return current directory, better than current no-op
5792                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
5793                         }
5794                     }, fallbackPollingInterval, fallbackOptions);
5795                 }
5796             }
5797             function readFileWorker(fileName, _encoding) {
5798                 var buffer;
5799                 try {
5800                     buffer = _fs.readFileSync(fileName);
5801                 }
5802                 catch (e) {
5803                     return undefined;
5804                 }
5805                 var len = buffer.length;
5806                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
5807                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
5808                     // flip all byte pairs and treat as little endian.
5809                     len &= ~1; // Round down to a multiple of 2
5810                     for (var i = 0; i < len; i += 2) {
5811                         var temp = buffer[i];
5812                         buffer[i] = buffer[i + 1];
5813                         buffer[i + 1] = temp;
5814                     }
5815                     return buffer.toString("utf16le", 2);
5816                 }
5817                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
5818                     // Little endian UTF-16 byte order mark detected
5819                     return buffer.toString("utf16le", 2);
5820                 }
5821                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
5822                     // UTF-8 byte order mark detected
5823                     return buffer.toString("utf8", 3);
5824                 }
5825                 // Default is UTF-8 with no byte order mark
5826                 return buffer.toString("utf8");
5827             }
5828             function readFile(fileName, _encoding) {
5829                 ts.perfLogger.logStartReadFile(fileName);
5830                 var file = readFileWorker(fileName, _encoding);
5831                 ts.perfLogger.logStopReadFile();
5832                 return file;
5833             }
5834             function writeFile(fileName, data, writeByteOrderMark) {
5835                 ts.perfLogger.logEvent("WriteFile: " + fileName);
5836                 // If a BOM is required, emit one
5837                 if (writeByteOrderMark) {
5838                     data = byteOrderMarkIndicator + data;
5839                 }
5840                 var fd;
5841                 try {
5842                     fd = _fs.openSync(fileName, "w");
5843                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
5844                 }
5845                 finally {
5846                     if (fd !== undefined) {
5847                         _fs.closeSync(fd);
5848                     }
5849                 }
5850             }
5851             function getAccessibleFileSystemEntries(path) {
5852                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
5853                 try {
5854                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
5855                     var files = [];
5856                     var directories = [];
5857                     for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
5858                         var dirent = entries_2[_i];
5859                         // withFileTypes is not supported before Node 10.10.
5860                         var entry = typeof dirent === "string" ? dirent : dirent.name;
5861                         // This is necessary because on some file system node fails to exclude
5862                         // "." and "..". See https://github.com/nodejs/node/issues/4002
5863                         if (entry === "." || entry === "..") {
5864                             continue;
5865                         }
5866                         var stat = void 0;
5867                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
5868                             var name = ts.combinePaths(path, entry);
5869                             try {
5870                                 stat = _fs.statSync(name);
5871                             }
5872                             catch (e) {
5873                                 continue;
5874                             }
5875                         }
5876                         else {
5877                             stat = dirent;
5878                         }
5879                         if (stat.isFile()) {
5880                             files.push(entry);
5881                         }
5882                         else if (stat.isDirectory()) {
5883                             directories.push(entry);
5884                         }
5885                     }
5886                     files.sort();
5887                     directories.sort();
5888                     return { files: files, directories: directories };
5889                 }
5890                 catch (e) {
5891                     return ts.emptyFileSystemEntries;
5892                 }
5893             }
5894             function readDirectory(path, extensions, excludes, includes, depth) {
5895                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
5896             }
5897             function fileSystemEntryExists(path, entryKind) {
5898                 try {
5899                     var stat = _fs.statSync(path);
5900                     switch (entryKind) {
5901                         case 0 /* File */: return stat.isFile();
5902                         case 1 /* Directory */: return stat.isDirectory();
5903                         default: return false;
5904                     }
5905                 }
5906                 catch (e) {
5907                     return false;
5908                 }
5909             }
5910             function fileExists(path) {
5911                 return fileSystemEntryExists(path, 0 /* File */);
5912             }
5913             function directoryExists(path) {
5914                 return fileSystemEntryExists(path, 1 /* Directory */);
5915             }
5916             function getDirectories(path) {
5917                 return getAccessibleFileSystemEntries(path).directories.slice();
5918             }
5919             function realpath(path) {
5920                 try {
5921                     return _fs.realpathSync(path);
5922                 }
5923                 catch (_a) {
5924                     return path;
5925                 }
5926             }
5927             function getModifiedTime(path) {
5928                 try {
5929                     return _fs.statSync(path).mtime;
5930                 }
5931                 catch (e) {
5932                     return undefined;
5933                 }
5934             }
5935             function setModifiedTime(path, time) {
5936                 try {
5937                     _fs.utimesSync(path, time, time);
5938                 }
5939                 catch (e) {
5940                     return;
5941                 }
5942             }
5943             function deleteFile(path) {
5944                 try {
5945                     return _fs.unlinkSync(path);
5946                 }
5947                 catch (e) {
5948                     return;
5949                 }
5950             }
5951             function createSHA256Hash(data) {
5952                 var hash = _crypto.createHash("sha256");
5953                 hash.update(data);
5954                 return hash.digest("hex");
5955             }
5956         }
5957         var sys;
5958         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
5959             // process and process.nextTick checks if current environment is node-like
5960             // process.browser check excludes webpack and browserify
5961             sys = getNodeSystem();
5962         }
5963         if (sys) {
5964             // patch writefile to create folder before writing the file
5965             patchWriteFileEnsuringDirectory(sys);
5966         }
5967         return sys;
5968     })();
5969     if (ts.sys && ts.sys.getEnvironmentVariable) {
5970         setCustomPollingValues(ts.sys);
5971         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
5972             ? 1 /* Normal */
5973             : 0 /* None */);
5974     }
5975     if (ts.sys && ts.sys.debugMode) {
5976         ts.Debug.isDebugging = true;
5977     }
5978 })(ts || (ts = {}));
5979 /* @internal */
5980 var ts;
5981 (function (ts) {
5982     /**
5983      * Internally, we represent paths as strings with '/' as the directory separator.
5984      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
5985      * we expect the host to correctly handle paths in our specified format.
5986      */
5987     ts.directorySeparator = "/";
5988     var altDirectorySeparator = "\\";
5989     var urlSchemeSeparator = "://";
5990     var backslashRegExp = /\\/g;
5991     //// Path Tests
5992     /**
5993      * Determines whether a charCode corresponds to `/` or `\`.
5994      */
5995     function isAnyDirectorySeparator(charCode) {
5996         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
5997     }
5998     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
5999     /**
6000      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
6001      */
6002     function isUrl(path) {
6003         return getEncodedRootLength(path) < 0;
6004     }
6005     ts.isUrl = isUrl;
6006     /**
6007      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
6008      * like `c:`, `c:\` or `c:/`).
6009      */
6010     function isRootedDiskPath(path) {
6011         return getEncodedRootLength(path) > 0;
6012     }
6013     ts.isRootedDiskPath = isRootedDiskPath;
6014     /**
6015      * Determines whether a path consists only of a path root.
6016      */
6017     function isDiskPathRoot(path) {
6018         var rootLength = getEncodedRootLength(path);
6019         return rootLength > 0 && rootLength === path.length;
6020     }
6021     ts.isDiskPathRoot = isDiskPathRoot;
6022     /**
6023      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
6024      *
6025      * ```ts
6026      * // POSIX
6027      * pathIsAbsolute("/path/to/file.ext") === true
6028      * // DOS
6029      * pathIsAbsolute("c:/path/to/file.ext") === true
6030      * // URL
6031      * pathIsAbsolute("file:///path/to/file.ext") === true
6032      * // Non-absolute
6033      * pathIsAbsolute("path/to/file.ext") === false
6034      * pathIsAbsolute("./path/to/file.ext") === false
6035      * ```
6036      */
6037     function pathIsAbsolute(path) {
6038         return getEncodedRootLength(path) !== 0;
6039     }
6040     ts.pathIsAbsolute = pathIsAbsolute;
6041     /**
6042      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
6043      */
6044     function pathIsRelative(path) {
6045         return /^\.\.?($|[\\/])/.test(path);
6046     }
6047     ts.pathIsRelative = pathIsRelative;
6048     function hasExtension(fileName) {
6049         return ts.stringContains(getBaseFileName(fileName), ".");
6050     }
6051     ts.hasExtension = hasExtension;
6052     function fileExtensionIs(path, extension) {
6053         return path.length > extension.length && ts.endsWith(path, extension);
6054     }
6055     ts.fileExtensionIs = fileExtensionIs;
6056     function fileExtensionIsOneOf(path, extensions) {
6057         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
6058             var extension = extensions_1[_i];
6059             if (fileExtensionIs(path, extension)) {
6060                 return true;
6061             }
6062         }
6063         return false;
6064     }
6065     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
6066     /**
6067      * Determines whether a path has a trailing separator (`/` or `\\`).
6068      */
6069     function hasTrailingDirectorySeparator(path) {
6070         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
6071     }
6072     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
6073     //// Path Parsing
6074     function isVolumeCharacter(charCode) {
6075         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
6076             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
6077     }
6078     function getFileUrlVolumeSeparatorEnd(url, start) {
6079         var ch0 = url.charCodeAt(start);
6080         if (ch0 === 58 /* colon */)
6081             return start + 1;
6082         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
6083             var ch2 = url.charCodeAt(start + 2);
6084             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
6085                 return start + 3;
6086         }
6087         return -1;
6088     }
6089     /**
6090      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6091      * If the root is part of a URL, the twos-complement of the root length is returned.
6092      */
6093     function getEncodedRootLength(path) {
6094         if (!path)
6095             return 0;
6096         var ch0 = path.charCodeAt(0);
6097         // POSIX or UNC
6098         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
6099             if (path.charCodeAt(1) !== ch0)
6100                 return 1; // POSIX: "/" (or non-normalized "\")
6101             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
6102             if (p1 < 0)
6103                 return path.length; // UNC: "//server" or "\\server"
6104             return p1 + 1; // UNC: "//server/" or "\\server\"
6105         }
6106         // DOS
6107         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
6108             var ch2 = path.charCodeAt(2);
6109             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
6110                 return 3; // DOS: "c:/" or "c:\"
6111             if (path.length === 2)
6112                 return 2; // DOS: "c:" (but not "c:d")
6113         }
6114         // URL
6115         var schemeEnd = path.indexOf(urlSchemeSeparator);
6116         if (schemeEnd !== -1) {
6117             var authorityStart = schemeEnd + urlSchemeSeparator.length;
6118             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
6119             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
6120                 // For local "file" URLs, include the leading DOS volume (if present).
6121                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
6122                 // special case interpreted as "the machine from which the URL is being interpreted".
6123                 var scheme = path.slice(0, schemeEnd);
6124                 var authority = path.slice(authorityStart, authorityEnd);
6125                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
6126                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
6127                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
6128                     if (volumeSeparatorEnd !== -1) {
6129                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
6130                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
6131                             return ~(volumeSeparatorEnd + 1);
6132                         }
6133                         if (volumeSeparatorEnd === path.length) {
6134                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
6135                             // but not "file:///c:d" or "file:///c%3ad"
6136                             return ~volumeSeparatorEnd;
6137                         }
6138                     }
6139                 }
6140                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
6141             }
6142             return ~path.length; // URL: "file://server", "http://server"
6143         }
6144         // relative
6145         return 0;
6146     }
6147     /**
6148      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6149      *
6150      * For example:
6151      * ```ts
6152      * getRootLength("a") === 0                   // ""
6153      * getRootLength("/") === 1                   // "/"
6154      * getRootLength("c:") === 2                  // "c:"
6155      * getRootLength("c:d") === 0                 // ""
6156      * getRootLength("c:/") === 3                 // "c:/"
6157      * getRootLength("c:\\") === 3                // "c:\\"
6158      * getRootLength("//server") === 7            // "//server"
6159      * getRootLength("//server/share") === 8      // "//server/"
6160      * getRootLength("\\\\server") === 7          // "\\\\server"
6161      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
6162      * getRootLength("file:///path") === 8        // "file:///"
6163      * getRootLength("file:///c:") === 10         // "file:///c:"
6164      * getRootLength("file:///c:d") === 8         // "file:///"
6165      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
6166      * getRootLength("file://server") === 13      // "file://server"
6167      * getRootLength("file://server/path") === 14 // "file://server/"
6168      * getRootLength("http://server") === 13      // "http://server"
6169      * getRootLength("http://server/path") === 14 // "http://server/"
6170      * ```
6171      */
6172     function getRootLength(path) {
6173         var rootLength = getEncodedRootLength(path);
6174         return rootLength < 0 ? ~rootLength : rootLength;
6175     }
6176     ts.getRootLength = getRootLength;
6177     function getDirectoryPath(path) {
6178         path = normalizeSlashes(path);
6179         // If the path provided is itself the root, then return it.
6180         var rootLength = getRootLength(path);
6181         if (rootLength === path.length)
6182             return path;
6183         // return the leading portion of the path up to the last (non-terminal) directory separator
6184         // but not including any trailing directory separator.
6185         path = removeTrailingDirectorySeparator(path);
6186         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
6187     }
6188     ts.getDirectoryPath = getDirectoryPath;
6189     function getBaseFileName(path, extensions, ignoreCase) {
6190         path = normalizeSlashes(path);
6191         // if the path provided is itself the root, then it has not file name.
6192         var rootLength = getRootLength(path);
6193         if (rootLength === path.length)
6194             return "";
6195         // return the trailing portion of the path starting after the last (non-terminal) directory
6196         // separator but not including any trailing directory separator.
6197         path = removeTrailingDirectorySeparator(path);
6198         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
6199         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
6200         return extension ? name.slice(0, name.length - extension.length) : name;
6201     }
6202     ts.getBaseFileName = getBaseFileName;
6203     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
6204         if (!ts.startsWith(extension, "."))
6205             extension = "." + extension;
6206         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
6207             var pathExtension = path.slice(path.length - extension.length);
6208             if (stringEqualityComparer(pathExtension, extension)) {
6209                 return pathExtension;
6210             }
6211         }
6212     }
6213     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
6214         if (typeof extensions === "string") {
6215             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
6216         }
6217         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
6218             var extension = extensions_2[_i];
6219             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
6220             if (result)
6221                 return result;
6222         }
6223         return "";
6224     }
6225     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
6226         // Retrieves any string from the final "." onwards from a base file name.
6227         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
6228         if (extensions) {
6229             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
6230         }
6231         var baseFileName = getBaseFileName(path);
6232         var extensionIndex = baseFileName.lastIndexOf(".");
6233         if (extensionIndex >= 0) {
6234             return baseFileName.substring(extensionIndex);
6235         }
6236         return "";
6237     }
6238     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
6239     function pathComponents(path, rootLength) {
6240         var root = path.substring(0, rootLength);
6241         var rest = path.substring(rootLength).split(ts.directorySeparator);
6242         if (rest.length && !ts.lastOrUndefined(rest))
6243             rest.pop();
6244         return __spreadArrays([root], rest);
6245     }
6246     /**
6247      * Parse a path into an array containing a root component (at index 0) and zero or more path
6248      * components (at indices > 0). The result is not normalized.
6249      * If the path is relative, the root component is `""`.
6250      * If the path is absolute, the root component includes the first path separator (`/`).
6251      *
6252      * ```ts
6253      * // POSIX
6254      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
6255      * getPathComponents("/path/to/") === ["/", "path", "to"]
6256      * getPathComponents("/") === ["/"]
6257      * // DOS
6258      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
6259      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
6260      * getPathComponents("c:/") === ["c:/"]
6261      * getPathComponents("c:") === ["c:"]
6262      * // URL
6263      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
6264      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
6265      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
6266      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
6267      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
6268      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
6269      * getPathComponents("file://server/") === ["file://server/"]
6270      * getPathComponents("file://server") === ["file://server"]
6271      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
6272      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
6273      * getPathComponents("file:///") === ["file:///"]
6274      * getPathComponents("file://") === ["file://"]
6275      */
6276     function getPathComponents(path, currentDirectory) {
6277         if (currentDirectory === void 0) { currentDirectory = ""; }
6278         path = combinePaths(currentDirectory, path);
6279         return pathComponents(path, getRootLength(path));
6280     }
6281     ts.getPathComponents = getPathComponents;
6282     //// Path Formatting
6283     /**
6284      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
6285      * segments (at indices > 0).
6286      *
6287      * ```ts
6288      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
6289      * ```
6290      */
6291     function getPathFromPathComponents(pathComponents) {
6292         if (pathComponents.length === 0)
6293             return "";
6294         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
6295         return root + pathComponents.slice(1).join(ts.directorySeparator);
6296     }
6297     ts.getPathFromPathComponents = getPathFromPathComponents;
6298     //// Path Normalization
6299     /**
6300      * Normalize path separators, converting `\` into `/`.
6301      */
6302     function normalizeSlashes(path) {
6303         return path.replace(backslashRegExp, ts.directorySeparator);
6304     }
6305     ts.normalizeSlashes = normalizeSlashes;
6306     /**
6307      * Reduce an array of path components to a more simplified path by navigating any
6308      * `"."` or `".."` entries in the path.
6309      */
6310     function reducePathComponents(components) {
6311         if (!ts.some(components))
6312             return [];
6313         var reduced = [components[0]];
6314         for (var i = 1; i < components.length; i++) {
6315             var component = components[i];
6316             if (!component)
6317                 continue;
6318             if (component === ".")
6319                 continue;
6320             if (component === "..") {
6321                 if (reduced.length > 1) {
6322                     if (reduced[reduced.length - 1] !== "..") {
6323                         reduced.pop();
6324                         continue;
6325                     }
6326                 }
6327                 else if (reduced[0])
6328                     continue;
6329             }
6330             reduced.push(component);
6331         }
6332         return reduced;
6333     }
6334     ts.reducePathComponents = reducePathComponents;
6335     /**
6336      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
6337      *
6338      * ```ts
6339      * // Non-rooted
6340      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
6341      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
6342      * // POSIX
6343      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
6344      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
6345      * // DOS
6346      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
6347      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
6348      * // URL
6349      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
6350      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
6351      * ```
6352      */
6353     function combinePaths(path) {
6354         var paths = [];
6355         for (var _i = 1; _i < arguments.length; _i++) {
6356             paths[_i - 1] = arguments[_i];
6357         }
6358         if (path)
6359             path = normalizeSlashes(path);
6360         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
6361             var relativePath = paths_1[_a];
6362             if (!relativePath)
6363                 continue;
6364             relativePath = normalizeSlashes(relativePath);
6365             if (!path || getRootLength(relativePath) !== 0) {
6366                 path = relativePath;
6367             }
6368             else {
6369                 path = ensureTrailingDirectorySeparator(path) + relativePath;
6370             }
6371         }
6372         return path;
6373     }
6374     ts.combinePaths = combinePaths;
6375     /**
6376      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
6377      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
6378      *
6379      * ```ts
6380      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
6381      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
6382      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
6383      * ```
6384      */
6385     function resolvePath(path) {
6386         var paths = [];
6387         for (var _i = 1; _i < arguments.length; _i++) {
6388             paths[_i - 1] = arguments[_i];
6389         }
6390         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
6391     }
6392     ts.resolvePath = resolvePath;
6393     /**
6394      * Parse a path into an array containing a root component (at index 0) and zero or more path
6395      * components (at indices > 0). The result is normalized.
6396      * If the path is relative, the root component is `""`.
6397      * If the path is absolute, the root component includes the first path separator (`/`).
6398      *
6399      * ```ts
6400      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
6401      * ```
6402      */
6403     function getNormalizedPathComponents(path, currentDirectory) {
6404         return reducePathComponents(getPathComponents(path, currentDirectory));
6405     }
6406     ts.getNormalizedPathComponents = getNormalizedPathComponents;
6407     function getNormalizedAbsolutePath(fileName, currentDirectory) {
6408         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
6409     }
6410     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
6411     function normalizePath(path) {
6412         path = normalizeSlashes(path);
6413         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
6414         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
6415     }
6416     ts.normalizePath = normalizePath;
6417     function getPathWithoutRoot(pathComponents) {
6418         if (pathComponents.length === 0)
6419             return "";
6420         return pathComponents.slice(1).join(ts.directorySeparator);
6421     }
6422     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
6423         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
6424     }
6425     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
6426     function toPath(fileName, basePath, getCanonicalFileName) {
6427         var nonCanonicalizedPath = isRootedDiskPath(fileName)
6428             ? normalizePath(fileName)
6429             : getNormalizedAbsolutePath(fileName, basePath);
6430         return getCanonicalFileName(nonCanonicalizedPath);
6431     }
6432     ts.toPath = toPath;
6433     function normalizePathAndParts(path) {
6434         path = normalizeSlashes(path);
6435         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
6436         if (parts.length) {
6437             var joinedParts = root + parts.join(ts.directorySeparator);
6438             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
6439         }
6440         else {
6441             return { path: root, parts: parts };
6442         }
6443     }
6444     ts.normalizePathAndParts = normalizePathAndParts;
6445     function removeTrailingDirectorySeparator(path) {
6446         if (hasTrailingDirectorySeparator(path)) {
6447             return path.substr(0, path.length - 1);
6448         }
6449         return path;
6450     }
6451     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
6452     function ensureTrailingDirectorySeparator(path) {
6453         if (!hasTrailingDirectorySeparator(path)) {
6454             return path + ts.directorySeparator;
6455         }
6456         return path;
6457     }
6458     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
6459     /**
6460      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
6461      * with `./` or `../`) so as not to be confused with an unprefixed module name.
6462      *
6463      * ```ts
6464      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
6465      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
6466      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
6467      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
6468      * ```
6469      */
6470     function ensurePathIsNonModuleName(path) {
6471         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
6472     }
6473     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
6474     function changeAnyExtension(path, ext, extensions, ignoreCase) {
6475         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
6476         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
6477     }
6478     ts.changeAnyExtension = changeAnyExtension;
6479     //// Path Comparisons
6480     // check path for these segments: '', '.'. '..'
6481     var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
6482     function comparePathsWorker(a, b, componentComparer) {
6483         if (a === b)
6484             return 0 /* EqualTo */;
6485         if (a === undefined)
6486             return -1 /* LessThan */;
6487         if (b === undefined)
6488             return 1 /* GreaterThan */;
6489         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
6490         //       need to perform path reduction.
6491         var aRoot = a.substring(0, getRootLength(a));
6492         var bRoot = b.substring(0, getRootLength(b));
6493         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
6494         if (result !== 0 /* EqualTo */) {
6495             return result;
6496         }
6497         // NOTE: Performance optimization - shortcut if there are no relative path segments in
6498         //       the non-root portion of the path
6499         var aRest = a.substring(aRoot.length);
6500         var bRest = b.substring(bRoot.length);
6501         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6502             return componentComparer(aRest, bRest);
6503         }
6504         // The path contains a relative path segment. Normalize the paths and perform a slower component
6505         // by component comparison.
6506         var aComponents = reducePathComponents(getPathComponents(a));
6507         var bComponents = reducePathComponents(getPathComponents(b));
6508         var sharedLength = Math.min(aComponents.length, bComponents.length);
6509         for (var i = 1; i < sharedLength; i++) {
6510             var result_1 = componentComparer(aComponents[i], bComponents[i]);
6511             if (result_1 !== 0 /* EqualTo */) {
6512                 return result_1;
6513             }
6514         }
6515         return ts.compareValues(aComponents.length, bComponents.length);
6516     }
6517     /**
6518      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6519      */
6520     function comparePathsCaseSensitive(a, b) {
6521         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6522     }
6523     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6524     /**
6525      * Performs a case-insensitive comparison of two paths.
6526      */
6527     function comparePathsCaseInsensitive(a, b) {
6528         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6529     }
6530     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6531     function comparePaths(a, b, currentDirectory, ignoreCase) {
6532         if (typeof currentDirectory === "string") {
6533             a = combinePaths(currentDirectory, a);
6534             b = combinePaths(currentDirectory, b);
6535         }
6536         else if (typeof currentDirectory === "boolean") {
6537             ignoreCase = currentDirectory;
6538         }
6539         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6540     }
6541     ts.comparePaths = comparePaths;
6542     function containsPath(parent, child, currentDirectory, ignoreCase) {
6543         if (typeof currentDirectory === "string") {
6544             parent = combinePaths(currentDirectory, parent);
6545             child = combinePaths(currentDirectory, child);
6546         }
6547         else if (typeof currentDirectory === "boolean") {
6548             ignoreCase = currentDirectory;
6549         }
6550         if (parent === undefined || child === undefined)
6551             return false;
6552         if (parent === child)
6553             return true;
6554         var parentComponents = reducePathComponents(getPathComponents(parent));
6555         var childComponents = reducePathComponents(getPathComponents(child));
6556         if (childComponents.length < parentComponents.length) {
6557             return false;
6558         }
6559         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6560         for (var i = 0; i < parentComponents.length; i++) {
6561             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6562             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6563                 return false;
6564             }
6565         }
6566         return true;
6567     }
6568     ts.containsPath = containsPath;
6569     /**
6570      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6571      * Comparison is case-sensitive between the canonical paths.
6572      *
6573      * @deprecated Use `containsPath` if possible.
6574      */
6575     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6576         var canonicalFileName = getCanonicalFileName(fileName);
6577         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6578         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6579     }
6580     ts.startsWithDirectory = startsWithDirectory;
6581     //// Relative Paths
6582     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6583         var fromComponents = reducePathComponents(getPathComponents(from));
6584         var toComponents = reducePathComponents(getPathComponents(to));
6585         var start;
6586         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6587             var fromComponent = getCanonicalFileName(fromComponents[start]);
6588             var toComponent = getCanonicalFileName(toComponents[start]);
6589             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6590             if (!comparer(fromComponent, toComponent))
6591                 break;
6592         }
6593         if (start === 0) {
6594             return toComponents;
6595         }
6596         var components = toComponents.slice(start);
6597         var relative = [];
6598         for (; start < fromComponents.length; start++) {
6599             relative.push("..");
6600         }
6601         return __spreadArrays([""], relative, components);
6602     }
6603     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6604     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6605         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6606         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6607         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6608         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6609         return getPathFromPathComponents(pathComponents);
6610     }
6611     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6612     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6613         return !isRootedDiskPath(absoluteOrRelativePath)
6614             ? absoluteOrRelativePath
6615             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6616     }
6617     ts.convertToRelativePath = convertToRelativePath;
6618     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6619         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6620     }
6621     ts.getRelativePathFromFile = getRelativePathFromFile;
6622     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6623         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6624         var firstComponent = pathComponents[0];
6625         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6626             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6627             pathComponents[0] = prefix + firstComponent;
6628         }
6629         return getPathFromPathComponents(pathComponents);
6630     }
6631     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6632     function forEachAncestorDirectory(directory, callback) {
6633         while (true) {
6634             var result = callback(directory);
6635             if (result !== undefined) {
6636                 return result;
6637             }
6638             var parentPath = getDirectoryPath(directory);
6639             if (parentPath === directory) {
6640                 return undefined;
6641             }
6642             directory = parentPath;
6643         }
6644     }
6645     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6646     function isNodeModulesDirectory(dirPath) {
6647         return ts.endsWith(dirPath, "/node_modules");
6648     }
6649     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6650 })(ts || (ts = {}));
6651 // <auto-generated />
6652 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
6653 /* @internal */
6654 var ts;
6655 (function (ts) {
6656     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) {
6657         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid };
6658     }
6659     ts.Diagnostics = {
6660         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
6661         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
6662         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
6663         A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."),
6664         The_parser_expected_to_find_a_to_match_the_token_here: diag(1007, ts.DiagnosticCategory.Error, "The_parser_expected_to_find_a_to_match_the_token_here_1007", "The parser expected to find a '}' to match the '{' token here."),
6665         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
6666         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
6667         An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."),
6668         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
6669         A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."),
6670         A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."),
6671         Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."),
6672         A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."),
6673         An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."),
6674         An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."),
6675         An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."),
6676         An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."),
6677         An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."),
6678         An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."),
6679         An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."),
6680         readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."),
6681         An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."),
6682         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
6683         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
6684         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
6685         _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."),
6686         super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."),
6687         Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."),
6688         Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."),
6689         A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."),
6690         Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."),
6691         _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."),
6692         _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."),
6693         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
6694         _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."),
6695         _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."),
6696         A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."),
6697         Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier: diag(1046, ts.DiagnosticCategory.Error, "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046", "Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier."),
6698         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
6699         A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."),
6700         A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."),
6701         A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."),
6702         A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."),
6703         A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."),
6704         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
6705         Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."),
6706         Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."),
6707         An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."),
6708         The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."),
6709         A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."),
6710         The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."),
6711         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
6712         Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."),
6713         An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."),
6714         The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise<T> type."),
6715         In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."),
6716         Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."),
6717         Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."),
6718         _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."),
6719         _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."),
6720         A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."),
6721         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
6722         Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."),
6723         _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."),
6724         _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."),
6725         Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."),
6726         Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."),
6727         Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."),
6728         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
6729         A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."),
6730         An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."),
6731         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
6732         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
6733         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
6734         Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."),
6735         with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."),
6736         delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."),
6737         A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."),
6738         A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."),
6739         A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."),
6740         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
6741         A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."),
6742         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
6743         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
6744         A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."),
6745         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
6746         A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."),
6747         A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."),
6748         An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."),
6749         An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."),
6750         An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."),
6751         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
6752         Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."),
6753         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
6754         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
6755         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
6756         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
6757         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
6758         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
6759         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
6760         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
6761         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
6762         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
6763         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
6764         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
6765         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
6766         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
6767         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
6768         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
6769         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
6770         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
6771         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
6772         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
6773         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
6774         Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."),
6775         Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."),
6776         File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."),
6777         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
6778         const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."),
6779         let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."),
6780         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
6781         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
6782         An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."),
6783         A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."),
6784         Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."),
6785         A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."),
6786         A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."),
6787         A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."),
6788         A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."),
6789         A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."),
6790         A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."),
6791         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
6792         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
6793         Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."),
6794         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
6795         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
6796         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
6797         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
6798         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
6799         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
6800         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
6801         A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."),
6802         An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."),
6803         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
6804         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
6805         A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."),
6806         A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."),
6807         Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."),
6808         The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."),
6809         The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."),
6810         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
6811         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
6812         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
6813         Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."),
6814         export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."),
6815         Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."),
6816         Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."),
6817         An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."),
6818         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
6819         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
6820         Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."),
6821         Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."),
6822         Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type: diag(1205, ts.DiagnosticCategory.Error, "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205", "Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'."),
6823         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
6824         Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
6825         All_files_must_be_modules_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "All_files_must_be_modules_when_the_isolatedModules_flag_is_provided_1208", "All files must be modules when the '--isolatedModules' flag is provided."),
6826         Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
6827         A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
6828         Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
6829         Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."),
6830         Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."),
6831         Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."),
6832         Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."),
6833         Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."),
6834         Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning."),
6835         Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."),
6836         Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."),
6837         An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."),
6838         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
6839         Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."),
6840         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
6841         Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."),
6842         Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."),
6843         A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."),
6844         A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."),
6845         A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."),
6846         An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."),
6847         An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."),
6848         An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."),
6849         An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."),
6850         A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."),
6851         The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."),
6852         The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."),
6853         Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."),
6854         Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."),
6855         Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."),
6856         Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."),
6857         abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."),
6858         _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."),
6859         Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."),
6860         Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."),
6861         An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."),
6862         A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."),
6863         A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."),
6864         A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."),
6865         Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."),
6866         Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."),
6867         Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."),
6868         _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."),
6869         A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."),
6870         A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."),
6871         A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."),
6872         A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."),
6873         Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation: diag(1258, ts.DiagnosticCategory.Error, "Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation_1258", "Definite assignment assertions can only be used along with a type annotation."),
6874         Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"),
6875         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
6876         Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."),
6877         with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."),
6878         await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."),
6879         can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."),
6880         The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."),
6881         Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."),
6882         Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."),
6883         Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."),
6884         A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."),
6885         An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."),
6886         A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."),
6887         Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
6888         Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
6889         Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
6890         Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'."),
6891         Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
6892         Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
6893         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
6894         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
6895         Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."),
6896         _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"),
6897         A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."),
6898         A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."),
6899         A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."),
6900         unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."),
6901         unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."),
6902         unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."),
6903         An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."),
6904         An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."),
6905         infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."),
6906         Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."),
6907         Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"),
6908         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
6909         The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'esnext' or 'system'."),
6910         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
6911         An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"),
6912         This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."),
6913         use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."),
6914         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
6915         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
6916         Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."),
6917         An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
6918         A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
6919         A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
6920         readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
6921         A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355", "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals."),
6922         Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"),
6923         An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."),
6924         Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."),
6925         Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."),
6926         Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"),
6927         _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."),
6928         _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."),
6929         A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."),
6930         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
6931         Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"),
6932         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
6933         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
6934         Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"),
6935         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
6936         Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."),
6937         This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371", "This import is never used as a value and must use 'import type' because the 'importsNotUsedAsValues' is set to 'error'."),
6938         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
6939         Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"),
6940         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: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'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."),
6941         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
6942         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
6943         Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1378, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."),
6944         An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type: diag(1379, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379", "An import alias cannot reference a declaration that was exported using 'export type'."),
6945         An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type: diag(1380, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380", "An import alias cannot reference a declaration that was imported using 'import type'."),
6946         Unexpected_token_Did_you_mean_or_rbrace: diag(1381, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_rbrace_1381", "Unexpected token. Did you mean `{'}'}` or `&rbrace;`?"),
6947         Unexpected_token_Did_you_mean_or_gt: diag(1382, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_gt_1382", "Unexpected token. Did you mean `{'>'}` or `&gt;`?"),
6948         Only_named_exports_may_use_export_type: diag(1383, ts.DiagnosticCategory.Error, "Only_named_exports_may_use_export_type_1383", "Only named exports may use 'export type'."),
6949         A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list: diag(1384, ts.DiagnosticCategory.Error, "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384", "A 'new' expression with type arguments must always be followed by a parenthesized argument list."),
6950         The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."),
6951         The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."),
6952         Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
6953         Construct_signature_return_types_0_and_1_are_incompatible: diag(2203, ts.DiagnosticCategory.Error, "Construct_signature_return_types_0_and_1_are_incompatible_2203", "Construct signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
6954         Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2204, ts.DiagnosticCategory.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*/ undefined, /*elidedInCompatabilityPyramid*/ true),
6955         Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.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*/ undefined, /*elidedInCompatabilityPyramid*/ true),
6956         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
6957         Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."),
6958         Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."),
6959         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
6960         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
6961         Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."),
6962         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
6963         Cannot_find_module_0_or_its_corresponding_type_declarations: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_or_its_corresponding_type_declarations_2307", "Cannot find module '{0}' or its corresponding type declarations."),
6964         Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."),
6965         An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
6966         Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
6967         A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
6968         An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
6969         Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
6970         Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
6971         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
6972         Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."),
6973         Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."),
6974         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
6975         Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."),
6976         Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."),
6977         Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."),
6978         Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."),
6979         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
6980         Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."),
6981         Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."),
6982         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
6983         Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."),
6984         Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."),
6985         Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."),
6986         Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
6987         this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."),
6988         this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."),
6989         this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."),
6990         this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."),
6991         super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."),
6992         super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."),
6993         Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."),
6994         super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."),
6995         Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."),
6996         Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."),
6997         Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."),
6998         An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."),
6999         This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343", "This syntax requires an imported helper named '{1}' which does not exist in '{0}'. Consider upgrading your version of '{0}'."),
7000         Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."),
7001         Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."),
7002         Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."),
7003         Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."),
7004         Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"),
7005         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
7006         Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."),
7007         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
7008         Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."),
7009         Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."),
7010         This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."),
7011         A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."),
7012         An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."),
7013         The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."),
7014         The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."),
7015         The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."),
7016         The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."),
7017         The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."),
7018         The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),
7019         The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),
7020         The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."),
7021         Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."),
7022         Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."),
7023         This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."),
7024         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7025         A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."),
7026         A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."),
7027         A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."),
7028         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7029         Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."),
7030         Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7031         Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7032         A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."),
7033         Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."),
7034         A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."),
7035         Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."),
7036         get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."),
7037         A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."),
7038         Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."),
7039         Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."),
7040         Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."),
7041         Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."),
7042         Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."),
7043         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
7044         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
7045         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
7046         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
7047         Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
7048         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
7049         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
7050         This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
7051         Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
7052         Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
7053         Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
7054         constructor_cannot_be_used_as_a_parameter_property_name: diag(2398, ts.DiagnosticCategory.Error, "constructor_cannot_be_used_as_a_parameter_property_name_2398", "'constructor' cannot be used as a parameter property name."),
7055         Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."),
7056         Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."),
7057         Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."),
7058         Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."),
7059         Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type.  Variable '{0}' must be of type '{1}', but here has type '{2}'."),
7060         The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."),
7061         The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."),
7062         The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."),
7063         The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."),
7064         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
7065         Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."),
7066         The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."),
7067         Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."),
7068         Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."),
7069         Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."),
7070         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
7071         Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."),
7072         Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."),
7073         Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
7074         Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
7075         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
7076         A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
7077         Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
7078         Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
7079         Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."),
7080         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
7081         All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."),
7082         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
7083         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
7084         In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."),
7085         A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."),
7086         A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."),
7087         Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."),
7088         Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."),
7089         Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."),
7090         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
7091         Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."),
7092         Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."),
7093         Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."),
7094         Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."),
7095         Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."),
7096         Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."),
7097         Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."),
7098         Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."),
7099         The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."),
7100         Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."),
7101         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
7102         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
7103         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
7104         An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."),
7105         The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."),
7106         Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."),
7107         Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."),
7108         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
7109         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
7110         An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."),
7111         Module_0_declares_1_locally_but_it_is_not_exported: diag(2459, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_not_exported_2459", "Module '{0}' declares '{1}' locally, but it is not exported."),
7112         Module_0_declares_1_locally_but_it_is_exported_as_2: diag(2460, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_exported_as_2_2460", "Module '{0}' declares '{1}' locally, but it is exported as '{2}'."),
7113         Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."),
7114         A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."),
7115         A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."),
7116         A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."),
7117         this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."),
7118         super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."),
7119         A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."),
7120         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
7121         The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."),
7122         Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."),
7123         A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."),
7124         Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."),
7125         Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."),
7126         const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."),
7127         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: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'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."),
7128         A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."),
7129         const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."),
7130         const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."),
7131         Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."),
7132         let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."),
7133         Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."),
7134         The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."),
7135         Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."),
7136         The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."),
7137         Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."),
7138         An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."),
7139         The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the '{0}()' method of an iterator must have a 'value' property."),
7140         The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."),
7141         Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."),
7142         Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."),
7143         Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."),
7144         Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."),
7145         The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."),
7146         This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."),
7147         Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."),
7148         An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."),
7149         A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."),
7150         A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."),
7151         _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."),
7152         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
7153         Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."),
7154         A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."),
7155         _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
7156         Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
7157         No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
7158         Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
7159         Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
7160         Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
7161         Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
7162         Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."),
7163         Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."),
7164         Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."),
7165         All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."),
7166         Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."),
7167         A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."),
7168         An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."),
7169         Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."),
7170         Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."),
7171         The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."),
7172         yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."),
7173         await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."),
7174         Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."),
7175         A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."),
7176         The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."),
7177         A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."),
7178         Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."),
7179         Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."),
7180         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
7181         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
7182         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
7183         A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."),
7184         Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."),
7185         Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."),
7186         Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
7187         Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
7188         Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
7189         Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
7190         The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
7191         Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
7192         Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
7193         Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."),
7194         A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."),
7195         The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."),
7196         Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
7197         Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
7198         Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"),
7199         Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"),
7200         Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."),
7201         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
7202         Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."),
7203         Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."),
7204         Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."),
7205         Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."),
7206         Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."),
7207         Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"),
7208         Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"),
7209         Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."),
7210         The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."),
7211         Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."),
7212         Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."),
7213         A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."),
7214         Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."),
7215         Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."),
7216         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
7217         Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
7218         Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."),
7219         A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."),
7220         No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."),
7221         Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"),
7222         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
7223         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
7224         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
7225         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
7226         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
7227         Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
7228         Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
7229         _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
7230         Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
7231         JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
7232         Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
7233         Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
7234         Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
7235         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
7236         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
7237         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
7238         This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."),
7239         _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."),
7240         _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."),
7241         _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."),
7242         _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."),
7243         JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
7244         The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
7245         JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
7246         Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."),
7247         JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."),
7248         JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."),
7249         Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."),
7250         JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."),
7251         The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."),
7252         JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."),
7253         _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."),
7254         _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."),
7255         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: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "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."),
7256         Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"),
7257         Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"),
7258         Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."),
7259         _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."),
7260         _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."),
7261         Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."),
7262         A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."),
7263         Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."),
7264         Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."),
7265         Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."),
7266         Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."),
7267         JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."),
7268         Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."),
7269         super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."),
7270         super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."),
7271         Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."),
7272         Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"),
7273         Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"),
7274         Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."),
7275         Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."),
7276         Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."),
7277         Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."),
7278         export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."),
7279         Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."),
7280         Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."),
7281         Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."),
7282         Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."),
7283         Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."),
7284         Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."),
7285         Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."),
7286         Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."),
7287         A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."),
7288         Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."),
7289         A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."),
7290         A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."),
7291         A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."),
7292         get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."),
7293         this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."),
7294         The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."),
7295         The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."),
7296         _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."),
7297         All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."),
7298         Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."),
7299         Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"),
7300         An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."),
7301         _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.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."),
7302         _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.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."),
7303         Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."),
7304         Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.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),
7305         The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.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?"),
7306         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, ts.DiagnosticCategory.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."),
7307         Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."),
7308         Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."),
7309         Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."),
7310         The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."),
7311         _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."),
7312         The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."),
7313         The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."),
7314         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: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor.  Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),
7315         Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."),
7316         Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."),
7317         Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."),
7318         Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."),
7319         _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."),
7320         A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),
7321         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: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor.  Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),
7322         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: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "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}\"]'?"),
7323         The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."),
7324         Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."),
7325         Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."),
7326         Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type.  Property '{0}' must be of type '{1}', but here has type '{2}'."),
7327         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
7328         Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."),
7329         Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"),
7330         Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
7331         Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
7332         Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
7333         Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
7334         Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."),
7335         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
7336         Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"),
7337         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
7338         Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."),
7339         An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."),
7340         Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."),
7341         Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"),
7342         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
7343         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
7344         Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"),
7345         Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."),
7346         BigInt_literals_are_not_available_when_targeting_lower_than_ES2020: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737", "BigInt literals are not available when targeting lower than ES2020."),
7347         An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."),
7348         Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
7349         Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
7350         Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
7351         The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
7352         No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."),
7353         Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."),
7354         This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
7355         This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
7356         _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
7357         Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
7358         _0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749", "'{0}' refers to a value, but is being used as a type here. Did you mean 'typeof {0}'?"),
7359         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
7360         Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
7361         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
7362         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
7363         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
7364         No_constituent_of_type_0_is_callable: diag(2755, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_callable_2755", "No constituent of type '{0}' is callable."),
7365         Not_all_constituents_of_type_0_are_callable: diag(2756, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_callable_2756", "Not all constituents of type '{0}' are callable."),
7366         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
7367         Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2758, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758", "Each member of the union type '{0}' has signatures, but none of those signatures are compatible with each other."),
7368         No_constituent_of_type_0_is_constructable: diag(2759, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_constructable_2759", "No constituent of type '{0}' is constructable."),
7369         Not_all_constituents_of_type_0_are_constructable: diag(2760, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_constructable_2760", "Not all constituents of type '{0}' are constructable."),
7370         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
7371         Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2762, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762", "Each member of the union type '{0}' has construct signatures, but none of those signatures are compatible with each other."),
7372         Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0: diag(2763, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but for-of will always send '{0}'."),
7373         Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0: diag(2764, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array spread will always send '{0}'."),
7374         Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0: diag(2765, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array destructuring will always send '{0}'."),
7375         Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0: diag(2766, ts.DiagnosticCategory.Error, "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766", "Cannot delegate iteration to value because the 'next' method of its iterator expects type '{1}', but the containing generator will always send '{0}'."),
7376         The_0_property_of_an_iterator_must_be_a_method: diag(2767, ts.DiagnosticCategory.Error, "The_0_property_of_an_iterator_must_be_a_method_2767", "The '{0}' property of an iterator must be a method."),
7377         The_0_property_of_an_async_iterator_must_be_a_method: diag(2768, ts.DiagnosticCategory.Error, "The_0_property_of_an_async_iterator_must_be_a_method_2768", "The '{0}' property of an async iterator must be a method."),
7378         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
7379         The_last_overload_gave_the_following_error: diag(2770, ts.DiagnosticCategory.Error, "The_last_overload_gave_the_following_error_2770", "The last overload gave the following error."),
7380         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
7381         Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."),
7382         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
7383         This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"),
7384         Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."),
7385         Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."),
7386         The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."),
7387         The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access: diag(2778, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778", "The target of an object rest assignment may not be an optional property access."),
7388         The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access: diag(2779, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779", "The left-hand side of an assignment expression may not be an optional property access."),
7389         The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access: diag(2780, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780", "The left-hand side of a 'for...in' statement may not be an optional property access."),
7390         The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access: diag(2781, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781", "The left-hand side of a 'for...of' statement may not be an optional property access."),
7391         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
7392         _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."),
7393         get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."),
7394         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
7395         _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."),
7396         Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."),
7397         Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."),
7398         Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."),
7399         Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
7400         Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
7401         Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
7402         Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
7403         Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
7404         Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
7405         Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."),
7406         Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."),
7407         Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."),
7408         Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."),
7409         extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."),
7410         extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."),
7411         Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."),
7412         Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."),
7413         Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."),
7414         Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
7415         Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
7416         Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."),
7417         Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
7418         Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
7419         Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."),
7420         Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
7421         Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."),
7422         Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
7423         Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."),
7424         Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
7425         Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."),
7426         Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
7427         Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
7428         Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."),
7429         Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
7430         Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
7431         Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."),
7432         Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."),
7433         Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."),
7434         Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."),
7435         Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."),
7436         Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."),
7437         Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."),
7438         Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
7439         Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."),
7440         Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."),
7441         Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
7442         Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."),
7443         Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."),
7444         Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."),
7445         Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."),
7446         Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."),
7447         Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."),
7448         Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."),
7449         Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."),
7450         Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."),
7451         Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."),
7452         Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."),
7453         Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
7454         Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."),
7455         Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
7456         Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
7457         Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."),
7458         Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
7459         Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
7460         Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."),
7461         Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."),
7462         Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."),
7463         Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."),
7464         Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."),
7465         Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."),
7466         Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."),
7467         Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."),
7468         Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."),
7469         Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."),
7470         Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."),
7471         Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."),
7472         Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."),
7473         Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
7474         Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
7475         Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
7476         Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."),
7477         Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
7478         Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
7479         Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
7480         Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
7481         Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
7482         Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
7483         The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1: diag(4104, ts.DiagnosticCategory.Error, "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104", "The type '{0}' is 'readonly' and cannot be assigned to the mutable type '{1}'."),
7484         Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter: diag(4105, ts.DiagnosticCategory.Error, "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105", "Private or protected member '{0}' cannot be accessed on a type parameter."),
7485         Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."),
7486         Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."),
7487         Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."),
7488         Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."),
7489         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
7490         The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
7491         Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
7492         File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
7493         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
7494         Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."),
7495         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
7496         Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."),
7497         Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"),
7498         Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."),
7499         Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."),
7500         Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."),
7501         Option_0_cannot_be_specified_when_option_target_is_ES3: diag(5048, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_target_is_ES3_5048", "Option '{0}' cannot be specified when option 'target' is 'ES3'."),
7502         Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."),
7503         Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."),
7504         Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."),
7505         A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."),
7506         Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."),
7507         Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."),
7508         Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."),
7509         The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."),
7510         Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."),
7511         Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."),
7512         Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."),
7513         Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' can have at most one '*' character."),
7514         Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."),
7515         Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."),
7516         File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."),
7517         Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."),
7518         Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
7519         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: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
7520         Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
7521         Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
7522         Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."),
7523         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
7524         Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."),
7525         Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."),
7526         _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."),
7527         _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."),
7528         Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"),
7529         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
7530         Unknown_watch_option_0_Did_you_mean_1: diag(5079, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_Did_you_mean_1_5079", "Unknown watch option '{0}'. Did you mean '{1}'?"),
7531         Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."),
7532         Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."),
7533         _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."),
7534         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
7535         The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."),
7536         Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
7537         Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
7538         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
7539         Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."),
7540         Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."),
7541         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
7542         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
7543         Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."),
7544         Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."),
7545         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
7546         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
7547         Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."),
7548         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
7549         Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
7550         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
7551         Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."),
7552         Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."),
7553         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
7554         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
7555         Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."),
7556         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
7557         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
7558         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
7559         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
7560         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
7561         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
7562         Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."),
7563         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
7564         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
7565         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
7566         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
7567         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
7568         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
7569         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
7570         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
7571         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
7572         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
7573         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
7574         Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."),
7575         Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."),
7576         Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'."),
7577         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
7578         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
7579         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
7580         Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."),
7581         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
7582         File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."),
7583         Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."),
7584         Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."),
7585         Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."),
7586         File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."),
7587         Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."),
7588         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
7589         Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'null' on command line."),
7590         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
7591         Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."),
7592         Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."),
7593         Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."),
7594         Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."),
7595         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
7596         Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."),
7597         Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."),
7598         Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."),
7599         Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."),
7600         Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."),
7601         Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."),
7602         Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."),
7603         Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."),
7604         Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."),
7605         File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."),
7606         Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."),
7607         Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."),
7608         Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"),
7609         Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."),
7610         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
7611         Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."),
7612         Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."),
7613         Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"),
7614         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
7615         paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."),
7616         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
7617         Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."),
7618         Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."),
7619         Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."),
7620         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
7621         File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."),
7622         Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."),
7623         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
7624         package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."),
7625         package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."),
7626         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
7627         Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."),
7628         Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."),
7629         Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."),
7630         baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."),
7631         rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."),
7632         Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."),
7633         Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."),
7634         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
7635         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
7636         Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."),
7637         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
7638         Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"),
7639         Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."),
7640         Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"),
7641         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
7642         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
7643         Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"),
7644         Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"),
7645         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
7646         Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."),
7647         Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"),
7648         Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."),
7649         Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."),
7650         Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."),
7651         Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"),
7652         Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"),
7653         Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."),
7654         Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.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'."),
7655         File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."),
7656         _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true),
7657         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
7658         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
7659         The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.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."),
7660         Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."),
7661         Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true),
7662         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
7663         Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.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}'."),
7664         Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.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."),
7665         Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."),
7666         Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
7667         Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
7668         Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
7669         Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
7670         Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
7671         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
7672         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
7673         Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."),
7674         Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."),
7675         Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."),
7676         Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."),
7677         Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."),
7678         The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"),
7679         Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."),
7680         Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."),
7681         Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."),
7682         Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."),
7683         List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."),
7684         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
7685         The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."),
7686         Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."),
7687         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
7688         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
7689         A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."),
7690         List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."),
7691         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
7692         Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"),
7693         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
7694         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
7695         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
7696         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
7697         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
7698         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
7699         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
7700         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
7701         Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."),
7702         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
7703         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
7704         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
7705         Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."),
7706         Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."),
7707         Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."),
7708         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
7709         Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."),
7710         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
7711         Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
7712         Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.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."),
7713         All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true),
7714         Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."),
7715         Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
7716         Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.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)."),
7717         _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true),
7718         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
7719         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
7720         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
7721         Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.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}"),
7722         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
7723         Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.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}"),
7724         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
7725         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
7726         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
7727         package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."),
7728         package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."),
7729         package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."),
7730         package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."),
7731         An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."),
7732         An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."),
7733         Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"),
7734         Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"),
7735         Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."),
7736         Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."),
7737         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
7738         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
7739         Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2: diag(6218, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218", "======== Module name '{0}' was successfully resolved to '{1}' with Package ID '{2}'. ========"),
7740         Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3: diag(6219, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219", "======== Type reference directive '{0}' was successfully resolved to '{1}' with Package ID '{2}', primary: {3}. ========"),
7741         package_json_had_a_falsy_0_field: diag(6220, ts.DiagnosticCategory.Message, "package_json_had_a_falsy_0_field_6220", "'package.json' had a falsy '{0}' field."),
7742         Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects: diag(6221, ts.DiagnosticCategory.Message, "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221", "Disable use of source files instead of declaration files from referenced projects."),
7743         Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."),
7744         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
7745         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
7746         Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."),
7747         Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."),
7748         Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."),
7749         Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."),
7750         Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."),
7751         Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."),
7752         Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."),
7753         Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."),
7754         This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."),
7755         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
7756         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
7757         Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
7758         Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
7759         Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
7760         File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307", "File '{0}' is not listed within the file list of project '{1}'. Projects must list all files or use an 'include' pattern."),
7761         Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
7762         Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
7763         Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"),
7764         Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"),
7765         Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"),
7766         Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"),
7767         Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"),
7768         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
7769         A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"),
7770         A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"),
7771         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
7772         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
7773         delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"),
7774         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
7775         Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"),
7776         Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"),
7777         Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"),
7778         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
7779         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
7780         Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"),
7781         Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"),
7782         Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
7783         Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
7784         Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
7785         Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
7786         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
7787         A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
7788         A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
7789         Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
7790         Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
7791         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
7792         Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
7793         Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
7794         Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
7795         Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.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"),
7796         Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.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"),
7797         Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.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."),
7798         The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
7799         The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
7800         The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
7801         Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."),
7802         File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"),
7803         Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
7804         Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
7805         Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
7806         new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."),
7807         _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."),
7808         Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."),
7809         Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."),
7810         Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."),
7811         Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."),
7812         Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."),
7813         Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."),
7814         Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."),
7815         Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."),
7816         Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."),
7817         _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."),
7818         _0_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(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' 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."),
7819         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, ts.DiagnosticCategory.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."),
7820         Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation: diag(7025, ts.DiagnosticCategory.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."),
7821         JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.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."),
7822         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
7823         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
7824         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
7825         Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."),
7826         Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."),
7827         Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."),
7828         Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."),
7829         Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."),
7830         Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
7831         Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."),
7832         Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."),
7833         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: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "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."),
7834         Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."),
7835         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: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"),
7836         The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
7837         Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."),
7838         Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
7839         Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
7840         Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
7841         Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."),
7842         Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."),
7843         Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
7844         Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
7845         _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
7846         Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
7847         Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1: diag(7052, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052", "Element implicitly has an 'any' type because type '{0}' has no index signature. Did you mean to call '{1}'?"),
7848         Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1: diag(7053, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053", "Element implicitly has an 'any' type because expression of type '{0}' can't be used to index type '{1}'."),
7849         No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1: diag(7054, ts.DiagnosticCategory.Error, "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054", "No index signature with a parameter of type '{0}' was found on type '{1}'."),
7850         _0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type: diag(7055, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055", "'{0}', which lacks return-type annotation, implicitly has an '{1}' yield type."),
7851         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
7852         You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."),
7853         import_can_only_be_used_in_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."),
7854         export_can_only_be_used_in_TypeScript_files: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_TypeScript_files_8003", "'export =' can only be used in TypeScript files."),
7855         Type_parameter_declarations_can_only_be_used_in_TypeScript_files: diag(8004, ts.DiagnosticCategory.Error, "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004", "Type parameter declarations can only be used in TypeScript files."),
7856         implements_clauses_can_only_be_used_in_TypeScript_files: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_TypeScript_files_8005", "'implements' clauses can only be used in TypeScript files."),
7857         _0_declarations_can_only_be_used_in_TypeScript_files: diag(8006, ts.DiagnosticCategory.Error, "_0_declarations_can_only_be_used_in_TypeScript_files_8006", "'{0}' declarations can only be used in TypeScript files."),
7858         Type_aliases_can_only_be_used_in_TypeScript_files: diag(8008, ts.DiagnosticCategory.Error, "Type_aliases_can_only_be_used_in_TypeScript_files_8008", "Type aliases can only be used in TypeScript files."),
7859         The_0_modifier_can_only_be_used_in_TypeScript_files: diag(8009, ts.DiagnosticCategory.Error, "The_0_modifier_can_only_be_used_in_TypeScript_files_8009", "The '{0}' modifier can only be used in TypeScript files."),
7860         Type_annotations_can_only_be_used_in_TypeScript_files: diag(8010, ts.DiagnosticCategory.Error, "Type_annotations_can_only_be_used_in_TypeScript_files_8010", "Type annotations can only be used in TypeScript files."),
7861         Type_arguments_can_only_be_used_in_TypeScript_files: diag(8011, ts.DiagnosticCategory.Error, "Type_arguments_can_only_be_used_in_TypeScript_files_8011", "Type arguments can only be used in TypeScript files."),
7862         Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, ts.DiagnosticCategory.Error, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."),
7863         Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, ts.DiagnosticCategory.Error, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."),
7864         Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, ts.DiagnosticCategory.Error, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."),
7865         Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."),
7866         Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."),
7867         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
7868         JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."),
7869         JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."),
7870         JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."),
7871         JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."),
7872         JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."),
7873         Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."),
7874         Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."),
7875         Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."),
7876         JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."),
7877         JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."),
7878         The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."),
7879         You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."),
7880         Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."),
7881         Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."),
7882         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
7883         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
7884         Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."),
7885         Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."),
7886         JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."),
7887         JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."),
7888         Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."),
7889         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
7890         Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."),
7891         A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."),
7892         An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
7893         A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
7894         JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."),
7895         super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."),
7896         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
7897         super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."),
7898         _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"),
7899         Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."),
7900         JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
7901         Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
7902         JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
7903         JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
7904         Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"),
7905         Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
7906         A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
7907         The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
7908         No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
7909         File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
7910         This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
7911         Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
7912         JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
7913         require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."),
7914         This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."),
7915         await_has_no_effect_on_the_type_of_this_expression: diag(80007, ts.DiagnosticCategory.Suggestion, "await_has_no_effect_on_the_type_of_this_expression_80007", "'await' has no effect on the type of this expression."),
7916         Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers: diag(80008, ts.DiagnosticCategory.Suggestion, "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008", "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers."),
7917         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
7918         Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
7919         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
7920         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
7921         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
7922         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
7923         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
7924         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
7925         Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
7926         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
7927         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
7928         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
7929         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
7930         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
7931         Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
7932         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
7933         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
7934         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
7935         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
7936         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
7937         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
7938         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
7939         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
7940         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
7941         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
7942         Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"),
7943         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
7944         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
7945         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
7946         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
7947         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
7948         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
7949         Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
7950         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
7951         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
7952         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
7953         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
7954         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
7955         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
7956         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
7957         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
7958         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
7959         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
7960         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
7961         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
7962         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
7963         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
7964         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
7965         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
7966         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
7967         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
7968         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
7969         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
7970         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
7971         Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
7972         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
7973         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
7974         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
7975         Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"),
7976         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
7977         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
7978         Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"),
7979         Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"),
7980         Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"),
7981         Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"),
7982         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
7983         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
7984         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
7985         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
7986         Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"),
7987         Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"),
7988         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
7989         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
7990         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
7991         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
7992         Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"),
7993         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
7994         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
7995         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
7996         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
7997         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
7998         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
7999         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
8000         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
8001         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
8002         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
8003         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
8004         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
8005         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
8006         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
8007         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
8008         Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"),
8009         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
8010         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
8011         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8012         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8013         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8014         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8015         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8016         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8017         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8018         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8019         Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
8020         Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
8021         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8022         Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
8023         Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
8024         Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
8025         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8026         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8027         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8028         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8029         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8030         Infer_this_type_of_0_from_usage: diag(95080, ts.DiagnosticCategory.Message, "Infer_this_type_of_0_from_usage_95080", "Infer 'this' type of '{0}' from usage"),
8031         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8032         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8033         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8034         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8035         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8036         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8037         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8038         Enable_the_jsx_flag_in_your_configuration_file: diag(95088, ts.DiagnosticCategory.Message, "Enable_the_jsx_flag_in_your_configuration_file_95088", "Enable the '--jsx' flag in your configuration file"),
8039         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8040         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8041         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8042         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8043         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8044         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8045         Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"),
8046         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8047         Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"),
8048         Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"),
8049         Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"),
8050         Convert_invalid_character_to_its_html_entity_code: diag(95100, ts.DiagnosticCategory.Message, "Convert_invalid_character_to_its_html_entity_code_95100", "Convert invalid character to its html entity code"),
8051         Convert_all_invalid_characters_to_HTML_entity_code: diag(95101, ts.DiagnosticCategory.Message, "Convert_all_invalid_characters_to_HTML_entity_code_95101", "Convert all invalid characters to HTML entity code"),
8052         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8053         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8054         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8055         Convert_function_expression_0_to_arrow_function: diag(95105, ts.DiagnosticCategory.Message, "Convert_function_expression_0_to_arrow_function_95105", "Convert function expression '{0}' to arrow function"),
8056         Convert_function_declaration_0_to_arrow_function: diag(95106, ts.DiagnosticCategory.Message, "Convert_function_declaration_0_to_arrow_function_95106", "Convert function declaration '{0}' to arrow function"),
8057         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8058         Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"),
8059         Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"),
8060         Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"),
8061         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8062         Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"),
8063         Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"),
8064         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8065         Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"),
8066         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8067         No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."),
8068         Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."),
8069         JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"),
8070         Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"),
8071         An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."),
8072         The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."),
8073         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8074         Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier: diag(18013, ts.DiagnosticCategory.Error, "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013", "Property '{0}' is not accessible outside class '{1}' because it has a private identifier."),
8075         The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling: diag(18014, ts.DiagnosticCategory.Error, "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014", "The property '{0}' cannot be accessed on type '{1}' within this class because it is shadowed by another private identifier with the same spelling."),
8076         Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2: diag(18015, ts.DiagnosticCategory.Error, "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015", "Property '{0}' in type '{1}' refers to a different member that cannot be accessed from within type '{2}'."),
8077         Private_identifiers_are_not_allowed_outside_class_bodies: diag(18016, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_outside_class_bodies_18016", "Private identifiers are not allowed outside class bodies."),
8078         The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"),
8079         The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"),
8080         _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier"),
8081         A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."),
8082         An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."),
8083         An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."),
8084         can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."),
8085         Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."),
8086         Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."),
8087         Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."),
8088         An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."),
8089         The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."),
8090         The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."),
8091         Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."),
8092     };
8093 })(ts || (ts = {}));
8094 var ts;
8095 (function (ts) {
8096     var _a;
8097     /* @internal */
8098     function tokenIsIdentifierOrKeyword(token) {
8099         return token >= 75 /* Identifier */;
8100     }
8101     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
8102     /* @internal */
8103     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
8104         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
8105     }
8106     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
8107     var textToKeywordObj = (_a = {
8108             abstract: 122 /* AbstractKeyword */,
8109             any: 125 /* AnyKeyword */,
8110             as: 123 /* AsKeyword */,
8111             asserts: 124 /* AssertsKeyword */,
8112             bigint: 151 /* BigIntKeyword */,
8113             boolean: 128 /* BooleanKeyword */,
8114             break: 77 /* BreakKeyword */,
8115             case: 78 /* CaseKeyword */,
8116             catch: 79 /* CatchKeyword */,
8117             class: 80 /* ClassKeyword */,
8118             continue: 82 /* ContinueKeyword */,
8119             const: 81 /* ConstKeyword */
8120         },
8121         _a["" + "constructor"] = 129 /* ConstructorKeyword */,
8122         _a.debugger = 83 /* DebuggerKeyword */,
8123         _a.declare = 130 /* DeclareKeyword */,
8124         _a.default = 84 /* DefaultKeyword */,
8125         _a.delete = 85 /* DeleteKeyword */,
8126         _a.do = 86 /* DoKeyword */,
8127         _a.else = 87 /* ElseKeyword */,
8128         _a.enum = 88 /* EnumKeyword */,
8129         _a.export = 89 /* ExportKeyword */,
8130         _a.extends = 90 /* ExtendsKeyword */,
8131         _a.false = 91 /* FalseKeyword */,
8132         _a.finally = 92 /* FinallyKeyword */,
8133         _a.for = 93 /* ForKeyword */,
8134         _a.from = 149 /* FromKeyword */,
8135         _a.function = 94 /* FunctionKeyword */,
8136         _a.get = 131 /* GetKeyword */,
8137         _a.if = 95 /* IfKeyword */,
8138         _a.implements = 113 /* ImplementsKeyword */,
8139         _a.import = 96 /* ImportKeyword */,
8140         _a.in = 97 /* InKeyword */,
8141         _a.infer = 132 /* InferKeyword */,
8142         _a.instanceof = 98 /* InstanceOfKeyword */,
8143         _a.interface = 114 /* InterfaceKeyword */,
8144         _a.is = 133 /* IsKeyword */,
8145         _a.keyof = 134 /* KeyOfKeyword */,
8146         _a.let = 115 /* LetKeyword */,
8147         _a.module = 135 /* ModuleKeyword */,
8148         _a.namespace = 136 /* NamespaceKeyword */,
8149         _a.never = 137 /* NeverKeyword */,
8150         _a.new = 99 /* NewKeyword */,
8151         _a.null = 100 /* NullKeyword */,
8152         _a.number = 140 /* NumberKeyword */,
8153         _a.object = 141 /* ObjectKeyword */,
8154         _a.package = 116 /* PackageKeyword */,
8155         _a.private = 117 /* PrivateKeyword */,
8156         _a.protected = 118 /* ProtectedKeyword */,
8157         _a.public = 119 /* PublicKeyword */,
8158         _a.readonly = 138 /* ReadonlyKeyword */,
8159         _a.require = 139 /* RequireKeyword */,
8160         _a.global = 150 /* GlobalKeyword */,
8161         _a.return = 101 /* ReturnKeyword */,
8162         _a.set = 142 /* SetKeyword */,
8163         _a.static = 120 /* StaticKeyword */,
8164         _a.string = 143 /* StringKeyword */,
8165         _a.super = 102 /* SuperKeyword */,
8166         _a.switch = 103 /* SwitchKeyword */,
8167         _a.symbol = 144 /* SymbolKeyword */,
8168         _a.this = 104 /* ThisKeyword */,
8169         _a.throw = 105 /* ThrowKeyword */,
8170         _a.true = 106 /* TrueKeyword */,
8171         _a.try = 107 /* TryKeyword */,
8172         _a.type = 145 /* TypeKeyword */,
8173         _a.typeof = 108 /* TypeOfKeyword */,
8174         _a.undefined = 146 /* UndefinedKeyword */,
8175         _a.unique = 147 /* UniqueKeyword */,
8176         _a.unknown = 148 /* UnknownKeyword */,
8177         _a.var = 109 /* VarKeyword */,
8178         _a.void = 110 /* VoidKeyword */,
8179         _a.while = 111 /* WhileKeyword */,
8180         _a.with = 112 /* WithKeyword */,
8181         _a.yield = 121 /* YieldKeyword */,
8182         _a.async = 126 /* AsyncKeyword */,
8183         _a.await = 127 /* AwaitKeyword */,
8184         _a.of = 152 /* OfKeyword */,
8185         _a);
8186     var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
8187     var textToToken = ts.createMapFromTemplate(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, "</": 30 /* LessThanSlashToken */, ">>": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 74 /* CaretEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }));
8188     /*
8189         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
8190         IdentifierStart ::
8191             Can contain Unicode 3.0.0 categories:
8192             Uppercase letter (Lu),
8193             Lowercase letter (Ll),
8194             Titlecase letter (Lt),
8195             Modifier letter (Lm),
8196             Other letter (Lo), or
8197             Letter number (Nl).
8198         IdentifierPart :: =
8199             Can contain IdentifierStart + Unicode 3.0.0 categories:
8200             Non-spacing mark (Mn),
8201             Combining spacing mark (Mc),
8202             Decimal number (Nd), or
8203             Connector punctuation (Pc).
8204
8205         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
8206         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
8207     */
8208     var 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,];
8209     var 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,];
8210     /*
8211         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
8212         IdentifierStart ::
8213             Can contain Unicode 6.2 categories:
8214             Uppercase letter (Lu),
8215             Lowercase letter (Ll),
8216             Titlecase letter (Lt),
8217             Modifier letter (Lm),
8218             Other letter (Lo), or
8219             Letter number (Nl).
8220         IdentifierPart ::
8221             Can contain IdentifierStart + Unicode 6.2 categories:
8222             Non-spacing mark (Mn),
8223             Combining spacing mark (Mc),
8224             Decimal number (Nd),
8225             Connector punctuation (Pc),
8226             <ZWNJ>, or
8227             <ZWJ>.
8228
8229         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
8230         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
8231     */
8232     var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 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, 43000, 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,];
8233     var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
8234     /**
8235      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
8236      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
8237      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
8238      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
8239      */
8240     var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101];
8241     var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999];
8242     /**
8243      * Test for whether a single line comment's text contains a directive.
8244      */
8245     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
8246     /**
8247      * Test for whether a multi-line comment's last line contains a directive.
8248      */
8249     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
8250     function lookupInUnicodeMap(code, map) {
8251         // Bail out quickly if it couldn't possibly be in the map.
8252         if (code < map[0]) {
8253             return false;
8254         }
8255         // Perform binary search in one of the Unicode range maps
8256         var lo = 0;
8257         var hi = map.length;
8258         var mid;
8259         while (lo + 1 < hi) {
8260             mid = lo + (hi - lo) / 2;
8261             // mid has to be even to catch a range's beginning
8262             mid -= mid % 2;
8263             if (map[mid] <= code && code <= map[mid + 1]) {
8264                 return true;
8265             }
8266             if (code < map[mid]) {
8267                 hi = mid;
8268             }
8269             else {
8270                 lo = mid + 2;
8271             }
8272         }
8273         return false;
8274     }
8275     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
8276         return languageVersion >= 2 /* ES2015 */ ?
8277             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
8278             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
8279                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
8280     }
8281     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
8282     function isUnicodeIdentifierPart(code, languageVersion) {
8283         return languageVersion >= 2 /* ES2015 */ ?
8284             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
8285             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
8286                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
8287     }
8288     function makeReverseMap(source) {
8289         var result = [];
8290         source.forEach(function (value, name) {
8291             result[value] = name;
8292         });
8293         return result;
8294     }
8295     var tokenStrings = makeReverseMap(textToToken);
8296     function tokenToString(t) {
8297         return tokenStrings[t];
8298     }
8299     ts.tokenToString = tokenToString;
8300     /* @internal */
8301     function stringToToken(s) {
8302         return textToToken.get(s);
8303     }
8304     ts.stringToToken = stringToToken;
8305     /* @internal */
8306     function computeLineStarts(text) {
8307         var result = new Array();
8308         var pos = 0;
8309         var lineStart = 0;
8310         while (pos < text.length) {
8311             var ch = text.charCodeAt(pos);
8312             pos++;
8313             switch (ch) {
8314                 case 13 /* carriageReturn */:
8315                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
8316                         pos++;
8317                     }
8318                 // falls through
8319                 case 10 /* lineFeed */:
8320                     result.push(lineStart);
8321                     lineStart = pos;
8322                     break;
8323                 default:
8324                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
8325                         result.push(lineStart);
8326                         lineStart = pos;
8327                     }
8328                     break;
8329             }
8330         }
8331         result.push(lineStart);
8332         return result;
8333     }
8334     ts.computeLineStarts = computeLineStarts;
8335     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
8336         return sourceFile.getPositionOfLineAndCharacter ?
8337             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
8338             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
8339     }
8340     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
8341     /* @internal */
8342     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
8343         if (line < 0 || line >= lineStarts.length) {
8344             if (allowEdits) {
8345                 // Clamp line to nearest allowable value
8346                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
8347             }
8348             else {
8349                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
8350             }
8351         }
8352         var res = lineStarts[line] + character;
8353         if (allowEdits) {
8354             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
8355             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
8356             // apply them to the computed position to improve accuracy
8357             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
8358         }
8359         if (line < lineStarts.length - 1) {
8360             ts.Debug.assert(res < lineStarts[line + 1]);
8361         }
8362         else if (debugText !== undefined) {
8363             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
8364         }
8365         return res;
8366     }
8367     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
8368     /* @internal */
8369     function getLineStarts(sourceFile) {
8370         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
8371     }
8372     ts.getLineStarts = getLineStarts;
8373     /* @internal */
8374     function computeLineAndCharacterOfPosition(lineStarts, position) {
8375         var lineNumber = computeLineOfPosition(lineStarts, position);
8376         return {
8377             line: lineNumber,
8378             character: position - lineStarts[lineNumber]
8379         };
8380     }
8381     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
8382     /**
8383      * @internal
8384      * We assume the first line starts at position 0 and 'position' is non-negative.
8385      */
8386     function computeLineOfPosition(lineStarts, position, lowerBound) {
8387         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
8388         if (lineNumber < 0) {
8389             // If the actual position was not found,
8390             // the binary search returns the 2's-complement of the next line start
8391             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
8392             // then the search will return -2.
8393             //
8394             // We want the index of the previous line start, so we subtract 1.
8395             // Review 2's-complement if this is confusing.
8396             lineNumber = ~lineNumber - 1;
8397             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
8398         }
8399         return lineNumber;
8400     }
8401     ts.computeLineOfPosition = computeLineOfPosition;
8402     /** @internal */
8403     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
8404         if (pos1 === pos2)
8405             return 0;
8406         var lineStarts = getLineStarts(sourceFile);
8407         var lower = Math.min(pos1, pos2);
8408         var isNegative = lower === pos2;
8409         var upper = isNegative ? pos1 : pos2;
8410         var lowerLine = computeLineOfPosition(lineStarts, lower);
8411         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
8412         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
8413     }
8414     ts.getLinesBetweenPositions = getLinesBetweenPositions;
8415     function getLineAndCharacterOfPosition(sourceFile, position) {
8416         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
8417     }
8418     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
8419     function isWhiteSpaceLike(ch) {
8420         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
8421     }
8422     ts.isWhiteSpaceLike = isWhiteSpaceLike;
8423     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
8424     function isWhiteSpaceSingleLine(ch) {
8425         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
8426         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
8427         return ch === 32 /* space */ ||
8428             ch === 9 /* tab */ ||
8429             ch === 11 /* verticalTab */ ||
8430             ch === 12 /* formFeed */ ||
8431             ch === 160 /* nonBreakingSpace */ ||
8432             ch === 133 /* nextLine */ ||
8433             ch === 5760 /* ogham */ ||
8434             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
8435             ch === 8239 /* narrowNoBreakSpace */ ||
8436             ch === 8287 /* mathematicalSpace */ ||
8437             ch === 12288 /* ideographicSpace */ ||
8438             ch === 65279 /* byteOrderMark */;
8439     }
8440     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
8441     function isLineBreak(ch) {
8442         // ES5 7.3:
8443         // The ECMAScript line terminator characters are listed in Table 3.
8444         //     Table 3: Line Terminator Characters
8445         //     Code Unit Value     Name                    Formal Name
8446         //     \u000A              Line Feed               <LF>
8447         //     \u000D              Carriage Return         <CR>
8448         //     \u2028              Line separator          <LS>
8449         //     \u2029              Paragraph separator     <PS>
8450         // Only the characters in Table 3 are treated as line terminators. Other new line or line
8451         // breaking characters are treated as white space but not as line terminators.
8452         return ch === 10 /* lineFeed */ ||
8453             ch === 13 /* carriageReturn */ ||
8454             ch === 8232 /* lineSeparator */ ||
8455             ch === 8233 /* paragraphSeparator */;
8456     }
8457     ts.isLineBreak = isLineBreak;
8458     function isDigit(ch) {
8459         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
8460     }
8461     function isHexDigit(ch) {
8462         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
8463     }
8464     function isCodePoint(code) {
8465         return code <= 0x10FFFF;
8466     }
8467     /* @internal */
8468     function isOctalDigit(ch) {
8469         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
8470     }
8471     ts.isOctalDigit = isOctalDigit;
8472     function couldStartTrivia(text, pos) {
8473         // Keep in sync with skipTrivia
8474         var ch = text.charCodeAt(pos);
8475         switch (ch) {
8476             case 13 /* carriageReturn */:
8477             case 10 /* lineFeed */:
8478             case 9 /* tab */:
8479             case 11 /* verticalTab */:
8480             case 12 /* formFeed */:
8481             case 32 /* space */:
8482             case 47 /* slash */:
8483             // starts of normal trivia
8484             // falls through
8485             case 60 /* lessThan */:
8486             case 124 /* bar */:
8487             case 61 /* equals */:
8488             case 62 /* greaterThan */:
8489                 // Starts of conflict marker trivia
8490                 return true;
8491             case 35 /* hash */:
8492                 // Only if its the beginning can we have #! trivia
8493                 return pos === 0;
8494             default:
8495                 return ch > 127 /* maxAsciiCharacter */;
8496         }
8497     }
8498     ts.couldStartTrivia = couldStartTrivia;
8499     /* @internal */
8500     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
8501         if (stopAtComments === void 0) { stopAtComments = false; }
8502         if (ts.positionIsSynthesized(pos)) {
8503             return pos;
8504         }
8505         // Keep in sync with couldStartTrivia
8506         while (true) {
8507             var ch = text.charCodeAt(pos);
8508             switch (ch) {
8509                 case 13 /* carriageReturn */:
8510                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8511                         pos++;
8512                     }
8513                 // falls through
8514                 case 10 /* lineFeed */:
8515                     pos++;
8516                     if (stopAfterLineBreak) {
8517                         return pos;
8518                     }
8519                     continue;
8520                 case 9 /* tab */:
8521                 case 11 /* verticalTab */:
8522                 case 12 /* formFeed */:
8523                 case 32 /* space */:
8524                     pos++;
8525                     continue;
8526                 case 47 /* slash */:
8527                     if (stopAtComments) {
8528                         break;
8529                     }
8530                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
8531                         pos += 2;
8532                         while (pos < text.length) {
8533                             if (isLineBreak(text.charCodeAt(pos))) {
8534                                 break;
8535                             }
8536                             pos++;
8537                         }
8538                         continue;
8539                     }
8540                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
8541                         pos += 2;
8542                         while (pos < text.length) {
8543                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8544                                 pos += 2;
8545                                 break;
8546                             }
8547                             pos++;
8548                         }
8549                         continue;
8550                     }
8551                     break;
8552                 case 60 /* lessThan */:
8553                 case 124 /* bar */:
8554                 case 61 /* equals */:
8555                 case 62 /* greaterThan */:
8556                     if (isConflictMarkerTrivia(text, pos)) {
8557                         pos = scanConflictMarkerTrivia(text, pos);
8558                         continue;
8559                     }
8560                     break;
8561                 case 35 /* hash */:
8562                     if (pos === 0 && isShebangTrivia(text, pos)) {
8563                         pos = scanShebangTrivia(text, pos);
8564                         continue;
8565                     }
8566                     break;
8567                 default:
8568                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8569                         pos++;
8570                         continue;
8571                     }
8572                     break;
8573             }
8574             return pos;
8575         }
8576     }
8577     ts.skipTrivia = skipTrivia;
8578     // All conflict markers consist of the same character repeated seven times.  If it is
8579     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
8580     var mergeConflictMarkerLength = "<<<<<<<".length;
8581     function isConflictMarkerTrivia(text, pos) {
8582         ts.Debug.assert(pos >= 0);
8583         // Conflict markers must be at the start of a line.
8584         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
8585             var ch = text.charCodeAt(pos);
8586             if ((pos + mergeConflictMarkerLength) < text.length) {
8587                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
8588                     if (text.charCodeAt(pos + i) !== ch) {
8589                         return false;
8590                     }
8591                 }
8592                 return ch === 61 /* equals */ ||
8593                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
8594             }
8595         }
8596         return false;
8597     }
8598     function scanConflictMarkerTrivia(text, pos, error) {
8599         if (error) {
8600             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
8601         }
8602         var ch = text.charCodeAt(pos);
8603         var len = text.length;
8604         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
8605             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
8606                 pos++;
8607             }
8608         }
8609         else {
8610             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
8611             // Consume everything from the start of a ||||||| or ======= marker to the start
8612             // of the next ======= or >>>>>>> marker.
8613             while (pos < len) {
8614                 var currentChar = text.charCodeAt(pos);
8615                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
8616                     break;
8617                 }
8618                 pos++;
8619             }
8620         }
8621         return pos;
8622     }
8623     var shebangTriviaRegex = /^#!.*/;
8624     /*@internal*/
8625     function isShebangTrivia(text, pos) {
8626         // Shebangs check must only be done at the start of the file
8627         ts.Debug.assert(pos === 0);
8628         return shebangTriviaRegex.test(text);
8629     }
8630     ts.isShebangTrivia = isShebangTrivia;
8631     /*@internal*/
8632     function scanShebangTrivia(text, pos) {
8633         var shebang = shebangTriviaRegex.exec(text)[0];
8634         pos = pos + shebang.length;
8635         return pos;
8636     }
8637     ts.scanShebangTrivia = scanShebangTrivia;
8638     /**
8639      * Invokes a callback for each comment range following the provided position.
8640      *
8641      * Single-line comment ranges include the leading double-slash characters but not the ending
8642      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
8643      * asterisk-slash characters.
8644      *
8645      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
8646      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
8647      * @param text The source text to scan.
8648      * @param pos The position at which to start scanning.
8649      * @param trailing If false, whitespace is skipped until the first line break and comments
8650      *      between that location and the next token are returned. If true, comments occurring
8651      *      between the given position and the next line break are returned.
8652      * @param cb The callback to execute as each comment range is encountered.
8653      * @param state A state value to pass to each iteration of the callback.
8654      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
8655      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
8656      *      return value of the callback.
8657      */
8658     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
8659         var pendingPos;
8660         var pendingEnd;
8661         var pendingKind;
8662         var pendingHasTrailingNewLine;
8663         var hasPendingCommentRange = false;
8664         var collecting = trailing;
8665         var accumulator = initial;
8666         if (pos === 0) {
8667             collecting = true;
8668             var shebang = getShebang(text);
8669             if (shebang) {
8670                 pos = shebang.length;
8671             }
8672         }
8673         scan: while (pos >= 0 && pos < text.length) {
8674             var ch = text.charCodeAt(pos);
8675             switch (ch) {
8676                 case 13 /* carriageReturn */:
8677                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8678                         pos++;
8679                     }
8680                 // falls through
8681                 case 10 /* lineFeed */:
8682                     pos++;
8683                     if (trailing) {
8684                         break scan;
8685                     }
8686                     collecting = true;
8687                     if (hasPendingCommentRange) {
8688                         pendingHasTrailingNewLine = true;
8689                     }
8690                     continue;
8691                 case 9 /* tab */:
8692                 case 11 /* verticalTab */:
8693                 case 12 /* formFeed */:
8694                 case 32 /* space */:
8695                     pos++;
8696                     continue;
8697                 case 47 /* slash */:
8698                     var nextChar = text.charCodeAt(pos + 1);
8699                     var hasTrailingNewLine = false;
8700                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
8701                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
8702                         var startPos = pos;
8703                         pos += 2;
8704                         if (nextChar === 47 /* slash */) {
8705                             while (pos < text.length) {
8706                                 if (isLineBreak(text.charCodeAt(pos))) {
8707                                     hasTrailingNewLine = true;
8708                                     break;
8709                                 }
8710                                 pos++;
8711                             }
8712                         }
8713                         else {
8714                             while (pos < text.length) {
8715                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8716                                     pos += 2;
8717                                     break;
8718                                 }
8719                                 pos++;
8720                             }
8721                         }
8722                         if (collecting) {
8723                             if (hasPendingCommentRange) {
8724                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8725                                 if (!reduce && accumulator) {
8726                                     // If we are not reducing and we have a truthy result, return it.
8727                                     return accumulator;
8728                                 }
8729                             }
8730                             pendingPos = startPos;
8731                             pendingEnd = pos;
8732                             pendingKind = kind;
8733                             pendingHasTrailingNewLine = hasTrailingNewLine;
8734                             hasPendingCommentRange = true;
8735                         }
8736                         continue;
8737                     }
8738                     break scan;
8739                 default:
8740                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8741                         if (hasPendingCommentRange && isLineBreak(ch)) {
8742                             pendingHasTrailingNewLine = true;
8743                         }
8744                         pos++;
8745                         continue;
8746                     }
8747                     break scan;
8748             }
8749         }
8750         if (hasPendingCommentRange) {
8751             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8752         }
8753         return accumulator;
8754     }
8755     function forEachLeadingCommentRange(text, pos, cb, state) {
8756         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
8757     }
8758     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
8759     function forEachTrailingCommentRange(text, pos, cb, state) {
8760         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
8761     }
8762     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
8763     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
8764         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
8765     }
8766     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
8767     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
8768         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
8769     }
8770     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
8771     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
8772         if (!comments) {
8773             comments = [];
8774         }
8775         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
8776         return comments;
8777     }
8778     function getLeadingCommentRanges(text, pos) {
8779         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8780     }
8781     ts.getLeadingCommentRanges = getLeadingCommentRanges;
8782     function getTrailingCommentRanges(text, pos) {
8783         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8784     }
8785     ts.getTrailingCommentRanges = getTrailingCommentRanges;
8786     /** Optionally, get the shebang */
8787     function getShebang(text) {
8788         var match = shebangTriviaRegex.exec(text);
8789         if (match) {
8790             return match[0];
8791         }
8792     }
8793     ts.getShebang = getShebang;
8794     function isIdentifierStart(ch, languageVersion) {
8795         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8796             ch === 36 /* $ */ || ch === 95 /* _ */ ||
8797             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
8798     }
8799     ts.isIdentifierStart = isIdentifierStart;
8800     function isIdentifierPart(ch, languageVersion, identifierVariant) {
8801         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8802             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
8803             // "-" and ":" are valid in JSX Identifiers
8804             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
8805             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
8806     }
8807     ts.isIdentifierPart = isIdentifierPart;
8808     /* @internal */
8809     function isIdentifierText(name, languageVersion, identifierVariant) {
8810         var ch = codePointAt(name, 0);
8811         if (!isIdentifierStart(ch, languageVersion)) {
8812             return false;
8813         }
8814         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
8815             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
8816                 return false;
8817             }
8818         }
8819         return true;
8820     }
8821     ts.isIdentifierText = isIdentifierText;
8822     // Creates a scanner over a (possibly unspecified) range of a piece of text.
8823     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
8824         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
8825         var text = textInitial;
8826         // Current position (end position of text of current token)
8827         var pos;
8828         // end of text
8829         var end;
8830         // Start position of whitespace before current token
8831         var startPos;
8832         // Start position of text of current token
8833         var tokenPos;
8834         var token;
8835         var tokenValue;
8836         var tokenFlags;
8837         var commentDirectives;
8838         var inJSDocType = 0;
8839         setText(text, start, length);
8840         var scanner = {
8841             getStartPos: function () { return startPos; },
8842             getTextPos: function () { return pos; },
8843             getToken: function () { return token; },
8844             getTokenPos: function () { return tokenPos; },
8845             getTokenText: function () { return text.substring(tokenPos, pos); },
8846             getTokenValue: function () { return tokenValue; },
8847             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
8848             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
8849             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
8850             isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; },
8851             isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; },
8852             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
8853             getCommentDirectives: function () { return commentDirectives; },
8854             getTokenFlags: function () { return tokenFlags; },
8855             reScanGreaterToken: reScanGreaterToken,
8856             reScanSlashToken: reScanSlashToken,
8857             reScanTemplateToken: reScanTemplateToken,
8858             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
8859             scanJsxIdentifier: scanJsxIdentifier,
8860             scanJsxAttributeValue: scanJsxAttributeValue,
8861             reScanJsxAttributeValue: reScanJsxAttributeValue,
8862             reScanJsxToken: reScanJsxToken,
8863             reScanLessThanToken: reScanLessThanToken,
8864             reScanQuestionToken: reScanQuestionToken,
8865             scanJsxToken: scanJsxToken,
8866             scanJsDocToken: scanJsDocToken,
8867             scan: scan,
8868             getText: getText,
8869             clearCommentDirectives: clearCommentDirectives,
8870             setText: setText,
8871             setScriptTarget: setScriptTarget,
8872             setLanguageVariant: setLanguageVariant,
8873             setOnError: setOnError,
8874             setTextPos: setTextPos,
8875             setInJSDocType: setInJSDocType,
8876             tryScan: tryScan,
8877             lookAhead: lookAhead,
8878             scanRange: scanRange,
8879         };
8880         if (ts.Debug.isDebugging) {
8881             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
8882                 get: function () {
8883                     var text = scanner.getText();
8884                     return text.slice(0, scanner.getStartPos()) + "║" + text.slice(scanner.getStartPos());
8885                 },
8886             });
8887         }
8888         return scanner;
8889         function error(message, errPos, length) {
8890             if (errPos === void 0) { errPos = pos; }
8891             if (onError) {
8892                 var oldPos = pos;
8893                 pos = errPos;
8894                 onError(message, length || 0);
8895                 pos = oldPos;
8896             }
8897         }
8898         function scanNumberFragment() {
8899             var start = pos;
8900             var allowSeparator = false;
8901             var isPreviousTokenSeparator = false;
8902             var result = "";
8903             while (true) {
8904                 var ch = text.charCodeAt(pos);
8905                 if (ch === 95 /* _ */) {
8906                     tokenFlags |= 512 /* ContainsSeparator */;
8907                     if (allowSeparator) {
8908                         allowSeparator = false;
8909                         isPreviousTokenSeparator = true;
8910                         result += text.substring(start, pos);
8911                     }
8912                     else if (isPreviousTokenSeparator) {
8913                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
8914                     }
8915                     else {
8916                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
8917                     }
8918                     pos++;
8919                     start = pos;
8920                     continue;
8921                 }
8922                 if (isDigit(ch)) {
8923                     allowSeparator = true;
8924                     isPreviousTokenSeparator = false;
8925                     pos++;
8926                     continue;
8927                 }
8928                 break;
8929             }
8930             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
8931                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
8932             }
8933             return result + text.substring(start, pos);
8934         }
8935         function scanNumber() {
8936             var start = pos;
8937             var mainFragment = scanNumberFragment();
8938             var decimalFragment;
8939             var scientificFragment;
8940             if (text.charCodeAt(pos) === 46 /* dot */) {
8941                 pos++;
8942                 decimalFragment = scanNumberFragment();
8943             }
8944             var end = pos;
8945             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
8946                 pos++;
8947                 tokenFlags |= 16 /* Scientific */;
8948                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
8949                     pos++;
8950                 var preNumericPart = pos;
8951                 var finalFragment = scanNumberFragment();
8952                 if (!finalFragment) {
8953                     error(ts.Diagnostics.Digit_expected);
8954                 }
8955                 else {
8956                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
8957                     end = pos;
8958                 }
8959             }
8960             var result;
8961             if (tokenFlags & 512 /* ContainsSeparator */) {
8962                 result = mainFragment;
8963                 if (decimalFragment) {
8964                     result += "." + decimalFragment;
8965                 }
8966                 if (scientificFragment) {
8967                     result += scientificFragment;
8968                 }
8969             }
8970             else {
8971                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
8972             }
8973             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
8974                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
8975                 return {
8976                     type: 8 /* NumericLiteral */,
8977                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
8978                 };
8979             }
8980             else {
8981                 tokenValue = result;
8982                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
8983                 checkForIdentifierStartAfterNumericLiteral(start);
8984                 return { type: type, value: tokenValue };
8985             }
8986         }
8987         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
8988             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
8989                 return;
8990             }
8991             var identifierStart = pos;
8992             var length = scanIdentifierParts().length;
8993             if (length === 1 && text[identifierStart] === "n") {
8994                 if (isScientific) {
8995                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
8996                 }
8997                 else {
8998                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
8999                 }
9000             }
9001             else {
9002                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
9003                 pos = identifierStart;
9004             }
9005         }
9006         function scanOctalDigits() {
9007             var start = pos;
9008             while (isOctalDigit(text.charCodeAt(pos))) {
9009                 pos++;
9010             }
9011             return +(text.substring(start, pos));
9012         }
9013         /**
9014          * Scans the given number of hexadecimal digits in the text,
9015          * returning -1 if the given number is unavailable.
9016          */
9017         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9018             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9019             return valueString ? parseInt(valueString, 16) : -1;
9020         }
9021         /**
9022          * Scans as many hexadecimal digits as are available in the text,
9023          * returning "" if the given number of digits was unavailable.
9024          */
9025         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9026             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9027         }
9028         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9029             var valueChars = [];
9030             var allowSeparator = false;
9031             var isPreviousTokenSeparator = false;
9032             while (valueChars.length < minCount || scanAsManyAsPossible) {
9033                 var ch = text.charCodeAt(pos);
9034                 if (canHaveSeparators && ch === 95 /* _ */) {
9035                     tokenFlags |= 512 /* ContainsSeparator */;
9036                     if (allowSeparator) {
9037                         allowSeparator = false;
9038                         isPreviousTokenSeparator = true;
9039                     }
9040                     else if (isPreviousTokenSeparator) {
9041                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9042                     }
9043                     else {
9044                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9045                     }
9046                     pos++;
9047                     continue;
9048                 }
9049                 allowSeparator = canHaveSeparators;
9050                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9051                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9052                 }
9053                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9054                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9055                     break;
9056                 }
9057                 valueChars.push(ch);
9058                 pos++;
9059                 isPreviousTokenSeparator = false;
9060             }
9061             if (valueChars.length < minCount) {
9062                 valueChars = [];
9063             }
9064             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9065                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9066             }
9067             return String.fromCharCode.apply(String, valueChars);
9068         }
9069         function scanString(jsxAttributeString) {
9070             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9071             var quote = text.charCodeAt(pos);
9072             pos++;
9073             var result = "";
9074             var start = pos;
9075             while (true) {
9076                 if (pos >= end) {
9077                     result += text.substring(start, pos);
9078                     tokenFlags |= 4 /* Unterminated */;
9079                     error(ts.Diagnostics.Unterminated_string_literal);
9080                     break;
9081                 }
9082                 var ch = text.charCodeAt(pos);
9083                 if (ch === quote) {
9084                     result += text.substring(start, pos);
9085                     pos++;
9086                     break;
9087                 }
9088                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
9089                     result += text.substring(start, pos);
9090                     result += scanEscapeSequence();
9091                     start = pos;
9092                     continue;
9093                 }
9094                 if (isLineBreak(ch) && !jsxAttributeString) {
9095                     result += text.substring(start, pos);
9096                     tokenFlags |= 4 /* Unterminated */;
9097                     error(ts.Diagnostics.Unterminated_string_literal);
9098                     break;
9099                 }
9100                 pos++;
9101             }
9102             return result;
9103         }
9104         /**
9105          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
9106          * a literal component of a TemplateExpression.
9107          */
9108         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
9109             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
9110             pos++;
9111             var start = pos;
9112             var contents = "";
9113             var resultingToken;
9114             while (true) {
9115                 if (pos >= end) {
9116                     contents += text.substring(start, pos);
9117                     tokenFlags |= 4 /* Unterminated */;
9118                     error(ts.Diagnostics.Unterminated_template_literal);
9119                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9120                     break;
9121                 }
9122                 var currChar = text.charCodeAt(pos);
9123                 // '`'
9124                 if (currChar === 96 /* backtick */) {
9125                     contents += text.substring(start, pos);
9126                     pos++;
9127                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9128                     break;
9129                 }
9130                 // '${'
9131                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
9132                     contents += text.substring(start, pos);
9133                     pos += 2;
9134                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
9135                     break;
9136                 }
9137                 // Escape character
9138                 if (currChar === 92 /* backslash */) {
9139                     contents += text.substring(start, pos);
9140                     contents += scanEscapeSequence(isTaggedTemplate);
9141                     start = pos;
9142                     continue;
9143                 }
9144                 // Speculated ECMAScript 6 Spec 11.8.6.1:
9145                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
9146                 if (currChar === 13 /* carriageReturn */) {
9147                     contents += text.substring(start, pos);
9148                     pos++;
9149                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9150                         pos++;
9151                     }
9152                     contents += "\n";
9153                     start = pos;
9154                     continue;
9155                 }
9156                 pos++;
9157             }
9158             ts.Debug.assert(resultingToken !== undefined);
9159             tokenValue = contents;
9160             return resultingToken;
9161         }
9162         function scanEscapeSequence(isTaggedTemplate) {
9163             var start = pos;
9164             pos++;
9165             if (pos >= end) {
9166                 error(ts.Diagnostics.Unexpected_end_of_text);
9167                 return "";
9168             }
9169             var ch = text.charCodeAt(pos);
9170             pos++;
9171             switch (ch) {
9172                 case 48 /* _0 */:
9173                     // '\01'
9174                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
9175                         pos++;
9176                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
9177                         return text.substring(start, pos);
9178                     }
9179                     return "\0";
9180                 case 98 /* b */:
9181                     return "\b";
9182                 case 116 /* t */:
9183                     return "\t";
9184                 case 110 /* n */:
9185                     return "\n";
9186                 case 118 /* v */:
9187                     return "\v";
9188                 case 102 /* f */:
9189                     return "\f";
9190                 case 114 /* r */:
9191                     return "\r";
9192                 case 39 /* singleQuote */:
9193                     return "\'";
9194                 case 34 /* doubleQuote */:
9195                     return "\"";
9196                 case 117 /* u */:
9197                     if (isTaggedTemplate) {
9198                         // '\u' or '\u0' or '\u00' or '\u000'
9199                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
9200                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
9201                                 pos = escapePos;
9202                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9203                                 return text.substring(start, pos);
9204                             }
9205                         }
9206                     }
9207                     // '\u{DDDDDDDD}'
9208                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
9209                         pos++;
9210                         // '\u{'
9211                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
9212                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9213                             return text.substring(start, pos);
9214                         }
9215                         if (isTaggedTemplate) {
9216                             var savePos = pos;
9217                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9218                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9219                             // '\u{Not Code Point' or '\u{CodePoint'
9220                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
9221                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9222                                 return text.substring(start, pos);
9223                             }
9224                             else {
9225                                 pos = savePos;
9226                             }
9227                         }
9228                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9229                         return scanExtendedUnicodeEscape();
9230                     }
9231                     tokenFlags |= 1024 /* UnicodeEscape */;
9232                     // '\uDDDD'
9233                     return scanHexadecimalEscape(/*numDigits*/ 4);
9234                 case 120 /* x */:
9235                     if (isTaggedTemplate) {
9236                         if (!isHexDigit(text.charCodeAt(pos))) {
9237                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9238                             return text.substring(start, pos);
9239                         }
9240                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
9241                             pos++;
9242                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9243                             return text.substring(start, pos);
9244                         }
9245                     }
9246                     // '\xDD'
9247                     return scanHexadecimalEscape(/*numDigits*/ 2);
9248                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
9249                 // the line terminator is interpreted to be "the empty code unit sequence".
9250                 case 13 /* carriageReturn */:
9251                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9252                         pos++;
9253                     }
9254                 // falls through
9255                 case 10 /* lineFeed */:
9256                 case 8232 /* lineSeparator */:
9257                 case 8233 /* paragraphSeparator */:
9258                     return "";
9259                 default:
9260                     return String.fromCharCode(ch);
9261             }
9262         }
9263         function scanHexadecimalEscape(numDigits) {
9264             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
9265             if (escapedValue >= 0) {
9266                 return String.fromCharCode(escapedValue);
9267             }
9268             else {
9269                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9270                 return "";
9271             }
9272         }
9273         function scanExtendedUnicodeEscape() {
9274             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9275             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9276             var isInvalidExtendedEscape = false;
9277             // Validate the value of the digit
9278             if (escapedValue < 0) {
9279                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9280                 isInvalidExtendedEscape = true;
9281             }
9282             else if (escapedValue > 0x10FFFF) {
9283                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
9284                 isInvalidExtendedEscape = true;
9285             }
9286             if (pos >= end) {
9287                 error(ts.Diagnostics.Unexpected_end_of_text);
9288                 isInvalidExtendedEscape = true;
9289             }
9290             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
9291                 // Only swallow the following character up if it's a '}'.
9292                 pos++;
9293             }
9294             else {
9295                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
9296                 isInvalidExtendedEscape = true;
9297             }
9298             if (isInvalidExtendedEscape) {
9299                 return "";
9300             }
9301             return utf16EncodeAsString(escapedValue);
9302         }
9303         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
9304         // and return code point value if valid Unicode escape is found. Otherwise return -1.
9305         function peekUnicodeEscape() {
9306             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
9307                 var start_1 = pos;
9308                 pos += 2;
9309                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
9310                 pos = start_1;
9311                 return value;
9312             }
9313             return -1;
9314         }
9315         function peekExtendedUnicodeEscape() {
9316             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
9317                 var start_2 = pos;
9318                 pos += 3;
9319                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9320                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9321                 pos = start_2;
9322                 return escapedValue;
9323             }
9324             return -1;
9325         }
9326         function scanIdentifierParts() {
9327             var result = "";
9328             var start = pos;
9329             while (pos < end) {
9330                 var ch = codePointAt(text, pos);
9331                 if (isIdentifierPart(ch, languageVersion)) {
9332                     pos += charSize(ch);
9333                 }
9334                 else if (ch === 92 /* backslash */) {
9335                     ch = peekExtendedUnicodeEscape();
9336                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
9337                         pos += 3;
9338                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9339                         result += scanExtendedUnicodeEscape();
9340                         start = pos;
9341                         continue;
9342                     }
9343                     ch = peekUnicodeEscape();
9344                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
9345                         break;
9346                     }
9347                     tokenFlags |= 1024 /* UnicodeEscape */;
9348                     result += text.substring(start, pos);
9349                     result += utf16EncodeAsString(ch);
9350                     // Valid Unicode escape is always six characters
9351                     pos += 6;
9352                     start = pos;
9353                 }
9354                 else {
9355                     break;
9356                 }
9357             }
9358             result += text.substring(start, pos);
9359             return result;
9360         }
9361         function getIdentifierToken() {
9362             // Reserved words are between 2 and 11 characters long and start with a lowercase letter
9363             var len = tokenValue.length;
9364             if (len >= 2 && len <= 11) {
9365                 var ch = tokenValue.charCodeAt(0);
9366                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
9367                     var keyword = textToKeyword.get(tokenValue);
9368                     if (keyword !== undefined) {
9369                         return token = keyword;
9370                     }
9371                 }
9372             }
9373             return token = 75 /* Identifier */;
9374         }
9375         function scanBinaryOrOctalDigits(base) {
9376             var value = "";
9377             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
9378             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
9379             var separatorAllowed = false;
9380             var isPreviousTokenSeparator = false;
9381             while (true) {
9382                 var ch = text.charCodeAt(pos);
9383                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
9384                 if (ch === 95 /* _ */) {
9385                     tokenFlags |= 512 /* ContainsSeparator */;
9386                     if (separatorAllowed) {
9387                         separatorAllowed = false;
9388                         isPreviousTokenSeparator = true;
9389                     }
9390                     else if (isPreviousTokenSeparator) {
9391                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9392                     }
9393                     else {
9394                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9395                     }
9396                     pos++;
9397                     continue;
9398                 }
9399                 separatorAllowed = true;
9400                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
9401                     break;
9402                 }
9403                 value += text[pos];
9404                 pos++;
9405                 isPreviousTokenSeparator = false;
9406             }
9407             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9408                 // Literal ends with underscore - not allowed
9409                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9410             }
9411             return value;
9412         }
9413         function checkBigIntSuffix() {
9414             if (text.charCodeAt(pos) === 110 /* n */) {
9415                 tokenValue += "n";
9416                 // Use base 10 instead of base 2 or base 8 for shorter literals
9417                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
9418                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
9419                 }
9420                 pos++;
9421                 return 9 /* BigIntLiteral */;
9422             }
9423             else { // not a bigint, so can convert to number in simplified form
9424                 // Number() may not support 0b or 0o, so use parseInt() instead
9425                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
9426                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
9427                     : tokenFlags & 256 /* OctalSpecifier */
9428                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
9429                         : +tokenValue;
9430                 tokenValue = "" + numericValue;
9431                 return 8 /* NumericLiteral */;
9432             }
9433         }
9434         function scan() {
9435             var _a;
9436             startPos = pos;
9437             tokenFlags = 0 /* None */;
9438             var asteriskSeen = false;
9439             while (true) {
9440                 tokenPos = pos;
9441                 if (pos >= end) {
9442                     return token = 1 /* EndOfFileToken */;
9443                 }
9444                 var ch = codePointAt(text, pos);
9445                 // Special handling for shebang
9446                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
9447                     pos = scanShebangTrivia(text, pos);
9448                     if (skipTrivia) {
9449                         continue;
9450                     }
9451                     else {
9452                         return token = 6 /* ShebangTrivia */;
9453                     }
9454                 }
9455                 switch (ch) {
9456                     case 10 /* lineFeed */:
9457                     case 13 /* carriageReturn */:
9458                         tokenFlags |= 1 /* PrecedingLineBreak */;
9459                         if (skipTrivia) {
9460                             pos++;
9461                             continue;
9462                         }
9463                         else {
9464                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9465                                 // consume both CR and LF
9466                                 pos += 2;
9467                             }
9468                             else {
9469                                 pos++;
9470                             }
9471                             return token = 4 /* NewLineTrivia */;
9472                         }
9473                     case 9 /* tab */:
9474                     case 11 /* verticalTab */:
9475                     case 12 /* formFeed */:
9476                     case 32 /* space */:
9477                     case 160 /* nonBreakingSpace */:
9478                     case 5760 /* ogham */:
9479                     case 8192 /* enQuad */:
9480                     case 8193 /* emQuad */:
9481                     case 8194 /* enSpace */:
9482                     case 8195 /* emSpace */:
9483                     case 8196 /* threePerEmSpace */:
9484                     case 8197 /* fourPerEmSpace */:
9485                     case 8198 /* sixPerEmSpace */:
9486                     case 8199 /* figureSpace */:
9487                     case 8200 /* punctuationSpace */:
9488                     case 8201 /* thinSpace */:
9489                     case 8202 /* hairSpace */:
9490                     case 8203 /* zeroWidthSpace */:
9491                     case 8239 /* narrowNoBreakSpace */:
9492                     case 8287 /* mathematicalSpace */:
9493                     case 12288 /* ideographicSpace */:
9494                     case 65279 /* byteOrderMark */:
9495                         if (skipTrivia) {
9496                             pos++;
9497                             continue;
9498                         }
9499                         else {
9500                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
9501                                 pos++;
9502                             }
9503                             return token = 5 /* WhitespaceTrivia */;
9504                         }
9505                     case 33 /* exclamation */:
9506                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9507                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9508                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
9509                             }
9510                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
9511                         }
9512                         pos++;
9513                         return token = 53 /* ExclamationToken */;
9514                     case 34 /* doubleQuote */:
9515                     case 39 /* singleQuote */:
9516                         tokenValue = scanString();
9517                         return token = 10 /* StringLiteral */;
9518                     case 96 /* backtick */:
9519                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
9520                     case 37 /* percent */:
9521                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9522                             return pos += 2, token = 68 /* PercentEqualsToken */;
9523                         }
9524                         pos++;
9525                         return token = 44 /* PercentToken */;
9526                     case 38 /* ampersand */:
9527                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
9528                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
9529                         }
9530                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9531                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
9532                         }
9533                         pos++;
9534                         return token = 50 /* AmpersandToken */;
9535                     case 40 /* openParen */:
9536                         pos++;
9537                         return token = 20 /* OpenParenToken */;
9538                     case 41 /* closeParen */:
9539                         pos++;
9540                         return token = 21 /* CloseParenToken */;
9541                     case 42 /* asterisk */:
9542                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9543                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
9544                         }
9545                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9546                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9547                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
9548                             }
9549                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
9550                         }
9551                         pos++;
9552                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
9553                             // decoration at the start of a JSDoc comment line
9554                             asteriskSeen = true;
9555                             continue;
9556                         }
9557                         return token = 41 /* AsteriskToken */;
9558                     case 43 /* plus */:
9559                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
9560                             return pos += 2, token = 45 /* PlusPlusToken */;
9561                         }
9562                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9563                             return pos += 2, token = 63 /* PlusEqualsToken */;
9564                         }
9565                         pos++;
9566                         return token = 39 /* PlusToken */;
9567                     case 44 /* comma */:
9568                         pos++;
9569                         return token = 27 /* CommaToken */;
9570                     case 45 /* minus */:
9571                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
9572                             return pos += 2, token = 46 /* MinusMinusToken */;
9573                         }
9574                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9575                             return pos += 2, token = 64 /* MinusEqualsToken */;
9576                         }
9577                         pos++;
9578                         return token = 40 /* MinusToken */;
9579                     case 46 /* dot */:
9580                         if (isDigit(text.charCodeAt(pos + 1))) {
9581                             tokenValue = scanNumber().value;
9582                             return token = 8 /* NumericLiteral */;
9583                         }
9584                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
9585                             return pos += 3, token = 25 /* DotDotDotToken */;
9586                         }
9587                         pos++;
9588                         return token = 24 /* DotToken */;
9589                     case 47 /* slash */:
9590                         // Single-line comment
9591                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9592                             pos += 2;
9593                             while (pos < end) {
9594                                 if (isLineBreak(text.charCodeAt(pos))) {
9595                                     break;
9596                                 }
9597                                 pos++;
9598                             }
9599                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
9600                             if (skipTrivia) {
9601                                 continue;
9602                             }
9603                             else {
9604                                 return token = 2 /* SingleLineCommentTrivia */;
9605                             }
9606                         }
9607                         // Multi-line comment
9608                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9609                             pos += 2;
9610                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
9611                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
9612                             }
9613                             var commentClosed = false;
9614                             var lastLineStart = tokenPos;
9615                             while (pos < end) {
9616                                 var ch_1 = text.charCodeAt(pos);
9617                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9618                                     pos += 2;
9619                                     commentClosed = true;
9620                                     break;
9621                                 }
9622                                 pos++;
9623                                 if (isLineBreak(ch_1)) {
9624                                     lastLineStart = pos;
9625                                     tokenFlags |= 1 /* PrecedingLineBreak */;
9626                                 }
9627                             }
9628                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
9629                             if (!commentClosed) {
9630                                 error(ts.Diagnostics.Asterisk_Slash_expected);
9631                             }
9632                             if (skipTrivia) {
9633                                 continue;
9634                             }
9635                             else {
9636                                 if (!commentClosed) {
9637                                     tokenFlags |= 4 /* Unterminated */;
9638                                 }
9639                                 return token = 3 /* MultiLineCommentTrivia */;
9640                             }
9641                         }
9642                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9643                             return pos += 2, token = 67 /* SlashEqualsToken */;
9644                         }
9645                         pos++;
9646                         return token = 43 /* SlashToken */;
9647                     case 48 /* _0 */:
9648                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
9649                             pos += 2;
9650                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
9651                             if (!tokenValue) {
9652                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9653                                 tokenValue = "0";
9654                             }
9655                             tokenValue = "0x" + tokenValue;
9656                             tokenFlags |= 64 /* HexSpecifier */;
9657                             return token = checkBigIntSuffix();
9658                         }
9659                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
9660                             pos += 2;
9661                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
9662                             if (!tokenValue) {
9663                                 error(ts.Diagnostics.Binary_digit_expected);
9664                                 tokenValue = "0";
9665                             }
9666                             tokenValue = "0b" + tokenValue;
9667                             tokenFlags |= 128 /* BinarySpecifier */;
9668                             return token = checkBigIntSuffix();
9669                         }
9670                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
9671                             pos += 2;
9672                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
9673                             if (!tokenValue) {
9674                                 error(ts.Diagnostics.Octal_digit_expected);
9675                                 tokenValue = "0";
9676                             }
9677                             tokenValue = "0o" + tokenValue;
9678                             tokenFlags |= 256 /* OctalSpecifier */;
9679                             return token = checkBigIntSuffix();
9680                         }
9681                         // Try to parse as an octal
9682                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
9683                             tokenValue = "" + scanOctalDigits();
9684                             tokenFlags |= 32 /* Octal */;
9685                             return token = 8 /* NumericLiteral */;
9686                         }
9687                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
9688                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
9689                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
9690                     // falls through
9691                     case 49 /* _1 */:
9692                     case 50 /* _2 */:
9693                     case 51 /* _3 */:
9694                     case 52 /* _4 */:
9695                     case 53 /* _5 */:
9696                     case 54 /* _6 */:
9697                     case 55 /* _7 */:
9698                     case 56 /* _8 */:
9699                     case 57 /* _9 */:
9700                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
9701                         return token;
9702                     case 58 /* colon */:
9703                         pos++;
9704                         return token = 58 /* ColonToken */;
9705                     case 59 /* semicolon */:
9706                         pos++;
9707                         return token = 26 /* SemicolonToken */;
9708                     case 60 /* lessThan */:
9709                         if (isConflictMarkerTrivia(text, pos)) {
9710                             pos = scanConflictMarkerTrivia(text, pos, error);
9711                             if (skipTrivia) {
9712                                 continue;
9713                             }
9714                             else {
9715                                 return token = 7 /* ConflictMarkerTrivia */;
9716                             }
9717                         }
9718                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
9719                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9720                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
9721                             }
9722                             return pos += 2, token = 47 /* LessThanLessThanToken */;
9723                         }
9724                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9725                             return pos += 2, token = 32 /* LessThanEqualsToken */;
9726                         }
9727                         if (languageVariant === 1 /* JSX */ &&
9728                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
9729                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
9730                             return pos += 2, token = 30 /* LessThanSlashToken */;
9731                         }
9732                         pos++;
9733                         return token = 29 /* LessThanToken */;
9734                     case 61 /* equals */:
9735                         if (isConflictMarkerTrivia(text, pos)) {
9736                             pos = scanConflictMarkerTrivia(text, pos, error);
9737                             if (skipTrivia) {
9738                                 continue;
9739                             }
9740                             else {
9741                                 return token = 7 /* ConflictMarkerTrivia */;
9742                             }
9743                         }
9744                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9745                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9746                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
9747                             }
9748                             return pos += 2, token = 34 /* EqualsEqualsToken */;
9749                         }
9750                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9751                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
9752                         }
9753                         pos++;
9754                         return token = 62 /* EqualsToken */;
9755                     case 62 /* greaterThan */:
9756                         if (isConflictMarkerTrivia(text, pos)) {
9757                             pos = scanConflictMarkerTrivia(text, pos, error);
9758                             if (skipTrivia) {
9759                                 continue;
9760                             }
9761                             else {
9762                                 return token = 7 /* ConflictMarkerTrivia */;
9763                             }
9764                         }
9765                         pos++;
9766                         return token = 31 /* GreaterThanToken */;
9767                     case 63 /* question */:
9768                         pos++;
9769                         if (text.charCodeAt(pos) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 1))) {
9770                             pos++;
9771                             return token = 28 /* QuestionDotToken */;
9772                         }
9773                         if (text.charCodeAt(pos) === 63 /* question */) {
9774                             pos++;
9775                             return token = 60 /* QuestionQuestionToken */;
9776                         }
9777                         return token = 57 /* QuestionToken */;
9778                     case 91 /* openBracket */:
9779                         pos++;
9780                         return token = 22 /* OpenBracketToken */;
9781                     case 93 /* closeBracket */:
9782                         pos++;
9783                         return token = 23 /* CloseBracketToken */;
9784                     case 94 /* caret */:
9785                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9786                             return pos += 2, token = 74 /* CaretEqualsToken */;
9787                         }
9788                         pos++;
9789                         return token = 52 /* CaretToken */;
9790                     case 123 /* openBrace */:
9791                         pos++;
9792                         return token = 18 /* OpenBraceToken */;
9793                     case 124 /* bar */:
9794                         if (isConflictMarkerTrivia(text, pos)) {
9795                             pos = scanConflictMarkerTrivia(text, pos, error);
9796                             if (skipTrivia) {
9797                                 continue;
9798                             }
9799                             else {
9800                                 return token = 7 /* ConflictMarkerTrivia */;
9801                             }
9802                         }
9803                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
9804                             return pos += 2, token = 56 /* BarBarToken */;
9805                         }
9806                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9807                             return pos += 2, token = 73 /* BarEqualsToken */;
9808                         }
9809                         pos++;
9810                         return token = 51 /* BarToken */;
9811                     case 125 /* closeBrace */:
9812                         pos++;
9813                         return token = 19 /* CloseBraceToken */;
9814                     case 126 /* tilde */:
9815                         pos++;
9816                         return token = 54 /* TildeToken */;
9817                     case 64 /* at */:
9818                         pos++;
9819                         return token = 59 /* AtToken */;
9820                     case 92 /* backslash */:
9821                         var extendedCookedChar = peekExtendedUnicodeEscape();
9822                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
9823                             pos += 3;
9824                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9825                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
9826                             return token = getIdentifierToken();
9827                         }
9828                         var cookedChar = peekUnicodeEscape();
9829                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
9830                             pos += 6;
9831                             tokenFlags |= 1024 /* UnicodeEscape */;
9832                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
9833                             return token = getIdentifierToken();
9834                         }
9835                         error(ts.Diagnostics.Invalid_character);
9836                         pos++;
9837                         return token = 0 /* Unknown */;
9838                     case 35 /* hash */:
9839                         if (pos !== 0 && text[pos + 1] === "!") {
9840                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
9841                             pos++;
9842                             return token = 0 /* Unknown */;
9843                         }
9844                         pos++;
9845                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
9846                             pos++;
9847                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
9848                                 pos++;
9849                             tokenValue = text.substring(tokenPos, pos);
9850                             if (ch === 92 /* backslash */) {
9851                                 tokenValue += scanIdentifierParts();
9852                             }
9853                         }
9854                         else {
9855                             tokenValue = "#";
9856                             error(ts.Diagnostics.Invalid_character);
9857                         }
9858                         return token = 76 /* PrivateIdentifier */;
9859                     default:
9860                         if (isIdentifierStart(ch, languageVersion)) {
9861                             pos += charSize(ch);
9862                             while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
9863                                 pos += charSize(ch);
9864                             tokenValue = text.substring(tokenPos, pos);
9865                             if (ch === 92 /* backslash */) {
9866                                 tokenValue += scanIdentifierParts();
9867                             }
9868                             return token = getIdentifierToken();
9869                         }
9870                         else if (isWhiteSpaceSingleLine(ch)) {
9871                             pos += charSize(ch);
9872                             continue;
9873                         }
9874                         else if (isLineBreak(ch)) {
9875                             tokenFlags |= 1 /* PrecedingLineBreak */;
9876                             pos += charSize(ch);
9877                             continue;
9878                         }
9879                         error(ts.Diagnostics.Invalid_character);
9880                         pos += charSize(ch);
9881                         return token = 0 /* Unknown */;
9882                 }
9883             }
9884         }
9885         function reScanGreaterToken() {
9886             if (token === 31 /* GreaterThanToken */) {
9887                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
9888                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9889                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9890                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
9891                         }
9892                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
9893                     }
9894                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9895                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
9896                     }
9897                     pos++;
9898                     return token = 48 /* GreaterThanGreaterThanToken */;
9899                 }
9900                 if (text.charCodeAt(pos) === 61 /* equals */) {
9901                     pos++;
9902                     return token = 33 /* GreaterThanEqualsToken */;
9903                 }
9904             }
9905             return token;
9906         }
9907         function reScanSlashToken() {
9908             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
9909                 var p = tokenPos + 1;
9910                 var inEscape = false;
9911                 var inCharacterClass = false;
9912                 while (true) {
9913                     // If we reach the end of a file, or hit a newline, then this is an unterminated
9914                     // regex.  Report error and return what we have so far.
9915                     if (p >= end) {
9916                         tokenFlags |= 4 /* Unterminated */;
9917                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9918                         break;
9919                     }
9920                     var ch = text.charCodeAt(p);
9921                     if (isLineBreak(ch)) {
9922                         tokenFlags |= 4 /* Unterminated */;
9923                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9924                         break;
9925                     }
9926                     if (inEscape) {
9927                         // Parsing an escape character;
9928                         // reset the flag and just advance to the next char.
9929                         inEscape = false;
9930                     }
9931                     else if (ch === 47 /* slash */ && !inCharacterClass) {
9932                         // A slash within a character class is permissible,
9933                         // but in general it signals the end of the regexp literal.
9934                         p++;
9935                         break;
9936                     }
9937                     else if (ch === 91 /* openBracket */) {
9938                         inCharacterClass = true;
9939                     }
9940                     else if (ch === 92 /* backslash */) {
9941                         inEscape = true;
9942                     }
9943                     else if (ch === 93 /* closeBracket */) {
9944                         inCharacterClass = false;
9945                     }
9946                     p++;
9947                 }
9948                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
9949                     p++;
9950                 }
9951                 pos = p;
9952                 tokenValue = text.substring(tokenPos, pos);
9953                 token = 13 /* RegularExpressionLiteral */;
9954             }
9955             return token;
9956         }
9957         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
9958             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
9959             if (type === undefined) {
9960                 return commentDirectives;
9961             }
9962             return ts.append(commentDirectives, {
9963                 range: { pos: lineStart, end: pos },
9964                 type: type,
9965             });
9966         }
9967         function getDirectiveFromComment(text, commentDirectiveRegEx) {
9968             var match = commentDirectiveRegEx.exec(text);
9969             if (!match) {
9970                 return undefined;
9971             }
9972             switch (match[1]) {
9973                 case "ts-expect-error":
9974                     return 0 /* ExpectError */;
9975                 case "ts-ignore":
9976                     return 1 /* Ignore */;
9977             }
9978             return undefined;
9979         }
9980         /**
9981          * Unconditionally back up and scan a template expression portion.
9982          */
9983         function reScanTemplateToken(isTaggedTemplate) {
9984             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
9985             pos = tokenPos;
9986             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
9987         }
9988         function reScanTemplateHeadOrNoSubstitutionTemplate() {
9989             pos = tokenPos;
9990             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
9991         }
9992         function reScanJsxToken() {
9993             pos = tokenPos = startPos;
9994             return token = scanJsxToken();
9995         }
9996         function reScanLessThanToken() {
9997             if (token === 47 /* LessThanLessThanToken */) {
9998                 pos = tokenPos + 1;
9999                 return token = 29 /* LessThanToken */;
10000             }
10001             return token;
10002         }
10003         function reScanQuestionToken() {
10004             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
10005             pos = tokenPos + 1;
10006             return token = 57 /* QuestionToken */;
10007         }
10008         function scanJsxToken() {
10009             startPos = tokenPos = pos;
10010             if (pos >= end) {
10011                 return token = 1 /* EndOfFileToken */;
10012             }
10013             var char = text.charCodeAt(pos);
10014             if (char === 60 /* lessThan */) {
10015                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10016                     pos += 2;
10017                     return token = 30 /* LessThanSlashToken */;
10018                 }
10019                 pos++;
10020                 return token = 29 /* LessThanToken */;
10021             }
10022             if (char === 123 /* openBrace */) {
10023                 pos++;
10024                 return token = 18 /* OpenBraceToken */;
10025             }
10026             // First non-whitespace character on this line.
10027             var firstNonWhitespace = 0;
10028             var lastNonWhitespace = -1;
10029             // These initial values are special because the first line is:
10030             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10031             while (pos < end) {
10032                 // We want to keep track of the last non-whitespace (but including
10033                 // newlines character for hitting the end of the JSX Text region)
10034                 if (!isWhiteSpaceSingleLine(char)) {
10035                     lastNonWhitespace = pos;
10036                 }
10037                 char = text.charCodeAt(pos);
10038                 if (char === 123 /* openBrace */) {
10039                     break;
10040                 }
10041                 if (char === 60 /* lessThan */) {
10042                     if (isConflictMarkerTrivia(text, pos)) {
10043                         pos = scanConflictMarkerTrivia(text, pos, error);
10044                         return token = 7 /* ConflictMarkerTrivia */;
10045                     }
10046                     break;
10047                 }
10048                 if (char === 62 /* greaterThan */) {
10049                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10050                 }
10051                 if (char === 125 /* closeBrace */) {
10052                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10053                 }
10054                 if (lastNonWhitespace > 0)
10055                     lastNonWhitespace++;
10056                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10057                 // i.e (- : whitespace)
10058                 //      <div>----
10059                 //      </div> becomes <div></div>
10060                 //
10061                 //      <div>----</div> becomes <div>----</div>
10062                 if (isLineBreak(char) && firstNonWhitespace === 0) {
10063                     firstNonWhitespace = -1;
10064                 }
10065                 else if (!isWhiteSpaceLike(char)) {
10066                     firstNonWhitespace = pos;
10067                 }
10068                 pos++;
10069             }
10070             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10071             tokenValue = text.substring(startPos, endPosition);
10072             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10073         }
10074         // Scans a JSX identifier; these differ from normal identifiers in that
10075         // they allow dashes
10076         function scanJsxIdentifier() {
10077             if (tokenIsIdentifierOrKeyword(token)) {
10078                 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
10079                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
10080                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
10081                 while (pos < end) {
10082                     var ch = text.charCodeAt(pos);
10083                     if (ch === 45 /* minus */) {
10084                         tokenValue += "-";
10085                         pos++;
10086                         continue;
10087                     }
10088                     var oldPos = pos;
10089                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
10090                     if (pos === oldPos) {
10091                         break;
10092                     }
10093                 }
10094             }
10095             return token;
10096         }
10097         function scanJsxAttributeValue() {
10098             startPos = pos;
10099             switch (text.charCodeAt(pos)) {
10100                 case 34 /* doubleQuote */:
10101                 case 39 /* singleQuote */:
10102                     tokenValue = scanString(/*jsxAttributeString*/ true);
10103                     return token = 10 /* StringLiteral */;
10104                 default:
10105                     // If this scans anything other than `{`, it's a parse error.
10106                     return scan();
10107             }
10108         }
10109         function reScanJsxAttributeValue() {
10110             pos = tokenPos = startPos;
10111             return scanJsxAttributeValue();
10112         }
10113         function scanJsDocToken() {
10114             startPos = tokenPos = pos;
10115             tokenFlags = 0 /* None */;
10116             if (pos >= end) {
10117                 return token = 1 /* EndOfFileToken */;
10118             }
10119             var ch = codePointAt(text, pos);
10120             pos += charSize(ch);
10121             switch (ch) {
10122                 case 9 /* tab */:
10123                 case 11 /* verticalTab */:
10124                 case 12 /* formFeed */:
10125                 case 32 /* space */:
10126                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10127                         pos++;
10128                     }
10129                     return token = 5 /* WhitespaceTrivia */;
10130                 case 64 /* at */:
10131                     return token = 59 /* AtToken */;
10132                 case 10 /* lineFeed */:
10133                 case 13 /* carriageReturn */:
10134                     tokenFlags |= 1 /* PrecedingLineBreak */;
10135                     return token = 4 /* NewLineTrivia */;
10136                 case 42 /* asterisk */:
10137                     return token = 41 /* AsteriskToken */;
10138                 case 123 /* openBrace */:
10139                     return token = 18 /* OpenBraceToken */;
10140                 case 125 /* closeBrace */:
10141                     return token = 19 /* CloseBraceToken */;
10142                 case 91 /* openBracket */:
10143                     return token = 22 /* OpenBracketToken */;
10144                 case 93 /* closeBracket */:
10145                     return token = 23 /* CloseBracketToken */;
10146                 case 60 /* lessThan */:
10147                     return token = 29 /* LessThanToken */;
10148                 case 62 /* greaterThan */:
10149                     return token = 31 /* GreaterThanToken */;
10150                 case 61 /* equals */:
10151                     return token = 62 /* EqualsToken */;
10152                 case 44 /* comma */:
10153                     return token = 27 /* CommaToken */;
10154                 case 46 /* dot */:
10155                     return token = 24 /* DotToken */;
10156                 case 96 /* backtick */:
10157                     return token = 61 /* BacktickToken */;
10158                 case 92 /* backslash */:
10159                     pos--;
10160                     var extendedCookedChar = peekExtendedUnicodeEscape();
10161                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10162                         pos += 3;
10163                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10164                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10165                         return token = getIdentifierToken();
10166                     }
10167                     var cookedChar = peekUnicodeEscape();
10168                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10169                         pos += 6;
10170                         tokenFlags |= 1024 /* UnicodeEscape */;
10171                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10172                         return token = getIdentifierToken();
10173                     }
10174                     pos++;
10175                     return token = 0 /* Unknown */;
10176             }
10177             if (isIdentifierStart(ch, languageVersion)) {
10178                 var char = ch;
10179                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
10180                     pos += charSize(char);
10181                 tokenValue = text.substring(tokenPos, pos);
10182                 if (char === 92 /* backslash */) {
10183                     tokenValue += scanIdentifierParts();
10184                 }
10185                 return token = getIdentifierToken();
10186             }
10187             else {
10188                 return token = 0 /* Unknown */;
10189             }
10190         }
10191         function speculationHelper(callback, isLookahead) {
10192             var savePos = pos;
10193             var saveStartPos = startPos;
10194             var saveTokenPos = tokenPos;
10195             var saveToken = token;
10196             var saveTokenValue = tokenValue;
10197             var saveTokenFlags = tokenFlags;
10198             var result = callback();
10199             // If our callback returned something 'falsy' or we're just looking ahead,
10200             // then unconditionally restore us to where we were.
10201             if (!result || isLookahead) {
10202                 pos = savePos;
10203                 startPos = saveStartPos;
10204                 tokenPos = saveTokenPos;
10205                 token = saveToken;
10206                 tokenValue = saveTokenValue;
10207                 tokenFlags = saveTokenFlags;
10208             }
10209             return result;
10210         }
10211         function scanRange(start, length, callback) {
10212             var saveEnd = end;
10213             var savePos = pos;
10214             var saveStartPos = startPos;
10215             var saveTokenPos = tokenPos;
10216             var saveToken = token;
10217             var saveTokenValue = tokenValue;
10218             var saveTokenFlags = tokenFlags;
10219             var saveErrorExpectations = commentDirectives;
10220             setText(text, start, length);
10221             var result = callback();
10222             end = saveEnd;
10223             pos = savePos;
10224             startPos = saveStartPos;
10225             tokenPos = saveTokenPos;
10226             token = saveToken;
10227             tokenValue = saveTokenValue;
10228             tokenFlags = saveTokenFlags;
10229             commentDirectives = saveErrorExpectations;
10230             return result;
10231         }
10232         function lookAhead(callback) {
10233             return speculationHelper(callback, /*isLookahead*/ true);
10234         }
10235         function tryScan(callback) {
10236             return speculationHelper(callback, /*isLookahead*/ false);
10237         }
10238         function getText() {
10239             return text;
10240         }
10241         function clearCommentDirectives() {
10242             commentDirectives = undefined;
10243         }
10244         function setText(newText, start, length) {
10245             text = newText || "";
10246             end = length === undefined ? text.length : start + length;
10247             setTextPos(start || 0);
10248         }
10249         function setOnError(errorCallback) {
10250             onError = errorCallback;
10251         }
10252         function setScriptTarget(scriptTarget) {
10253             languageVersion = scriptTarget;
10254         }
10255         function setLanguageVariant(variant) {
10256             languageVariant = variant;
10257         }
10258         function setTextPos(textPos) {
10259             ts.Debug.assert(textPos >= 0);
10260             pos = textPos;
10261             startPos = textPos;
10262             tokenPos = textPos;
10263             token = 0 /* Unknown */;
10264             tokenValue = undefined;
10265             tokenFlags = 0 /* None */;
10266         }
10267         function setInJSDocType(inType) {
10268             inJSDocType += inType ? 1 : -1;
10269         }
10270     }
10271     ts.createScanner = createScanner;
10272     /* @internal */
10273     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
10274         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
10275         var size = str.length;
10276         // Account for out-of-bounds indices:
10277         if (i < 0 || i >= size) {
10278             return undefined; // String.codePointAt returns `undefined` for OOB indexes
10279         }
10280         // Get the first code unit
10281         var first = str.charCodeAt(i);
10282         // check if it’s the start of a surrogate pair
10283         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
10284             var second = str.charCodeAt(i + 1);
10285             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
10286                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
10287                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
10288             }
10289         }
10290         return first;
10291     };
10292     /* @internal */
10293     function charSize(ch) {
10294         if (ch >= 0x10000) {
10295             return 2;
10296         }
10297         return 1;
10298     }
10299     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
10300     function utf16EncodeAsStringFallback(codePoint) {
10301         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
10302         if (codePoint <= 65535) {
10303             return String.fromCharCode(codePoint);
10304         }
10305         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
10306         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
10307         return String.fromCharCode(codeUnit1, codeUnit2);
10308     }
10309     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
10310     /* @internal */
10311     function utf16EncodeAsString(codePoint) {
10312         return utf16EncodeAsStringWorker(codePoint);
10313     }
10314     ts.utf16EncodeAsString = utf16EncodeAsString;
10315 })(ts || (ts = {}));
10316 var ts;
10317 (function (ts) {
10318     function isExternalModuleNameRelative(moduleName) {
10319         // TypeScript 1.0 spec (April 2014): 11.2.1
10320         // An external module name is "relative" if the first term is "." or "..".
10321         // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module.
10322         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
10323     }
10324     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
10325     function sortAndDeduplicateDiagnostics(diagnostics) {
10326         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
10327     }
10328     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
10329     function getDefaultLibFileName(options) {
10330         switch (options.target) {
10331             case 99 /* ESNext */:
10332                 return "lib.esnext.full.d.ts";
10333             case 7 /* ES2020 */:
10334                 return "lib.es2020.full.d.ts";
10335             case 6 /* ES2019 */:
10336                 return "lib.es2019.full.d.ts";
10337             case 5 /* ES2018 */:
10338                 return "lib.es2018.full.d.ts";
10339             case 4 /* ES2017 */:
10340                 return "lib.es2017.full.d.ts";
10341             case 3 /* ES2016 */:
10342                 return "lib.es2016.full.d.ts";
10343             case 2 /* ES2015 */:
10344                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
10345             default:
10346                 return "lib.d.ts";
10347         }
10348     }
10349     ts.getDefaultLibFileName = getDefaultLibFileName;
10350     function textSpanEnd(span) {
10351         return span.start + span.length;
10352     }
10353     ts.textSpanEnd = textSpanEnd;
10354     function textSpanIsEmpty(span) {
10355         return span.length === 0;
10356     }
10357     ts.textSpanIsEmpty = textSpanIsEmpty;
10358     function textSpanContainsPosition(span, position) {
10359         return position >= span.start && position < textSpanEnd(span);
10360     }
10361     ts.textSpanContainsPosition = textSpanContainsPosition;
10362     /* @internal */
10363     function textRangeContainsPositionInclusive(span, position) {
10364         return position >= span.pos && position <= span.end;
10365     }
10366     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
10367     // Returns true if 'span' contains 'other'.
10368     function textSpanContainsTextSpan(span, other) {
10369         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
10370     }
10371     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
10372     function textSpanOverlapsWith(span, other) {
10373         return textSpanOverlap(span, other) !== undefined;
10374     }
10375     ts.textSpanOverlapsWith = textSpanOverlapsWith;
10376     function textSpanOverlap(span1, span2) {
10377         var overlap = textSpanIntersection(span1, span2);
10378         return overlap && overlap.length === 0 ? undefined : overlap;
10379     }
10380     ts.textSpanOverlap = textSpanOverlap;
10381     function textSpanIntersectsWithTextSpan(span, other) {
10382         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
10383     }
10384     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
10385     function textSpanIntersectsWith(span, start, length) {
10386         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
10387     }
10388     ts.textSpanIntersectsWith = textSpanIntersectsWith;
10389     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
10390         var end1 = start1 + length1;
10391         var end2 = start2 + length2;
10392         return start2 <= end1 && end2 >= start1;
10393     }
10394     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
10395     function textSpanIntersectsWithPosition(span, position) {
10396         return position <= textSpanEnd(span) && position >= span.start;
10397     }
10398     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
10399     function textSpanIntersection(span1, span2) {
10400         var start = Math.max(span1.start, span2.start);
10401         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
10402         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
10403     }
10404     ts.textSpanIntersection = textSpanIntersection;
10405     function createTextSpan(start, length) {
10406         if (start < 0) {
10407             throw new Error("start < 0");
10408         }
10409         if (length < 0) {
10410             throw new Error("length < 0");
10411         }
10412         return { start: start, length: length };
10413     }
10414     ts.createTextSpan = createTextSpan;
10415     function createTextSpanFromBounds(start, end) {
10416         return createTextSpan(start, end - start);
10417     }
10418     ts.createTextSpanFromBounds = createTextSpanFromBounds;
10419     function textChangeRangeNewSpan(range) {
10420         return createTextSpan(range.span.start, range.newLength);
10421     }
10422     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
10423     function textChangeRangeIsUnchanged(range) {
10424         return textSpanIsEmpty(range.span) && range.newLength === 0;
10425     }
10426     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
10427     function createTextChangeRange(span, newLength) {
10428         if (newLength < 0) {
10429             throw new Error("newLength < 0");
10430         }
10431         return { span: span, newLength: newLength };
10432     }
10433     ts.createTextChangeRange = createTextChangeRange;
10434     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
10435     /**
10436      * Called to merge all the changes that occurred across several versions of a script snapshot
10437      * into a single change.  i.e. if a user keeps making successive edits to a script we will
10438      * have a text change from V1 to V2, V2 to V3, ..., Vn.
10439      *
10440      * This function will then merge those changes into a single change range valid between V1 and
10441      * Vn.
10442      */
10443     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
10444         if (changes.length === 0) {
10445             return ts.unchangedTextChangeRange;
10446         }
10447         if (changes.length === 1) {
10448             return changes[0];
10449         }
10450         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
10451         // as it makes things much easier to reason about.
10452         var change0 = changes[0];
10453         var oldStartN = change0.span.start;
10454         var oldEndN = textSpanEnd(change0.span);
10455         var newEndN = oldStartN + change0.newLength;
10456         for (var i = 1; i < changes.length; i++) {
10457             var nextChange = changes[i];
10458             // Consider the following case:
10459             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
10460             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
10461             // i.e. the span starting at 30 with length 30 is increased to length 40.
10462             //
10463             //      0         10        20        30        40        50        60        70        80        90        100
10464             //      -------------------------------------------------------------------------------------------------------
10465             //                |                                                 /
10466             //                |                                            /----
10467             //  T1            |                                       /----
10468             //                |                                  /----
10469             //                |                             /----
10470             //      -------------------------------------------------------------------------------------------------------
10471             //                                     |                            \
10472             //                                     |                               \
10473             //   T2                                |                                 \
10474             //                                     |                                   \
10475             //                                     |                                      \
10476             //      -------------------------------------------------------------------------------------------------------
10477             //
10478             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
10479             // it's just the min of the old and new starts.  i.e.:
10480             //
10481             //      0         10        20        30        40        50        60        70        80        90        100
10482             //      ------------------------------------------------------------*------------------------------------------
10483             //                |                                                 /
10484             //                |                                            /----
10485             //  T1            |                                       /----
10486             //                |                                  /----
10487             //                |                             /----
10488             //      ----------------------------------------$-------------------$------------------------------------------
10489             //                .                    |                            \
10490             //                .                    |                               \
10491             //   T2           .                    |                                 \
10492             //                .                    |                                   \
10493             //                .                    |                                      \
10494             //      ----------------------------------------------------------------------*--------------------------------
10495             //
10496             // (Note the dots represent the newly inferred start.
10497             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
10498             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
10499             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
10500             // means:
10501             //
10502             //      0         10        20        30        40        50        60        70        80        90        100
10503             //      --------------------------------------------------------------------------------*----------------------
10504             //                |                                                                     /
10505             //                |                                                                /----
10506             //  T1            |                                                           /----
10507             //                |                                                      /----
10508             //                |                                                 /----
10509             //      ------------------------------------------------------------$------------------------------------------
10510             //                .                    |                            \
10511             //                .                    |                               \
10512             //   T2           .                    |                                 \
10513             //                .                    |                                   \
10514             //                .                    |                                      \
10515             //      ----------------------------------------------------------------------*--------------------------------
10516             //
10517             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
10518             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
10519             // that's the same as if we started at char 80 instead of 60.
10520             //
10521             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
10522             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
10523             // first.
10524             //
10525             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
10526             // semantics: { { start: 10, length: 70 }, newLength: 60 }
10527             //
10528             // The math then works out as follows.
10529             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
10530             // final result like so:
10531             //
10532             // {
10533             //      oldStart3: Min(oldStart1, oldStart2),
10534             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
10535             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
10536             // }
10537             var oldStart1 = oldStartN;
10538             var oldEnd1 = oldEndN;
10539             var newEnd1 = newEndN;
10540             var oldStart2 = nextChange.span.start;
10541             var oldEnd2 = textSpanEnd(nextChange.span);
10542             var newEnd2 = oldStart2 + nextChange.newLength;
10543             oldStartN = Math.min(oldStart1, oldStart2);
10544             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
10545             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
10546         }
10547         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
10548     }
10549     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
10550     function getTypeParameterOwner(d) {
10551         if (d && d.kind === 155 /* TypeParameter */) {
10552             for (var current = d; current; current = current.parent) {
10553                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 246 /* InterfaceDeclaration */) {
10554                     return current;
10555                 }
10556             }
10557         }
10558     }
10559     ts.getTypeParameterOwner = getTypeParameterOwner;
10560     function isParameterPropertyDeclaration(node, parent) {
10561         return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 162 /* Constructor */;
10562     }
10563     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
10564     function isEmptyBindingPattern(node) {
10565         if (isBindingPattern(node)) {
10566             return ts.every(node.elements, isEmptyBindingElement);
10567         }
10568         return false;
10569     }
10570     ts.isEmptyBindingPattern = isEmptyBindingPattern;
10571     function isEmptyBindingElement(node) {
10572         if (isOmittedExpression(node)) {
10573             return true;
10574         }
10575         return isEmptyBindingPattern(node.name);
10576     }
10577     ts.isEmptyBindingElement = isEmptyBindingElement;
10578     function walkUpBindingElementsAndPatterns(binding) {
10579         var node = binding.parent;
10580         while (isBindingElement(node.parent)) {
10581             node = node.parent.parent;
10582         }
10583         return node.parent;
10584     }
10585     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
10586     function getCombinedFlags(node, getFlags) {
10587         if (isBindingElement(node)) {
10588             node = walkUpBindingElementsAndPatterns(node);
10589         }
10590         var flags = getFlags(node);
10591         if (node.kind === 242 /* VariableDeclaration */) {
10592             node = node.parent;
10593         }
10594         if (node && node.kind === 243 /* VariableDeclarationList */) {
10595             flags |= getFlags(node);
10596             node = node.parent;
10597         }
10598         if (node && node.kind === 225 /* VariableStatement */) {
10599             flags |= getFlags(node);
10600         }
10601         return flags;
10602     }
10603     function getCombinedModifierFlags(node) {
10604         return getCombinedFlags(node, ts.getModifierFlags);
10605     }
10606     ts.getCombinedModifierFlags = getCombinedModifierFlags;
10607     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
10608     // nodes like variable declarations and binding elements can returned a view of their flags
10609     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
10610     // stored on the variable declaration directly, but on the containing variable statement
10611     // (if it has one).  Similarly, flags for let/const are store on the variable declaration
10612     // list.  By calling this function, all those flags are combined so that the client can treat
10613     // the node as if it actually had those flags.
10614     function getCombinedNodeFlags(node) {
10615         return getCombinedFlags(node, function (n) { return n.flags; });
10616     }
10617     ts.getCombinedNodeFlags = getCombinedNodeFlags;
10618     /**
10619      * Checks to see if the locale is in the appropriate format,
10620      * and if it is, attempts to set the appropriate language.
10621      */
10622     function validateLocaleAndSetLanguage(locale, sys, errors) {
10623         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
10624         if (!matchResult) {
10625             if (errors) {
10626                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
10627             }
10628             return;
10629         }
10630         var language = matchResult[1];
10631         var territory = matchResult[3];
10632         // First try the entire locale, then fall back to just language if that's all we have.
10633         // Either ways do not fail, and fallback to the English diagnostic strings.
10634         if (!trySetLanguageAndTerritory(language, territory, errors)) {
10635             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
10636         }
10637         // Set the UI locale for string collation
10638         ts.setUILocale(locale);
10639         function trySetLanguageAndTerritory(language, territory, errors) {
10640             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
10641             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
10642             var filePath = ts.combinePaths(containingDirectoryPath, language);
10643             if (territory) {
10644                 filePath = filePath + "-" + territory;
10645             }
10646             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
10647             if (!sys.fileExists(filePath)) {
10648                 return false;
10649             }
10650             // TODO: Add codePage support for readFile?
10651             var fileContents = "";
10652             try {
10653                 fileContents = sys.readFile(filePath);
10654             }
10655             catch (e) {
10656                 if (errors) {
10657                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
10658                 }
10659                 return false;
10660             }
10661             try {
10662                 // this is a global mutation (or live binding update)!
10663                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
10664             }
10665             catch (_a) {
10666                 if (errors) {
10667                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
10668                 }
10669                 return false;
10670             }
10671             return true;
10672         }
10673     }
10674     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
10675     function getOriginalNode(node, nodeTest) {
10676         if (node) {
10677             while (node.original !== undefined) {
10678                 node = node.original;
10679             }
10680         }
10681         return !nodeTest || nodeTest(node) ? node : undefined;
10682     }
10683     ts.getOriginalNode = getOriginalNode;
10684     /**
10685      * Gets a value indicating whether a node originated in the parse tree.
10686      *
10687      * @param node The node to test.
10688      */
10689     function isParseTreeNode(node) {
10690         return (node.flags & 8 /* Synthesized */) === 0;
10691     }
10692     ts.isParseTreeNode = isParseTreeNode;
10693     function getParseTreeNode(node, nodeTest) {
10694         if (node === undefined || isParseTreeNode(node)) {
10695             return node;
10696         }
10697         node = getOriginalNode(node);
10698         if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
10699             return node;
10700         }
10701         return undefined;
10702     }
10703     ts.getParseTreeNode = getParseTreeNode;
10704     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
10705     function escapeLeadingUnderscores(identifier) {
10706         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
10707     }
10708     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
10709     /**
10710      * Remove extra underscore from escaped identifier text content.
10711      *
10712      * @param identifier The escaped identifier text.
10713      * @returns The unescaped identifier text.
10714      */
10715     function unescapeLeadingUnderscores(identifier) {
10716         var id = identifier;
10717         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
10718     }
10719     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
10720     function idText(identifierOrPrivateName) {
10721         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
10722     }
10723     ts.idText = idText;
10724     function symbolName(symbol) {
10725         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
10726             return idText(symbol.valueDeclaration.name);
10727         }
10728         return unescapeLeadingUnderscores(symbol.escapedName);
10729     }
10730     ts.symbolName = symbolName;
10731     /**
10732      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
10733      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
10734      * will be merged with)
10735      */
10736     function nameForNamelessJSDocTypedef(declaration) {
10737         var hostNode = declaration.parent.parent;
10738         if (!hostNode) {
10739             return undefined;
10740         }
10741         // Covers classes, functions - any named declaration host node
10742         if (isDeclaration(hostNode)) {
10743             return getDeclarationIdentifier(hostNode);
10744         }
10745         // Covers remaining cases (returning undefined if none match).
10746         switch (hostNode.kind) {
10747             case 225 /* VariableStatement */:
10748                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
10749                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
10750                 }
10751                 break;
10752             case 226 /* ExpressionStatement */:
10753                 var expr = hostNode.expression;
10754                 if (expr.kind === 209 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
10755                     expr = expr.left;
10756                 }
10757                 switch (expr.kind) {
10758                     case 194 /* PropertyAccessExpression */:
10759                         return expr.name;
10760                     case 195 /* ElementAccessExpression */:
10761                         var arg = expr.argumentExpression;
10762                         if (isIdentifier(arg)) {
10763                             return arg;
10764                         }
10765                 }
10766                 break;
10767             case 200 /* ParenthesizedExpression */: {
10768                 return getDeclarationIdentifier(hostNode.expression);
10769             }
10770             case 238 /* LabeledStatement */: {
10771                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
10772                     return getDeclarationIdentifier(hostNode.statement);
10773                 }
10774                 break;
10775             }
10776         }
10777     }
10778     function getDeclarationIdentifier(node) {
10779         var name = getNameOfDeclaration(node);
10780         return name && isIdentifier(name) ? name : undefined;
10781     }
10782     /** @internal */
10783     function nodeHasName(statement, name) {
10784         if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
10785             return true;
10786         }
10787         if (isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
10788             return true;
10789         }
10790         return false;
10791     }
10792     ts.nodeHasName = nodeHasName;
10793     function getNameOfJSDocTypedef(declaration) {
10794         return declaration.name || nameForNamelessJSDocTypedef(declaration);
10795     }
10796     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
10797     /** @internal */
10798     function isNamedDeclaration(node) {
10799         return !!node.name; // A 'name' property should always be a DeclarationName.
10800     }
10801     ts.isNamedDeclaration = isNamedDeclaration;
10802     /** @internal */
10803     function getNonAssignedNameOfDeclaration(declaration) {
10804         switch (declaration.kind) {
10805             case 75 /* Identifier */:
10806                 return declaration;
10807             case 323 /* JSDocPropertyTag */:
10808             case 317 /* JSDocParameterTag */: {
10809                 var name = declaration.name;
10810                 if (name.kind === 153 /* QualifiedName */) {
10811                     return name.right;
10812                 }
10813                 break;
10814             }
10815             case 196 /* CallExpression */:
10816             case 209 /* BinaryExpression */: {
10817                 var expr_1 = declaration;
10818                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
10819                     case 1 /* ExportsProperty */:
10820                     case 4 /* ThisProperty */:
10821                     case 5 /* Property */:
10822                     case 3 /* PrototypeProperty */:
10823                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
10824                     case 7 /* ObjectDefinePropertyValue */:
10825                     case 8 /* ObjectDefinePropertyExports */:
10826                     case 9 /* ObjectDefinePrototypeProperty */:
10827                         return expr_1.arguments[1];
10828                     default:
10829                         return undefined;
10830                 }
10831             }
10832             case 322 /* JSDocTypedefTag */:
10833                 return getNameOfJSDocTypedef(declaration);
10834             case 316 /* JSDocEnumTag */:
10835                 return nameForNamelessJSDocTypedef(declaration);
10836             case 259 /* ExportAssignment */: {
10837                 var expression = declaration.expression;
10838                 return isIdentifier(expression) ? expression : undefined;
10839             }
10840             case 195 /* ElementAccessExpression */:
10841                 var expr = declaration;
10842                 if (ts.isBindableStaticElementAccessExpression(expr)) {
10843                     return expr.argumentExpression;
10844                 }
10845         }
10846         return declaration.name;
10847     }
10848     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
10849     function getNameOfDeclaration(declaration) {
10850         if (declaration === undefined)
10851             return undefined;
10852         return getNonAssignedNameOfDeclaration(declaration) ||
10853             (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
10854     }
10855     ts.getNameOfDeclaration = getNameOfDeclaration;
10856     function getAssignedName(node) {
10857         if (!node.parent) {
10858             return undefined;
10859         }
10860         else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
10861             return node.parent.name;
10862         }
10863         else if (isBinaryExpression(node.parent) && node === node.parent.right) {
10864             if (isIdentifier(node.parent.left)) {
10865                 return node.parent.left;
10866             }
10867             else if (ts.isAccessExpression(node.parent.left)) {
10868                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
10869             }
10870         }
10871         else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
10872             return node.parent.name;
10873         }
10874     }
10875     /**
10876      * Gets the JSDoc parameter tags for the node if present.
10877      *
10878      * @remarks Returns any JSDoc param tag whose name matches the provided
10879      * parameter, whether a param tag on a containing function
10880      * expression, or a param tag on a variable declaration whose
10881      * initializer is the containing function. The tags closest to the
10882      * node are returned first, so in the previous example, the param
10883      * tag on the containing function expression would be first.
10884      *
10885      * For binding patterns, parameter tags are matched by position.
10886      */
10887     function getJSDocParameterTags(param) {
10888         if (param.name) {
10889             if (isIdentifier(param.name)) {
10890                 var name_1 = param.name.escapedText;
10891                 return getJSDocTags(param.parent).filter(function (tag) { return isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name_1; });
10892             }
10893             else {
10894                 var i = param.parent.parameters.indexOf(param);
10895                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
10896                 var paramTags = getJSDocTags(param.parent).filter(isJSDocParameterTag);
10897                 if (i < paramTags.length) {
10898                     return [paramTags[i]];
10899                 }
10900             }
10901         }
10902         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
10903         return ts.emptyArray;
10904     }
10905     ts.getJSDocParameterTags = getJSDocParameterTags;
10906     /**
10907      * Gets the JSDoc type parameter tags for the node if present.
10908      *
10909      * @remarks Returns any JSDoc template tag whose names match the provided
10910      * parameter, whether a template tag on a containing function
10911      * expression, or a template tag on a variable declaration whose
10912      * initializer is the containing function. The tags closest to the
10913      * node are returned first, so in the previous example, the template
10914      * tag on the containing function expression would be first.
10915      */
10916     function getJSDocTypeParameterTags(param) {
10917         var name = param.name.escapedText;
10918         return getJSDocTags(param.parent).filter(function (tag) {
10919             return isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
10920         });
10921     }
10922     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
10923     /**
10924      * Return true if the node has JSDoc parameter tags.
10925      *
10926      * @remarks Includes parameter tags that are not directly on the node,
10927      * for example on a variable declaration whose initializer is a function expression.
10928      */
10929     function hasJSDocParameterTags(node) {
10930         return !!getFirstJSDocTag(node, isJSDocParameterTag);
10931     }
10932     ts.hasJSDocParameterTags = hasJSDocParameterTags;
10933     /** Gets the JSDoc augments tag for the node if present */
10934     function getJSDocAugmentsTag(node) {
10935         return getFirstJSDocTag(node, isJSDocAugmentsTag);
10936     }
10937     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
10938     /** Gets the JSDoc implements tags for the node if present */
10939     function getJSDocImplementsTags(node) {
10940         return getAllJSDocTags(node, isJSDocImplementsTag);
10941     }
10942     ts.getJSDocImplementsTags = getJSDocImplementsTags;
10943     /** Gets the JSDoc class tag for the node if present */
10944     function getJSDocClassTag(node) {
10945         return getFirstJSDocTag(node, isJSDocClassTag);
10946     }
10947     ts.getJSDocClassTag = getJSDocClassTag;
10948     /** Gets the JSDoc public tag for the node if present */
10949     function getJSDocPublicTag(node) {
10950         return getFirstJSDocTag(node, isJSDocPublicTag);
10951     }
10952     ts.getJSDocPublicTag = getJSDocPublicTag;
10953     /** Gets the JSDoc private tag for the node if present */
10954     function getJSDocPrivateTag(node) {
10955         return getFirstJSDocTag(node, isJSDocPrivateTag);
10956     }
10957     ts.getJSDocPrivateTag = getJSDocPrivateTag;
10958     /** Gets the JSDoc protected tag for the node if present */
10959     function getJSDocProtectedTag(node) {
10960         return getFirstJSDocTag(node, isJSDocProtectedTag);
10961     }
10962     ts.getJSDocProtectedTag = getJSDocProtectedTag;
10963     /** Gets the JSDoc protected tag for the node if present */
10964     function getJSDocReadonlyTag(node) {
10965         return getFirstJSDocTag(node, isJSDocReadonlyTag);
10966     }
10967     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
10968     /** Gets the JSDoc enum tag for the node if present */
10969     function getJSDocEnumTag(node) {
10970         return getFirstJSDocTag(node, isJSDocEnumTag);
10971     }
10972     ts.getJSDocEnumTag = getJSDocEnumTag;
10973     /** Gets the JSDoc this tag for the node if present */
10974     function getJSDocThisTag(node) {
10975         return getFirstJSDocTag(node, isJSDocThisTag);
10976     }
10977     ts.getJSDocThisTag = getJSDocThisTag;
10978     /** Gets the JSDoc return tag for the node if present */
10979     function getJSDocReturnTag(node) {
10980         return getFirstJSDocTag(node, isJSDocReturnTag);
10981     }
10982     ts.getJSDocReturnTag = getJSDocReturnTag;
10983     /** Gets the JSDoc template tag for the node if present */
10984     function getJSDocTemplateTag(node) {
10985         return getFirstJSDocTag(node, isJSDocTemplateTag);
10986     }
10987     ts.getJSDocTemplateTag = getJSDocTemplateTag;
10988     /** Gets the JSDoc type tag for the node if present and valid */
10989     function getJSDocTypeTag(node) {
10990         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
10991         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
10992         if (tag && tag.typeExpression && tag.typeExpression.type) {
10993             return tag;
10994         }
10995         return undefined;
10996     }
10997     ts.getJSDocTypeTag = getJSDocTypeTag;
10998     /**
10999      * Gets the type node for the node if provided via JSDoc.
11000      *
11001      * @remarks The search includes any JSDoc param tag that relates
11002      * to the provided parameter, for example a type tag on the
11003      * parameter itself, or a param tag on a containing function
11004      * expression, or a param tag on a variable declaration whose
11005      * initializer is the containing function. The tags closest to the
11006      * node are examined first, so in the previous example, the type
11007      * tag directly on the node would be returned.
11008      */
11009     function getJSDocType(node) {
11010         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
11011         if (!tag && isParameter(node)) {
11012             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
11013         }
11014         return tag && tag.typeExpression && tag.typeExpression.type;
11015     }
11016     ts.getJSDocType = getJSDocType;
11017     /**
11018      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
11019      *
11020      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
11021      * gets the type from inside the braces, after the fat arrow, etc.
11022      */
11023     function getJSDocReturnType(node) {
11024         var returnTag = getJSDocReturnTag(node);
11025         if (returnTag && returnTag.typeExpression) {
11026             return returnTag.typeExpression.type;
11027         }
11028         var typeTag = getJSDocTypeTag(node);
11029         if (typeTag && typeTag.typeExpression) {
11030             var type = typeTag.typeExpression.type;
11031             if (isTypeLiteralNode(type)) {
11032                 var sig = ts.find(type.members, isCallSignatureDeclaration);
11033                 return sig && sig.type;
11034             }
11035             if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) {
11036                 return type.type;
11037             }
11038         }
11039     }
11040     ts.getJSDocReturnType = getJSDocReturnType;
11041     /** Get all JSDoc tags related to a node, including those on parent nodes. */
11042     function getJSDocTags(node) {
11043         var tags = node.jsDocCache;
11044         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
11045         if (tags === undefined) {
11046             var comments = ts.getJSDocCommentsAndTags(node);
11047             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
11048             node.jsDocCache = tags = ts.flatMap(comments, function (j) { return isJSDoc(j) ? j.tags : j; });
11049         }
11050         return tags;
11051     }
11052     ts.getJSDocTags = getJSDocTags;
11053     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
11054     function getFirstJSDocTag(node, predicate) {
11055         return ts.find(getJSDocTags(node), predicate);
11056     }
11057     /** Gets all JSDoc tags that match a specified predicate */
11058     function getAllJSDocTags(node, predicate) {
11059         return getJSDocTags(node).filter(predicate);
11060     }
11061     ts.getAllJSDocTags = getAllJSDocTags;
11062     /** Gets all JSDoc tags of a specified kind */
11063     function getAllJSDocTagsOfKind(node, kind) {
11064         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
11065     }
11066     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
11067     /**
11068      * Gets the effective type parameters. If the node was parsed in a
11069      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
11070      */
11071     function getEffectiveTypeParameterDeclarations(node) {
11072         if (isJSDocSignature(node)) {
11073             return ts.emptyArray;
11074         }
11075         if (ts.isJSDocTypeAlias(node)) {
11076             ts.Debug.assert(node.parent.kind === 303 /* JSDocComment */);
11077             return ts.flatMap(node.parent.tags, function (tag) { return isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
11078         }
11079         if (node.typeParameters) {
11080             return node.typeParameters;
11081         }
11082         if (ts.isInJSFile(node)) {
11083             var decls = ts.getJSDocTypeParameterDeclarations(node);
11084             if (decls.length) {
11085                 return decls;
11086             }
11087             var typeTag = getJSDocType(node);
11088             if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
11089                 return typeTag.typeParameters;
11090             }
11091         }
11092         return ts.emptyArray;
11093     }
11094     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
11095     function getEffectiveConstraintOfTypeParameter(node) {
11096         return node.constraint ? node.constraint :
11097             isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
11098                 undefined;
11099     }
11100     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
11101     // #region
11102     // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
11103     // Literals
11104     function isNumericLiteral(node) {
11105         return node.kind === 8 /* NumericLiteral */;
11106     }
11107     ts.isNumericLiteral = isNumericLiteral;
11108     function isBigIntLiteral(node) {
11109         return node.kind === 9 /* BigIntLiteral */;
11110     }
11111     ts.isBigIntLiteral = isBigIntLiteral;
11112     function isStringLiteral(node) {
11113         return node.kind === 10 /* StringLiteral */;
11114     }
11115     ts.isStringLiteral = isStringLiteral;
11116     function isJsxText(node) {
11117         return node.kind === 11 /* JsxText */;
11118     }
11119     ts.isJsxText = isJsxText;
11120     function isRegularExpressionLiteral(node) {
11121         return node.kind === 13 /* RegularExpressionLiteral */;
11122     }
11123     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
11124     function isNoSubstitutionTemplateLiteral(node) {
11125         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
11126     }
11127     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
11128     // Pseudo-literals
11129     function isTemplateHead(node) {
11130         return node.kind === 15 /* TemplateHead */;
11131     }
11132     ts.isTemplateHead = isTemplateHead;
11133     function isTemplateMiddle(node) {
11134         return node.kind === 16 /* TemplateMiddle */;
11135     }
11136     ts.isTemplateMiddle = isTemplateMiddle;
11137     function isTemplateTail(node) {
11138         return node.kind === 17 /* TemplateTail */;
11139     }
11140     ts.isTemplateTail = isTemplateTail;
11141     function isIdentifier(node) {
11142         return node.kind === 75 /* Identifier */;
11143     }
11144     ts.isIdentifier = isIdentifier;
11145     // Names
11146     function isQualifiedName(node) {
11147         return node.kind === 153 /* QualifiedName */;
11148     }
11149     ts.isQualifiedName = isQualifiedName;
11150     function isComputedPropertyName(node) {
11151         return node.kind === 154 /* ComputedPropertyName */;
11152     }
11153     ts.isComputedPropertyName = isComputedPropertyName;
11154     function isPrivateIdentifier(node) {
11155         return node.kind === 76 /* PrivateIdentifier */;
11156     }
11157     ts.isPrivateIdentifier = isPrivateIdentifier;
11158     function isIdentifierOrPrivateIdentifier(node) {
11159         return node.kind === 75 /* Identifier */ || node.kind === 76 /* PrivateIdentifier */;
11160     }
11161     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
11162     // Signature elements
11163     function isTypeParameterDeclaration(node) {
11164         return node.kind === 155 /* TypeParameter */;
11165     }
11166     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
11167     function isParameter(node) {
11168         return node.kind === 156 /* Parameter */;
11169     }
11170     ts.isParameter = isParameter;
11171     function isDecorator(node) {
11172         return node.kind === 157 /* Decorator */;
11173     }
11174     ts.isDecorator = isDecorator;
11175     // TypeMember
11176     function isPropertySignature(node) {
11177         return node.kind === 158 /* PropertySignature */;
11178     }
11179     ts.isPropertySignature = isPropertySignature;
11180     function isPropertyDeclaration(node) {
11181         return node.kind === 159 /* PropertyDeclaration */;
11182     }
11183     ts.isPropertyDeclaration = isPropertyDeclaration;
11184     function isMethodSignature(node) {
11185         return node.kind === 160 /* MethodSignature */;
11186     }
11187     ts.isMethodSignature = isMethodSignature;
11188     function isMethodDeclaration(node) {
11189         return node.kind === 161 /* MethodDeclaration */;
11190     }
11191     ts.isMethodDeclaration = isMethodDeclaration;
11192     function isConstructorDeclaration(node) {
11193         return node.kind === 162 /* Constructor */;
11194     }
11195     ts.isConstructorDeclaration = isConstructorDeclaration;
11196     function isGetAccessorDeclaration(node) {
11197         return node.kind === 163 /* GetAccessor */;
11198     }
11199     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
11200     function isSetAccessorDeclaration(node) {
11201         return node.kind === 164 /* SetAccessor */;
11202     }
11203     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
11204     function isCallSignatureDeclaration(node) {
11205         return node.kind === 165 /* CallSignature */;
11206     }
11207     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
11208     function isConstructSignatureDeclaration(node) {
11209         return node.kind === 166 /* ConstructSignature */;
11210     }
11211     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
11212     function isIndexSignatureDeclaration(node) {
11213         return node.kind === 167 /* IndexSignature */;
11214     }
11215     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
11216     /* @internal */
11217     function isGetOrSetAccessorDeclaration(node) {
11218         return node.kind === 164 /* SetAccessor */ || node.kind === 163 /* GetAccessor */;
11219     }
11220     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
11221     // Type
11222     function isTypePredicateNode(node) {
11223         return node.kind === 168 /* TypePredicate */;
11224     }
11225     ts.isTypePredicateNode = isTypePredicateNode;
11226     function isTypeReferenceNode(node) {
11227         return node.kind === 169 /* TypeReference */;
11228     }
11229     ts.isTypeReferenceNode = isTypeReferenceNode;
11230     function isFunctionTypeNode(node) {
11231         return node.kind === 170 /* FunctionType */;
11232     }
11233     ts.isFunctionTypeNode = isFunctionTypeNode;
11234     function isConstructorTypeNode(node) {
11235         return node.kind === 171 /* ConstructorType */;
11236     }
11237     ts.isConstructorTypeNode = isConstructorTypeNode;
11238     function isTypeQueryNode(node) {
11239         return node.kind === 172 /* TypeQuery */;
11240     }
11241     ts.isTypeQueryNode = isTypeQueryNode;
11242     function isTypeLiteralNode(node) {
11243         return node.kind === 173 /* TypeLiteral */;
11244     }
11245     ts.isTypeLiteralNode = isTypeLiteralNode;
11246     function isArrayTypeNode(node) {
11247         return node.kind === 174 /* ArrayType */;
11248     }
11249     ts.isArrayTypeNode = isArrayTypeNode;
11250     function isTupleTypeNode(node) {
11251         return node.kind === 175 /* TupleType */;
11252     }
11253     ts.isTupleTypeNode = isTupleTypeNode;
11254     function isUnionTypeNode(node) {
11255         return node.kind === 178 /* UnionType */;
11256     }
11257     ts.isUnionTypeNode = isUnionTypeNode;
11258     function isIntersectionTypeNode(node) {
11259         return node.kind === 179 /* IntersectionType */;
11260     }
11261     ts.isIntersectionTypeNode = isIntersectionTypeNode;
11262     function isConditionalTypeNode(node) {
11263         return node.kind === 180 /* ConditionalType */;
11264     }
11265     ts.isConditionalTypeNode = isConditionalTypeNode;
11266     function isInferTypeNode(node) {
11267         return node.kind === 181 /* InferType */;
11268     }
11269     ts.isInferTypeNode = isInferTypeNode;
11270     function isParenthesizedTypeNode(node) {
11271         return node.kind === 182 /* ParenthesizedType */;
11272     }
11273     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
11274     function isThisTypeNode(node) {
11275         return node.kind === 183 /* ThisType */;
11276     }
11277     ts.isThisTypeNode = isThisTypeNode;
11278     function isTypeOperatorNode(node) {
11279         return node.kind === 184 /* TypeOperator */;
11280     }
11281     ts.isTypeOperatorNode = isTypeOperatorNode;
11282     function isIndexedAccessTypeNode(node) {
11283         return node.kind === 185 /* IndexedAccessType */;
11284     }
11285     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
11286     function isMappedTypeNode(node) {
11287         return node.kind === 186 /* MappedType */;
11288     }
11289     ts.isMappedTypeNode = isMappedTypeNode;
11290     function isLiteralTypeNode(node) {
11291         return node.kind === 187 /* LiteralType */;
11292     }
11293     ts.isLiteralTypeNode = isLiteralTypeNode;
11294     function isImportTypeNode(node) {
11295         return node.kind === 188 /* ImportType */;
11296     }
11297     ts.isImportTypeNode = isImportTypeNode;
11298     // Binding patterns
11299     function isObjectBindingPattern(node) {
11300         return node.kind === 189 /* ObjectBindingPattern */;
11301     }
11302     ts.isObjectBindingPattern = isObjectBindingPattern;
11303     function isArrayBindingPattern(node) {
11304         return node.kind === 190 /* ArrayBindingPattern */;
11305     }
11306     ts.isArrayBindingPattern = isArrayBindingPattern;
11307     function isBindingElement(node) {
11308         return node.kind === 191 /* BindingElement */;
11309     }
11310     ts.isBindingElement = isBindingElement;
11311     // Expression
11312     function isArrayLiteralExpression(node) {
11313         return node.kind === 192 /* ArrayLiteralExpression */;
11314     }
11315     ts.isArrayLiteralExpression = isArrayLiteralExpression;
11316     function isObjectLiteralExpression(node) {
11317         return node.kind === 193 /* ObjectLiteralExpression */;
11318     }
11319     ts.isObjectLiteralExpression = isObjectLiteralExpression;
11320     function isPropertyAccessExpression(node) {
11321         return node.kind === 194 /* PropertyAccessExpression */;
11322     }
11323     ts.isPropertyAccessExpression = isPropertyAccessExpression;
11324     function isPropertyAccessChain(node) {
11325         return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11326     }
11327     ts.isPropertyAccessChain = isPropertyAccessChain;
11328     function isElementAccessExpression(node) {
11329         return node.kind === 195 /* ElementAccessExpression */;
11330     }
11331     ts.isElementAccessExpression = isElementAccessExpression;
11332     function isElementAccessChain(node) {
11333         return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11334     }
11335     ts.isElementAccessChain = isElementAccessChain;
11336     function isCallExpression(node) {
11337         return node.kind === 196 /* CallExpression */;
11338     }
11339     ts.isCallExpression = isCallExpression;
11340     function isCallChain(node) {
11341         return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11342     }
11343     ts.isCallChain = isCallChain;
11344     function isOptionalChain(node) {
11345         var kind = node.kind;
11346         return !!(node.flags & 32 /* OptionalChain */) &&
11347             (kind === 194 /* PropertyAccessExpression */
11348                 || kind === 195 /* ElementAccessExpression */
11349                 || kind === 196 /* CallExpression */
11350                 || kind === 218 /* NonNullExpression */);
11351     }
11352     ts.isOptionalChain = isOptionalChain;
11353     /* @internal */
11354     function isOptionalChainRoot(node) {
11355         return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken;
11356     }
11357     ts.isOptionalChainRoot = isOptionalChainRoot;
11358     /**
11359      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
11360      */
11361     /* @internal */
11362     function isExpressionOfOptionalChainRoot(node) {
11363         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
11364     }
11365     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
11366     /**
11367      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
11368      *
11369      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
11370      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
11371      * 3. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain)
11372      * 4. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is
11373      *   the end of the chain starting at `c?.`)
11374      * 5. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is
11375      *   the end of the chain starting at `a?.`)
11376      */
11377     /* @internal */
11378     function isOutermostOptionalChain(node) {
11379         return !isOptionalChain(node.parent) // cases 1, 2, and 3
11380             || isOptionalChainRoot(node.parent) // case 4
11381             || node !== node.parent.expression; // case 5
11382     }
11383     ts.isOutermostOptionalChain = isOutermostOptionalChain;
11384     function isNullishCoalesce(node) {
11385         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
11386     }
11387     ts.isNullishCoalesce = isNullishCoalesce;
11388     function isNewExpression(node) {
11389         return node.kind === 197 /* NewExpression */;
11390     }
11391     ts.isNewExpression = isNewExpression;
11392     function isTaggedTemplateExpression(node) {
11393         return node.kind === 198 /* TaggedTemplateExpression */;
11394     }
11395     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
11396     function isTypeAssertion(node) {
11397         return node.kind === 199 /* TypeAssertionExpression */;
11398     }
11399     ts.isTypeAssertion = isTypeAssertion;
11400     function isConstTypeReference(node) {
11401         return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
11402             node.typeName.escapedText === "const" && !node.typeArguments;
11403     }
11404     ts.isConstTypeReference = isConstTypeReference;
11405     function isParenthesizedExpression(node) {
11406         return node.kind === 200 /* ParenthesizedExpression */;
11407     }
11408     ts.isParenthesizedExpression = isParenthesizedExpression;
11409     function skipPartiallyEmittedExpressions(node) {
11410         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
11411     }
11412     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
11413     function isFunctionExpression(node) {
11414         return node.kind === 201 /* FunctionExpression */;
11415     }
11416     ts.isFunctionExpression = isFunctionExpression;
11417     function isArrowFunction(node) {
11418         return node.kind === 202 /* ArrowFunction */;
11419     }
11420     ts.isArrowFunction = isArrowFunction;
11421     function isDeleteExpression(node) {
11422         return node.kind === 203 /* DeleteExpression */;
11423     }
11424     ts.isDeleteExpression = isDeleteExpression;
11425     function isTypeOfExpression(node) {
11426         return node.kind === 204 /* TypeOfExpression */;
11427     }
11428     ts.isTypeOfExpression = isTypeOfExpression;
11429     function isVoidExpression(node) {
11430         return node.kind === 205 /* VoidExpression */;
11431     }
11432     ts.isVoidExpression = isVoidExpression;
11433     function isAwaitExpression(node) {
11434         return node.kind === 206 /* AwaitExpression */;
11435     }
11436     ts.isAwaitExpression = isAwaitExpression;
11437     function isPrefixUnaryExpression(node) {
11438         return node.kind === 207 /* PrefixUnaryExpression */;
11439     }
11440     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
11441     function isPostfixUnaryExpression(node) {
11442         return node.kind === 208 /* PostfixUnaryExpression */;
11443     }
11444     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
11445     function isBinaryExpression(node) {
11446         return node.kind === 209 /* BinaryExpression */;
11447     }
11448     ts.isBinaryExpression = isBinaryExpression;
11449     function isConditionalExpression(node) {
11450         return node.kind === 210 /* ConditionalExpression */;
11451     }
11452     ts.isConditionalExpression = isConditionalExpression;
11453     function isTemplateExpression(node) {
11454         return node.kind === 211 /* TemplateExpression */;
11455     }
11456     ts.isTemplateExpression = isTemplateExpression;
11457     function isYieldExpression(node) {
11458         return node.kind === 212 /* YieldExpression */;
11459     }
11460     ts.isYieldExpression = isYieldExpression;
11461     function isSpreadElement(node) {
11462         return node.kind === 213 /* SpreadElement */;
11463     }
11464     ts.isSpreadElement = isSpreadElement;
11465     function isClassExpression(node) {
11466         return node.kind === 214 /* ClassExpression */;
11467     }
11468     ts.isClassExpression = isClassExpression;
11469     function isOmittedExpression(node) {
11470         return node.kind === 215 /* OmittedExpression */;
11471     }
11472     ts.isOmittedExpression = isOmittedExpression;
11473     function isExpressionWithTypeArguments(node) {
11474         return node.kind === 216 /* ExpressionWithTypeArguments */;
11475     }
11476     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
11477     function isAsExpression(node) {
11478         return node.kind === 217 /* AsExpression */;
11479     }
11480     ts.isAsExpression = isAsExpression;
11481     function isNonNullExpression(node) {
11482         return node.kind === 218 /* NonNullExpression */;
11483     }
11484     ts.isNonNullExpression = isNonNullExpression;
11485     function isNonNullChain(node) {
11486         return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11487     }
11488     ts.isNonNullChain = isNonNullChain;
11489     function isMetaProperty(node) {
11490         return node.kind === 219 /* MetaProperty */;
11491     }
11492     ts.isMetaProperty = isMetaProperty;
11493     // Misc
11494     function isTemplateSpan(node) {
11495         return node.kind === 221 /* TemplateSpan */;
11496     }
11497     ts.isTemplateSpan = isTemplateSpan;
11498     function isSemicolonClassElement(node) {
11499         return node.kind === 222 /* SemicolonClassElement */;
11500     }
11501     ts.isSemicolonClassElement = isSemicolonClassElement;
11502     // Block
11503     function isBlock(node) {
11504         return node.kind === 223 /* Block */;
11505     }
11506     ts.isBlock = isBlock;
11507     function isVariableStatement(node) {
11508         return node.kind === 225 /* VariableStatement */;
11509     }
11510     ts.isVariableStatement = isVariableStatement;
11511     function isEmptyStatement(node) {
11512         return node.kind === 224 /* EmptyStatement */;
11513     }
11514     ts.isEmptyStatement = isEmptyStatement;
11515     function isExpressionStatement(node) {
11516         return node.kind === 226 /* ExpressionStatement */;
11517     }
11518     ts.isExpressionStatement = isExpressionStatement;
11519     function isIfStatement(node) {
11520         return node.kind === 227 /* IfStatement */;
11521     }
11522     ts.isIfStatement = isIfStatement;
11523     function isDoStatement(node) {
11524         return node.kind === 228 /* DoStatement */;
11525     }
11526     ts.isDoStatement = isDoStatement;
11527     function isWhileStatement(node) {
11528         return node.kind === 229 /* WhileStatement */;
11529     }
11530     ts.isWhileStatement = isWhileStatement;
11531     function isForStatement(node) {
11532         return node.kind === 230 /* ForStatement */;
11533     }
11534     ts.isForStatement = isForStatement;
11535     function isForInStatement(node) {
11536         return node.kind === 231 /* ForInStatement */;
11537     }
11538     ts.isForInStatement = isForInStatement;
11539     function isForOfStatement(node) {
11540         return node.kind === 232 /* ForOfStatement */;
11541     }
11542     ts.isForOfStatement = isForOfStatement;
11543     function isContinueStatement(node) {
11544         return node.kind === 233 /* ContinueStatement */;
11545     }
11546     ts.isContinueStatement = isContinueStatement;
11547     function isBreakStatement(node) {
11548         return node.kind === 234 /* BreakStatement */;
11549     }
11550     ts.isBreakStatement = isBreakStatement;
11551     function isBreakOrContinueStatement(node) {
11552         return node.kind === 234 /* BreakStatement */ || node.kind === 233 /* ContinueStatement */;
11553     }
11554     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
11555     function isReturnStatement(node) {
11556         return node.kind === 235 /* ReturnStatement */;
11557     }
11558     ts.isReturnStatement = isReturnStatement;
11559     function isWithStatement(node) {
11560         return node.kind === 236 /* WithStatement */;
11561     }
11562     ts.isWithStatement = isWithStatement;
11563     function isSwitchStatement(node) {
11564         return node.kind === 237 /* SwitchStatement */;
11565     }
11566     ts.isSwitchStatement = isSwitchStatement;
11567     function isLabeledStatement(node) {
11568         return node.kind === 238 /* LabeledStatement */;
11569     }
11570     ts.isLabeledStatement = isLabeledStatement;
11571     function isThrowStatement(node) {
11572         return node.kind === 239 /* ThrowStatement */;
11573     }
11574     ts.isThrowStatement = isThrowStatement;
11575     function isTryStatement(node) {
11576         return node.kind === 240 /* TryStatement */;
11577     }
11578     ts.isTryStatement = isTryStatement;
11579     function isDebuggerStatement(node) {
11580         return node.kind === 241 /* DebuggerStatement */;
11581     }
11582     ts.isDebuggerStatement = isDebuggerStatement;
11583     function isVariableDeclaration(node) {
11584         return node.kind === 242 /* VariableDeclaration */;
11585     }
11586     ts.isVariableDeclaration = isVariableDeclaration;
11587     function isVariableDeclarationList(node) {
11588         return node.kind === 243 /* VariableDeclarationList */;
11589     }
11590     ts.isVariableDeclarationList = isVariableDeclarationList;
11591     function isFunctionDeclaration(node) {
11592         return node.kind === 244 /* FunctionDeclaration */;
11593     }
11594     ts.isFunctionDeclaration = isFunctionDeclaration;
11595     function isClassDeclaration(node) {
11596         return node.kind === 245 /* ClassDeclaration */;
11597     }
11598     ts.isClassDeclaration = isClassDeclaration;
11599     function isInterfaceDeclaration(node) {
11600         return node.kind === 246 /* InterfaceDeclaration */;
11601     }
11602     ts.isInterfaceDeclaration = isInterfaceDeclaration;
11603     function isTypeAliasDeclaration(node) {
11604         return node.kind === 247 /* TypeAliasDeclaration */;
11605     }
11606     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
11607     function isEnumDeclaration(node) {
11608         return node.kind === 248 /* EnumDeclaration */;
11609     }
11610     ts.isEnumDeclaration = isEnumDeclaration;
11611     function isModuleDeclaration(node) {
11612         return node.kind === 249 /* ModuleDeclaration */;
11613     }
11614     ts.isModuleDeclaration = isModuleDeclaration;
11615     function isModuleBlock(node) {
11616         return node.kind === 250 /* ModuleBlock */;
11617     }
11618     ts.isModuleBlock = isModuleBlock;
11619     function isCaseBlock(node) {
11620         return node.kind === 251 /* CaseBlock */;
11621     }
11622     ts.isCaseBlock = isCaseBlock;
11623     function isNamespaceExportDeclaration(node) {
11624         return node.kind === 252 /* NamespaceExportDeclaration */;
11625     }
11626     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
11627     function isImportEqualsDeclaration(node) {
11628         return node.kind === 253 /* ImportEqualsDeclaration */;
11629     }
11630     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
11631     function isImportDeclaration(node) {
11632         return node.kind === 254 /* ImportDeclaration */;
11633     }
11634     ts.isImportDeclaration = isImportDeclaration;
11635     function isImportClause(node) {
11636         return node.kind === 255 /* ImportClause */;
11637     }
11638     ts.isImportClause = isImportClause;
11639     function isNamespaceImport(node) {
11640         return node.kind === 256 /* NamespaceImport */;
11641     }
11642     ts.isNamespaceImport = isNamespaceImport;
11643     function isNamespaceExport(node) {
11644         return node.kind === 262 /* NamespaceExport */;
11645     }
11646     ts.isNamespaceExport = isNamespaceExport;
11647     function isNamedExportBindings(node) {
11648         return node.kind === 262 /* NamespaceExport */ || node.kind === 261 /* NamedExports */;
11649     }
11650     ts.isNamedExportBindings = isNamedExportBindings;
11651     function isNamedImports(node) {
11652         return node.kind === 257 /* NamedImports */;
11653     }
11654     ts.isNamedImports = isNamedImports;
11655     function isImportSpecifier(node) {
11656         return node.kind === 258 /* ImportSpecifier */;
11657     }
11658     ts.isImportSpecifier = isImportSpecifier;
11659     function isExportAssignment(node) {
11660         return node.kind === 259 /* ExportAssignment */;
11661     }
11662     ts.isExportAssignment = isExportAssignment;
11663     function isExportDeclaration(node) {
11664         return node.kind === 260 /* ExportDeclaration */;
11665     }
11666     ts.isExportDeclaration = isExportDeclaration;
11667     function isNamedExports(node) {
11668         return node.kind === 261 /* NamedExports */;
11669     }
11670     ts.isNamedExports = isNamedExports;
11671     function isExportSpecifier(node) {
11672         return node.kind === 263 /* ExportSpecifier */;
11673     }
11674     ts.isExportSpecifier = isExportSpecifier;
11675     function isMissingDeclaration(node) {
11676         return node.kind === 264 /* MissingDeclaration */;
11677     }
11678     ts.isMissingDeclaration = isMissingDeclaration;
11679     // Module References
11680     function isExternalModuleReference(node) {
11681         return node.kind === 265 /* ExternalModuleReference */;
11682     }
11683     ts.isExternalModuleReference = isExternalModuleReference;
11684     // JSX
11685     function isJsxElement(node) {
11686         return node.kind === 266 /* JsxElement */;
11687     }
11688     ts.isJsxElement = isJsxElement;
11689     function isJsxSelfClosingElement(node) {
11690         return node.kind === 267 /* JsxSelfClosingElement */;
11691     }
11692     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
11693     function isJsxOpeningElement(node) {
11694         return node.kind === 268 /* JsxOpeningElement */;
11695     }
11696     ts.isJsxOpeningElement = isJsxOpeningElement;
11697     function isJsxClosingElement(node) {
11698         return node.kind === 269 /* JsxClosingElement */;
11699     }
11700     ts.isJsxClosingElement = isJsxClosingElement;
11701     function isJsxFragment(node) {
11702         return node.kind === 270 /* JsxFragment */;
11703     }
11704     ts.isJsxFragment = isJsxFragment;
11705     function isJsxOpeningFragment(node) {
11706         return node.kind === 271 /* JsxOpeningFragment */;
11707     }
11708     ts.isJsxOpeningFragment = isJsxOpeningFragment;
11709     function isJsxClosingFragment(node) {
11710         return node.kind === 272 /* JsxClosingFragment */;
11711     }
11712     ts.isJsxClosingFragment = isJsxClosingFragment;
11713     function isJsxAttribute(node) {
11714         return node.kind === 273 /* JsxAttribute */;
11715     }
11716     ts.isJsxAttribute = isJsxAttribute;
11717     function isJsxAttributes(node) {
11718         return node.kind === 274 /* JsxAttributes */;
11719     }
11720     ts.isJsxAttributes = isJsxAttributes;
11721     function isJsxSpreadAttribute(node) {
11722         return node.kind === 275 /* JsxSpreadAttribute */;
11723     }
11724     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
11725     function isJsxExpression(node) {
11726         return node.kind === 276 /* JsxExpression */;
11727     }
11728     ts.isJsxExpression = isJsxExpression;
11729     // Clauses
11730     function isCaseClause(node) {
11731         return node.kind === 277 /* CaseClause */;
11732     }
11733     ts.isCaseClause = isCaseClause;
11734     function isDefaultClause(node) {
11735         return node.kind === 278 /* DefaultClause */;
11736     }
11737     ts.isDefaultClause = isDefaultClause;
11738     function isHeritageClause(node) {
11739         return node.kind === 279 /* HeritageClause */;
11740     }
11741     ts.isHeritageClause = isHeritageClause;
11742     function isCatchClause(node) {
11743         return node.kind === 280 /* CatchClause */;
11744     }
11745     ts.isCatchClause = isCatchClause;
11746     // Property assignments
11747     function isPropertyAssignment(node) {
11748         return node.kind === 281 /* PropertyAssignment */;
11749     }
11750     ts.isPropertyAssignment = isPropertyAssignment;
11751     function isShorthandPropertyAssignment(node) {
11752         return node.kind === 282 /* ShorthandPropertyAssignment */;
11753     }
11754     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
11755     function isSpreadAssignment(node) {
11756         return node.kind === 283 /* SpreadAssignment */;
11757     }
11758     ts.isSpreadAssignment = isSpreadAssignment;
11759     // Enum
11760     function isEnumMember(node) {
11761         return node.kind === 284 /* EnumMember */;
11762     }
11763     ts.isEnumMember = isEnumMember;
11764     // Top-level nodes
11765     function isSourceFile(node) {
11766         return node.kind === 290 /* SourceFile */;
11767     }
11768     ts.isSourceFile = isSourceFile;
11769     function isBundle(node) {
11770         return node.kind === 291 /* Bundle */;
11771     }
11772     ts.isBundle = isBundle;
11773     function isUnparsedSource(node) {
11774         return node.kind === 292 /* UnparsedSource */;
11775     }
11776     ts.isUnparsedSource = isUnparsedSource;
11777     function isUnparsedPrepend(node) {
11778         return node.kind === 286 /* UnparsedPrepend */;
11779     }
11780     ts.isUnparsedPrepend = isUnparsedPrepend;
11781     function isUnparsedTextLike(node) {
11782         switch (node.kind) {
11783             case 287 /* UnparsedText */:
11784             case 288 /* UnparsedInternalText */:
11785                 return true;
11786             default:
11787                 return false;
11788         }
11789     }
11790     ts.isUnparsedTextLike = isUnparsedTextLike;
11791     function isUnparsedNode(node) {
11792         return isUnparsedTextLike(node) ||
11793             node.kind === 285 /* UnparsedPrologue */ ||
11794             node.kind === 289 /* UnparsedSyntheticReference */;
11795     }
11796     ts.isUnparsedNode = isUnparsedNode;
11797     // JSDoc
11798     function isJSDocTypeExpression(node) {
11799         return node.kind === 294 /* JSDocTypeExpression */;
11800     }
11801     ts.isJSDocTypeExpression = isJSDocTypeExpression;
11802     function isJSDocAllType(node) {
11803         return node.kind === 295 /* JSDocAllType */;
11804     }
11805     ts.isJSDocAllType = isJSDocAllType;
11806     function isJSDocUnknownType(node) {
11807         return node.kind === 296 /* JSDocUnknownType */;
11808     }
11809     ts.isJSDocUnknownType = isJSDocUnknownType;
11810     function isJSDocNullableType(node) {
11811         return node.kind === 297 /* JSDocNullableType */;
11812     }
11813     ts.isJSDocNullableType = isJSDocNullableType;
11814     function isJSDocNonNullableType(node) {
11815         return node.kind === 298 /* JSDocNonNullableType */;
11816     }
11817     ts.isJSDocNonNullableType = isJSDocNonNullableType;
11818     function isJSDocOptionalType(node) {
11819         return node.kind === 299 /* JSDocOptionalType */;
11820     }
11821     ts.isJSDocOptionalType = isJSDocOptionalType;
11822     function isJSDocFunctionType(node) {
11823         return node.kind === 300 /* JSDocFunctionType */;
11824     }
11825     ts.isJSDocFunctionType = isJSDocFunctionType;
11826     function isJSDocVariadicType(node) {
11827         return node.kind === 301 /* JSDocVariadicType */;
11828     }
11829     ts.isJSDocVariadicType = isJSDocVariadicType;
11830     function isJSDoc(node) {
11831         return node.kind === 303 /* JSDocComment */;
11832     }
11833     ts.isJSDoc = isJSDoc;
11834     function isJSDocAuthorTag(node) {
11835         return node.kind === 309 /* JSDocAuthorTag */;
11836     }
11837     ts.isJSDocAuthorTag = isJSDocAuthorTag;
11838     function isJSDocAugmentsTag(node) {
11839         return node.kind === 307 /* JSDocAugmentsTag */;
11840     }
11841     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
11842     function isJSDocImplementsTag(node) {
11843         return node.kind === 308 /* JSDocImplementsTag */;
11844     }
11845     ts.isJSDocImplementsTag = isJSDocImplementsTag;
11846     function isJSDocClassTag(node) {
11847         return node.kind === 310 /* JSDocClassTag */;
11848     }
11849     ts.isJSDocClassTag = isJSDocClassTag;
11850     function isJSDocPublicTag(node) {
11851         return node.kind === 311 /* JSDocPublicTag */;
11852     }
11853     ts.isJSDocPublicTag = isJSDocPublicTag;
11854     function isJSDocPrivateTag(node) {
11855         return node.kind === 312 /* JSDocPrivateTag */;
11856     }
11857     ts.isJSDocPrivateTag = isJSDocPrivateTag;
11858     function isJSDocProtectedTag(node) {
11859         return node.kind === 313 /* JSDocProtectedTag */;
11860     }
11861     ts.isJSDocProtectedTag = isJSDocProtectedTag;
11862     function isJSDocReadonlyTag(node) {
11863         return node.kind === 314 /* JSDocReadonlyTag */;
11864     }
11865     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
11866     function isJSDocEnumTag(node) {
11867         return node.kind === 316 /* JSDocEnumTag */;
11868     }
11869     ts.isJSDocEnumTag = isJSDocEnumTag;
11870     function isJSDocThisTag(node) {
11871         return node.kind === 319 /* JSDocThisTag */;
11872     }
11873     ts.isJSDocThisTag = isJSDocThisTag;
11874     function isJSDocParameterTag(node) {
11875         return node.kind === 317 /* JSDocParameterTag */;
11876     }
11877     ts.isJSDocParameterTag = isJSDocParameterTag;
11878     function isJSDocReturnTag(node) {
11879         return node.kind === 318 /* JSDocReturnTag */;
11880     }
11881     ts.isJSDocReturnTag = isJSDocReturnTag;
11882     function isJSDocTypeTag(node) {
11883         return node.kind === 320 /* JSDocTypeTag */;
11884     }
11885     ts.isJSDocTypeTag = isJSDocTypeTag;
11886     function isJSDocTemplateTag(node) {
11887         return node.kind === 321 /* JSDocTemplateTag */;
11888     }
11889     ts.isJSDocTemplateTag = isJSDocTemplateTag;
11890     function isJSDocTypedefTag(node) {
11891         return node.kind === 322 /* JSDocTypedefTag */;
11892     }
11893     ts.isJSDocTypedefTag = isJSDocTypedefTag;
11894     function isJSDocPropertyTag(node) {
11895         return node.kind === 323 /* JSDocPropertyTag */;
11896     }
11897     ts.isJSDocPropertyTag = isJSDocPropertyTag;
11898     function isJSDocPropertyLikeTag(node) {
11899         return node.kind === 323 /* JSDocPropertyTag */ || node.kind === 317 /* JSDocParameterTag */;
11900     }
11901     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
11902     function isJSDocTypeLiteral(node) {
11903         return node.kind === 304 /* JSDocTypeLiteral */;
11904     }
11905     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
11906     function isJSDocCallbackTag(node) {
11907         return node.kind === 315 /* JSDocCallbackTag */;
11908     }
11909     ts.isJSDocCallbackTag = isJSDocCallbackTag;
11910     function isJSDocSignature(node) {
11911         return node.kind === 305 /* JSDocSignature */;
11912     }
11913     ts.isJSDocSignature = isJSDocSignature;
11914     // #endregion
11915     // #region
11916     // Node tests
11917     //
11918     // All node tests in the following list should *not* reference parent pointers so that
11919     // they may be used with transformations.
11920     /* @internal */
11921     function isSyntaxList(n) {
11922         return n.kind === 324 /* SyntaxList */;
11923     }
11924     ts.isSyntaxList = isSyntaxList;
11925     /* @internal */
11926     function isNode(node) {
11927         return isNodeKind(node.kind);
11928     }
11929     ts.isNode = isNode;
11930     /* @internal */
11931     function isNodeKind(kind) {
11932         return kind >= 153 /* FirstNode */;
11933     }
11934     ts.isNodeKind = isNodeKind;
11935     /**
11936      * True if node is of some token syntax kind.
11937      * For example, this is true for an IfKeyword but not for an IfStatement.
11938      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
11939      */
11940     function isToken(n) {
11941         return n.kind >= 0 /* FirstToken */ && n.kind <= 152 /* LastToken */;
11942     }
11943     ts.isToken = isToken;
11944     // Node Arrays
11945     /* @internal */
11946     function isNodeArray(array) {
11947         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
11948     }
11949     ts.isNodeArray = isNodeArray;
11950     // Literals
11951     /* @internal */
11952     function isLiteralKind(kind) {
11953         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
11954     }
11955     ts.isLiteralKind = isLiteralKind;
11956     function isLiteralExpression(node) {
11957         return isLiteralKind(node.kind);
11958     }
11959     ts.isLiteralExpression = isLiteralExpression;
11960     // Pseudo-literals
11961     /* @internal */
11962     function isTemplateLiteralKind(kind) {
11963         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
11964     }
11965     ts.isTemplateLiteralKind = isTemplateLiteralKind;
11966     function isTemplateLiteralToken(node) {
11967         return isTemplateLiteralKind(node.kind);
11968     }
11969     ts.isTemplateLiteralToken = isTemplateLiteralToken;
11970     function isTemplateMiddleOrTemplateTail(node) {
11971         var kind = node.kind;
11972         return kind === 16 /* TemplateMiddle */
11973             || kind === 17 /* TemplateTail */;
11974     }
11975     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
11976     function isImportOrExportSpecifier(node) {
11977         return isImportSpecifier(node) || isExportSpecifier(node);
11978     }
11979     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
11980     function isTypeOnlyImportOrExportDeclaration(node) {
11981         switch (node.kind) {
11982             case 258 /* ImportSpecifier */:
11983             case 263 /* ExportSpecifier */:
11984                 return node.parent.parent.isTypeOnly;
11985             case 256 /* NamespaceImport */:
11986                 return node.parent.isTypeOnly;
11987             case 255 /* ImportClause */:
11988                 return node.isTypeOnly;
11989             default:
11990                 return false;
11991         }
11992     }
11993     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
11994     function isStringTextContainingNode(node) {
11995         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
11996     }
11997     ts.isStringTextContainingNode = isStringTextContainingNode;
11998     // Identifiers
11999     /* @internal */
12000     function isGeneratedIdentifier(node) {
12001         return isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
12002     }
12003     ts.isGeneratedIdentifier = isGeneratedIdentifier;
12004     // Private Identifiers
12005     /*@internal*/
12006     function isPrivateIdentifierPropertyDeclaration(node) {
12007         return isPropertyDeclaration(node) && isPrivateIdentifier(node.name);
12008     }
12009     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
12010     /*@internal*/
12011     function isPrivateIdentifierPropertyAccessExpression(node) {
12012         return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
12013     }
12014     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12015     // Keywords
12016     /* @internal */
12017     function isModifierKind(token) {
12018         switch (token) {
12019             case 122 /* AbstractKeyword */:
12020             case 126 /* AsyncKeyword */:
12021             case 81 /* ConstKeyword */:
12022             case 130 /* DeclareKeyword */:
12023             case 84 /* DefaultKeyword */:
12024             case 89 /* ExportKeyword */:
12025             case 119 /* PublicKeyword */:
12026             case 117 /* PrivateKeyword */:
12027             case 118 /* ProtectedKeyword */:
12028             case 138 /* ReadonlyKeyword */:
12029             case 120 /* StaticKeyword */:
12030                 return true;
12031         }
12032         return false;
12033     }
12034     ts.isModifierKind = isModifierKind;
12035     /* @internal */
12036     function isParameterPropertyModifier(kind) {
12037         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12038     }
12039     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12040     /* @internal */
12041     function isClassMemberModifier(idToken) {
12042         return isParameterPropertyModifier(idToken) || idToken === 120 /* StaticKeyword */;
12043     }
12044     ts.isClassMemberModifier = isClassMemberModifier;
12045     function isModifier(node) {
12046         return isModifierKind(node.kind);
12047     }
12048     ts.isModifier = isModifier;
12049     function isEntityName(node) {
12050         var kind = node.kind;
12051         return kind === 153 /* QualifiedName */
12052             || kind === 75 /* Identifier */;
12053     }
12054     ts.isEntityName = isEntityName;
12055     function isPropertyName(node) {
12056         var kind = node.kind;
12057         return kind === 75 /* Identifier */
12058             || kind === 76 /* PrivateIdentifier */
12059             || kind === 10 /* StringLiteral */
12060             || kind === 8 /* NumericLiteral */
12061             || kind === 154 /* ComputedPropertyName */;
12062     }
12063     ts.isPropertyName = isPropertyName;
12064     function isBindingName(node) {
12065         var kind = node.kind;
12066         return kind === 75 /* Identifier */
12067             || kind === 189 /* ObjectBindingPattern */
12068             || kind === 190 /* ArrayBindingPattern */;
12069     }
12070     ts.isBindingName = isBindingName;
12071     // Functions
12072     function isFunctionLike(node) {
12073         return node && isFunctionLikeKind(node.kind);
12074     }
12075     ts.isFunctionLike = isFunctionLike;
12076     /* @internal */
12077     function isFunctionLikeDeclaration(node) {
12078         return node && isFunctionLikeDeclarationKind(node.kind);
12079     }
12080     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12081     function isFunctionLikeDeclarationKind(kind) {
12082         switch (kind) {
12083             case 244 /* FunctionDeclaration */:
12084             case 161 /* MethodDeclaration */:
12085             case 162 /* Constructor */:
12086             case 163 /* GetAccessor */:
12087             case 164 /* SetAccessor */:
12088             case 201 /* FunctionExpression */:
12089             case 202 /* ArrowFunction */:
12090                 return true;
12091             default:
12092                 return false;
12093         }
12094     }
12095     /* @internal */
12096     function isFunctionLikeKind(kind) {
12097         switch (kind) {
12098             case 160 /* MethodSignature */:
12099             case 165 /* CallSignature */:
12100             case 305 /* JSDocSignature */:
12101             case 166 /* ConstructSignature */:
12102             case 167 /* IndexSignature */:
12103             case 170 /* FunctionType */:
12104             case 300 /* JSDocFunctionType */:
12105             case 171 /* ConstructorType */:
12106                 return true;
12107             default:
12108                 return isFunctionLikeDeclarationKind(kind);
12109         }
12110     }
12111     ts.isFunctionLikeKind = isFunctionLikeKind;
12112     /* @internal */
12113     function isFunctionOrModuleBlock(node) {
12114         return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent);
12115     }
12116     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12117     // Classes
12118     function isClassElement(node) {
12119         var kind = node.kind;
12120         return kind === 162 /* Constructor */
12121             || kind === 159 /* PropertyDeclaration */
12122             || kind === 161 /* MethodDeclaration */
12123             || kind === 163 /* GetAccessor */
12124             || kind === 164 /* SetAccessor */
12125             || kind === 167 /* IndexSignature */
12126             || kind === 222 /* SemicolonClassElement */;
12127     }
12128     ts.isClassElement = isClassElement;
12129     function isClassLike(node) {
12130         return node && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */);
12131     }
12132     ts.isClassLike = isClassLike;
12133     function isAccessor(node) {
12134         return node && (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */);
12135     }
12136     ts.isAccessor = isAccessor;
12137     /* @internal */
12138     function isMethodOrAccessor(node) {
12139         switch (node.kind) {
12140             case 161 /* MethodDeclaration */:
12141             case 163 /* GetAccessor */:
12142             case 164 /* SetAccessor */:
12143                 return true;
12144             default:
12145                 return false;
12146         }
12147     }
12148     ts.isMethodOrAccessor = isMethodOrAccessor;
12149     // Type members
12150     function isTypeElement(node) {
12151         var kind = node.kind;
12152         return kind === 166 /* ConstructSignature */
12153             || kind === 165 /* CallSignature */
12154             || kind === 158 /* PropertySignature */
12155             || kind === 160 /* MethodSignature */
12156             || kind === 167 /* IndexSignature */;
12157     }
12158     ts.isTypeElement = isTypeElement;
12159     function isClassOrTypeElement(node) {
12160         return isTypeElement(node) || isClassElement(node);
12161     }
12162     ts.isClassOrTypeElement = isClassOrTypeElement;
12163     function isObjectLiteralElementLike(node) {
12164         var kind = node.kind;
12165         return kind === 281 /* PropertyAssignment */
12166             || kind === 282 /* ShorthandPropertyAssignment */
12167             || kind === 283 /* SpreadAssignment */
12168             || kind === 161 /* MethodDeclaration */
12169             || kind === 163 /* GetAccessor */
12170             || kind === 164 /* SetAccessor */;
12171     }
12172     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12173     // Type
12174     /**
12175      * Node test that determines whether a node is a valid type node.
12176      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12177      * of a TypeNode.
12178      */
12179     function isTypeNode(node) {
12180         return ts.isTypeNodeKind(node.kind);
12181     }
12182     ts.isTypeNode = isTypeNode;
12183     function isFunctionOrConstructorTypeNode(node) {
12184         switch (node.kind) {
12185             case 170 /* FunctionType */:
12186             case 171 /* ConstructorType */:
12187                 return true;
12188         }
12189         return false;
12190     }
12191     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12192     // Binding patterns
12193     /* @internal */
12194     function isBindingPattern(node) {
12195         if (node) {
12196             var kind = node.kind;
12197             return kind === 190 /* ArrayBindingPattern */
12198                 || kind === 189 /* ObjectBindingPattern */;
12199         }
12200         return false;
12201     }
12202     ts.isBindingPattern = isBindingPattern;
12203     /* @internal */
12204     function isAssignmentPattern(node) {
12205         var kind = node.kind;
12206         return kind === 192 /* ArrayLiteralExpression */
12207             || kind === 193 /* ObjectLiteralExpression */;
12208     }
12209     ts.isAssignmentPattern = isAssignmentPattern;
12210     /* @internal */
12211     function isArrayBindingElement(node) {
12212         var kind = node.kind;
12213         return kind === 191 /* BindingElement */
12214             || kind === 215 /* OmittedExpression */;
12215     }
12216     ts.isArrayBindingElement = isArrayBindingElement;
12217     /**
12218      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12219      */
12220     /* @internal */
12221     function isDeclarationBindingElement(bindingElement) {
12222         switch (bindingElement.kind) {
12223             case 242 /* VariableDeclaration */:
12224             case 156 /* Parameter */:
12225             case 191 /* BindingElement */:
12226                 return true;
12227         }
12228         return false;
12229     }
12230     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12231     /**
12232      * Determines whether a node is a BindingOrAssignmentPattern
12233      */
12234     /* @internal */
12235     function isBindingOrAssignmentPattern(node) {
12236         return isObjectBindingOrAssignmentPattern(node)
12237             || isArrayBindingOrAssignmentPattern(node);
12238     }
12239     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12240     /**
12241      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12242      */
12243     /* @internal */
12244     function isObjectBindingOrAssignmentPattern(node) {
12245         switch (node.kind) {
12246             case 189 /* ObjectBindingPattern */:
12247             case 193 /* ObjectLiteralExpression */:
12248                 return true;
12249         }
12250         return false;
12251     }
12252     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12253     /**
12254      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12255      */
12256     /* @internal */
12257     function isArrayBindingOrAssignmentPattern(node) {
12258         switch (node.kind) {
12259             case 190 /* ArrayBindingPattern */:
12260             case 192 /* ArrayLiteralExpression */:
12261                 return true;
12262         }
12263         return false;
12264     }
12265     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12266     /* @internal */
12267     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12268         var kind = node.kind;
12269         return kind === 194 /* PropertyAccessExpression */
12270             || kind === 153 /* QualifiedName */
12271             || kind === 188 /* ImportType */;
12272     }
12273     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12274     // Expression
12275     function isPropertyAccessOrQualifiedName(node) {
12276         var kind = node.kind;
12277         return kind === 194 /* PropertyAccessExpression */
12278             || kind === 153 /* QualifiedName */;
12279     }
12280     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12281     function isCallLikeExpression(node) {
12282         switch (node.kind) {
12283             case 268 /* JsxOpeningElement */:
12284             case 267 /* JsxSelfClosingElement */:
12285             case 196 /* CallExpression */:
12286             case 197 /* NewExpression */:
12287             case 198 /* TaggedTemplateExpression */:
12288             case 157 /* Decorator */:
12289                 return true;
12290             default:
12291                 return false;
12292         }
12293     }
12294     ts.isCallLikeExpression = isCallLikeExpression;
12295     function isCallOrNewExpression(node) {
12296         return node.kind === 196 /* CallExpression */ || node.kind === 197 /* NewExpression */;
12297     }
12298     ts.isCallOrNewExpression = isCallOrNewExpression;
12299     function isTemplateLiteral(node) {
12300         var kind = node.kind;
12301         return kind === 211 /* TemplateExpression */
12302             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12303     }
12304     ts.isTemplateLiteral = isTemplateLiteral;
12305     /* @internal */
12306     function isLeftHandSideExpression(node) {
12307         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12308     }
12309     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12310     function isLeftHandSideExpressionKind(kind) {
12311         switch (kind) {
12312             case 194 /* PropertyAccessExpression */:
12313             case 195 /* ElementAccessExpression */:
12314             case 197 /* NewExpression */:
12315             case 196 /* CallExpression */:
12316             case 266 /* JsxElement */:
12317             case 267 /* JsxSelfClosingElement */:
12318             case 270 /* JsxFragment */:
12319             case 198 /* TaggedTemplateExpression */:
12320             case 192 /* ArrayLiteralExpression */:
12321             case 200 /* ParenthesizedExpression */:
12322             case 193 /* ObjectLiteralExpression */:
12323             case 214 /* ClassExpression */:
12324             case 201 /* FunctionExpression */:
12325             case 75 /* Identifier */:
12326             case 13 /* RegularExpressionLiteral */:
12327             case 8 /* NumericLiteral */:
12328             case 9 /* BigIntLiteral */:
12329             case 10 /* StringLiteral */:
12330             case 14 /* NoSubstitutionTemplateLiteral */:
12331             case 211 /* TemplateExpression */:
12332             case 91 /* FalseKeyword */:
12333             case 100 /* NullKeyword */:
12334             case 104 /* ThisKeyword */:
12335             case 106 /* TrueKeyword */:
12336             case 102 /* SuperKeyword */:
12337             case 218 /* NonNullExpression */:
12338             case 219 /* MetaProperty */:
12339             case 96 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12340                 return true;
12341             default:
12342                 return false;
12343         }
12344     }
12345     /* @internal */
12346     function isUnaryExpression(node) {
12347         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12348     }
12349     ts.isUnaryExpression = isUnaryExpression;
12350     function isUnaryExpressionKind(kind) {
12351         switch (kind) {
12352             case 207 /* PrefixUnaryExpression */:
12353             case 208 /* PostfixUnaryExpression */:
12354             case 203 /* DeleteExpression */:
12355             case 204 /* TypeOfExpression */:
12356             case 205 /* VoidExpression */:
12357             case 206 /* AwaitExpression */:
12358             case 199 /* TypeAssertionExpression */:
12359                 return true;
12360             default:
12361                 return isLeftHandSideExpressionKind(kind);
12362         }
12363     }
12364     /* @internal */
12365     function isUnaryExpressionWithWrite(expr) {
12366         switch (expr.kind) {
12367             case 208 /* PostfixUnaryExpression */:
12368                 return true;
12369             case 207 /* PrefixUnaryExpression */:
12370                 return expr.operator === 45 /* PlusPlusToken */ ||
12371                     expr.operator === 46 /* MinusMinusToken */;
12372             default:
12373                 return false;
12374         }
12375     }
12376     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12377     /* @internal */
12378     /**
12379      * Determines whether a node is an expression based only on its kind.
12380      * Use `isExpressionNode` if not in transforms.
12381      */
12382     function isExpression(node) {
12383         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12384     }
12385     ts.isExpression = isExpression;
12386     function isExpressionKind(kind) {
12387         switch (kind) {
12388             case 210 /* ConditionalExpression */:
12389             case 212 /* YieldExpression */:
12390             case 202 /* ArrowFunction */:
12391             case 209 /* BinaryExpression */:
12392             case 213 /* SpreadElement */:
12393             case 217 /* AsExpression */:
12394             case 215 /* OmittedExpression */:
12395             case 327 /* CommaListExpression */:
12396             case 326 /* PartiallyEmittedExpression */:
12397                 return true;
12398             default:
12399                 return isUnaryExpressionKind(kind);
12400         }
12401     }
12402     function isAssertionExpression(node) {
12403         var kind = node.kind;
12404         return kind === 199 /* TypeAssertionExpression */
12405             || kind === 217 /* AsExpression */;
12406     }
12407     ts.isAssertionExpression = isAssertionExpression;
12408     /* @internal */
12409     function isPartiallyEmittedExpression(node) {
12410         return node.kind === 326 /* PartiallyEmittedExpression */;
12411     }
12412     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
12413     /* @internal */
12414     function isNotEmittedStatement(node) {
12415         return node.kind === 325 /* NotEmittedStatement */;
12416     }
12417     ts.isNotEmittedStatement = isNotEmittedStatement;
12418     /* @internal */
12419     function isSyntheticReference(node) {
12420         return node.kind === 330 /* SyntheticReferenceExpression */;
12421     }
12422     ts.isSyntheticReference = isSyntheticReference;
12423     /* @internal */
12424     function isNotEmittedOrPartiallyEmittedNode(node) {
12425         return isNotEmittedStatement(node)
12426             || isPartiallyEmittedExpression(node);
12427     }
12428     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12429     function isIterationStatement(node, lookInLabeledStatements) {
12430         switch (node.kind) {
12431             case 230 /* ForStatement */:
12432             case 231 /* ForInStatement */:
12433             case 232 /* ForOfStatement */:
12434             case 228 /* DoStatement */:
12435             case 229 /* WhileStatement */:
12436                 return true;
12437             case 238 /* LabeledStatement */:
12438                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12439         }
12440         return false;
12441     }
12442     ts.isIterationStatement = isIterationStatement;
12443     /* @internal */
12444     function isScopeMarker(node) {
12445         return isExportAssignment(node) || isExportDeclaration(node);
12446     }
12447     ts.isScopeMarker = isScopeMarker;
12448     /* @internal */
12449     function hasScopeMarker(statements) {
12450         return ts.some(statements, isScopeMarker);
12451     }
12452     ts.hasScopeMarker = hasScopeMarker;
12453     /* @internal */
12454     function needsScopeMarker(result) {
12455         return !ts.isAnyImportOrReExport(result) && !isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12456     }
12457     ts.needsScopeMarker = needsScopeMarker;
12458     /* @internal */
12459     function isExternalModuleIndicator(result) {
12460         // Exported top-level member indicates moduleness
12461         return ts.isAnyImportOrReExport(result) || isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
12462     }
12463     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12464     /* @internal */
12465     function isForInOrOfStatement(node) {
12466         return node.kind === 231 /* ForInStatement */ || node.kind === 232 /* ForOfStatement */;
12467     }
12468     ts.isForInOrOfStatement = isForInOrOfStatement;
12469     // Element
12470     /* @internal */
12471     function isConciseBody(node) {
12472         return isBlock(node)
12473             || isExpression(node);
12474     }
12475     ts.isConciseBody = isConciseBody;
12476     /* @internal */
12477     function isFunctionBody(node) {
12478         return isBlock(node);
12479     }
12480     ts.isFunctionBody = isFunctionBody;
12481     /* @internal */
12482     function isForInitializer(node) {
12483         return isVariableDeclarationList(node)
12484             || isExpression(node);
12485     }
12486     ts.isForInitializer = isForInitializer;
12487     /* @internal */
12488     function isModuleBody(node) {
12489         var kind = node.kind;
12490         return kind === 250 /* ModuleBlock */
12491             || kind === 249 /* ModuleDeclaration */
12492             || kind === 75 /* Identifier */;
12493     }
12494     ts.isModuleBody = isModuleBody;
12495     /* @internal */
12496     function isNamespaceBody(node) {
12497         var kind = node.kind;
12498         return kind === 250 /* ModuleBlock */
12499             || kind === 249 /* ModuleDeclaration */;
12500     }
12501     ts.isNamespaceBody = isNamespaceBody;
12502     /* @internal */
12503     function isJSDocNamespaceBody(node) {
12504         var kind = node.kind;
12505         return kind === 75 /* Identifier */
12506             || kind === 249 /* ModuleDeclaration */;
12507     }
12508     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12509     /* @internal */
12510     function isNamedImportBindings(node) {
12511         var kind = node.kind;
12512         return kind === 257 /* NamedImports */
12513             || kind === 256 /* NamespaceImport */;
12514     }
12515     ts.isNamedImportBindings = isNamedImportBindings;
12516     /* @internal */
12517     function isModuleOrEnumDeclaration(node) {
12518         return node.kind === 249 /* ModuleDeclaration */ || node.kind === 248 /* EnumDeclaration */;
12519     }
12520     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12521     function isDeclarationKind(kind) {
12522         return kind === 202 /* ArrowFunction */
12523             || kind === 191 /* BindingElement */
12524             || kind === 245 /* ClassDeclaration */
12525             || kind === 214 /* ClassExpression */
12526             || kind === 162 /* Constructor */
12527             || kind === 248 /* EnumDeclaration */
12528             || kind === 284 /* EnumMember */
12529             || kind === 263 /* ExportSpecifier */
12530             || kind === 244 /* FunctionDeclaration */
12531             || kind === 201 /* FunctionExpression */
12532             || kind === 163 /* GetAccessor */
12533             || kind === 255 /* ImportClause */
12534             || kind === 253 /* ImportEqualsDeclaration */
12535             || kind === 258 /* ImportSpecifier */
12536             || kind === 246 /* InterfaceDeclaration */
12537             || kind === 273 /* JsxAttribute */
12538             || kind === 161 /* MethodDeclaration */
12539             || kind === 160 /* MethodSignature */
12540             || kind === 249 /* ModuleDeclaration */
12541             || kind === 252 /* NamespaceExportDeclaration */
12542             || kind === 256 /* NamespaceImport */
12543             || kind === 262 /* NamespaceExport */
12544             || kind === 156 /* Parameter */
12545             || kind === 281 /* PropertyAssignment */
12546             || kind === 159 /* PropertyDeclaration */
12547             || kind === 158 /* PropertySignature */
12548             || kind === 164 /* SetAccessor */
12549             || kind === 282 /* ShorthandPropertyAssignment */
12550             || kind === 247 /* TypeAliasDeclaration */
12551             || kind === 155 /* TypeParameter */
12552             || kind === 242 /* VariableDeclaration */
12553             || kind === 322 /* JSDocTypedefTag */
12554             || kind === 315 /* JSDocCallbackTag */
12555             || kind === 323 /* JSDocPropertyTag */;
12556     }
12557     function isDeclarationStatementKind(kind) {
12558         return kind === 244 /* FunctionDeclaration */
12559             || kind === 264 /* MissingDeclaration */
12560             || kind === 245 /* ClassDeclaration */
12561             || kind === 246 /* InterfaceDeclaration */
12562             || kind === 247 /* TypeAliasDeclaration */
12563             || kind === 248 /* EnumDeclaration */
12564             || kind === 249 /* ModuleDeclaration */
12565             || kind === 254 /* ImportDeclaration */
12566             || kind === 253 /* ImportEqualsDeclaration */
12567             || kind === 260 /* ExportDeclaration */
12568             || kind === 259 /* ExportAssignment */
12569             || kind === 252 /* NamespaceExportDeclaration */;
12570     }
12571     function isStatementKindButNotDeclarationKind(kind) {
12572         return kind === 234 /* BreakStatement */
12573             || kind === 233 /* ContinueStatement */
12574             || kind === 241 /* DebuggerStatement */
12575             || kind === 228 /* DoStatement */
12576             || kind === 226 /* ExpressionStatement */
12577             || kind === 224 /* EmptyStatement */
12578             || kind === 231 /* ForInStatement */
12579             || kind === 232 /* ForOfStatement */
12580             || kind === 230 /* ForStatement */
12581             || kind === 227 /* IfStatement */
12582             || kind === 238 /* LabeledStatement */
12583             || kind === 235 /* ReturnStatement */
12584             || kind === 237 /* SwitchStatement */
12585             || kind === 239 /* ThrowStatement */
12586             || kind === 240 /* TryStatement */
12587             || kind === 225 /* VariableStatement */
12588             || kind === 229 /* WhileStatement */
12589             || kind === 236 /* WithStatement */
12590             || kind === 325 /* NotEmittedStatement */
12591             || kind === 329 /* EndOfDeclarationMarker */
12592             || kind === 328 /* MergeDeclarationMarker */;
12593     }
12594     /* @internal */
12595     function isDeclaration(node) {
12596         if (node.kind === 155 /* TypeParameter */) {
12597             return (node.parent && node.parent.kind !== 321 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12598         }
12599         return isDeclarationKind(node.kind);
12600     }
12601     ts.isDeclaration = isDeclaration;
12602     /* @internal */
12603     function isDeclarationStatement(node) {
12604         return isDeclarationStatementKind(node.kind);
12605     }
12606     ts.isDeclarationStatement = isDeclarationStatement;
12607     /**
12608      * Determines whether the node is a statement that is not also a declaration
12609      */
12610     /* @internal */
12611     function isStatementButNotDeclaration(node) {
12612         return isStatementKindButNotDeclarationKind(node.kind);
12613     }
12614     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12615     /* @internal */
12616     function isStatement(node) {
12617         var kind = node.kind;
12618         return isStatementKindButNotDeclarationKind(kind)
12619             || isDeclarationStatementKind(kind)
12620             || isBlockStatement(node);
12621     }
12622     ts.isStatement = isStatement;
12623     function isBlockStatement(node) {
12624         if (node.kind !== 223 /* Block */)
12625             return false;
12626         if (node.parent !== undefined) {
12627             if (node.parent.kind === 240 /* TryStatement */ || node.parent.kind === 280 /* CatchClause */) {
12628                 return false;
12629             }
12630         }
12631         return !ts.isFunctionBlock(node);
12632     }
12633     // Module references
12634     /* @internal */
12635     function isModuleReference(node) {
12636         var kind = node.kind;
12637         return kind === 265 /* ExternalModuleReference */
12638             || kind === 153 /* QualifiedName */
12639             || kind === 75 /* Identifier */;
12640     }
12641     ts.isModuleReference = isModuleReference;
12642     // JSX
12643     /* @internal */
12644     function isJsxTagNameExpression(node) {
12645         var kind = node.kind;
12646         return kind === 104 /* ThisKeyword */
12647             || kind === 75 /* Identifier */
12648             || kind === 194 /* PropertyAccessExpression */;
12649     }
12650     ts.isJsxTagNameExpression = isJsxTagNameExpression;
12651     /* @internal */
12652     function isJsxChild(node) {
12653         var kind = node.kind;
12654         return kind === 266 /* JsxElement */
12655             || kind === 276 /* JsxExpression */
12656             || kind === 267 /* JsxSelfClosingElement */
12657             || kind === 11 /* JsxText */
12658             || kind === 270 /* JsxFragment */;
12659     }
12660     ts.isJsxChild = isJsxChild;
12661     /* @internal */
12662     function isJsxAttributeLike(node) {
12663         var kind = node.kind;
12664         return kind === 273 /* JsxAttribute */
12665             || kind === 275 /* JsxSpreadAttribute */;
12666     }
12667     ts.isJsxAttributeLike = isJsxAttributeLike;
12668     /* @internal */
12669     function isStringLiteralOrJsxExpression(node) {
12670         var kind = node.kind;
12671         return kind === 10 /* StringLiteral */
12672             || kind === 276 /* JsxExpression */;
12673     }
12674     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12675     function isJsxOpeningLikeElement(node) {
12676         var kind = node.kind;
12677         return kind === 268 /* JsxOpeningElement */
12678             || kind === 267 /* JsxSelfClosingElement */;
12679     }
12680     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12681     // Clauses
12682     function isCaseOrDefaultClause(node) {
12683         var kind = node.kind;
12684         return kind === 277 /* CaseClause */
12685             || kind === 278 /* DefaultClause */;
12686     }
12687     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12688     // JSDoc
12689     /** True if node is of some JSDoc syntax kind. */
12690     /* @internal */
12691     function isJSDocNode(node) {
12692         return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 323 /* LastJSDocNode */;
12693     }
12694     ts.isJSDocNode = isJSDocNode;
12695     /** True if node is of a kind that may contain comment text. */
12696     function isJSDocCommentContainingNode(node) {
12697         return node.kind === 303 /* JSDocComment */ || node.kind === 302 /* JSDocNamepathType */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
12698     }
12699     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12700     // TODO: determine what this does before making it public.
12701     /* @internal */
12702     function isJSDocTag(node) {
12703         return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 323 /* LastJSDocTagNode */;
12704     }
12705     ts.isJSDocTag = isJSDocTag;
12706     function isSetAccessor(node) {
12707         return node.kind === 164 /* SetAccessor */;
12708     }
12709     ts.isSetAccessor = isSetAccessor;
12710     function isGetAccessor(node) {
12711         return node.kind === 163 /* GetAccessor */;
12712     }
12713     ts.isGetAccessor = isGetAccessor;
12714     /** True if has jsdoc nodes attached to it. */
12715     /* @internal */
12716     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
12717     function hasJSDocNodes(node) {
12718         var jsDoc = node.jsDoc;
12719         return !!jsDoc && jsDoc.length > 0;
12720     }
12721     ts.hasJSDocNodes = hasJSDocNodes;
12722     /** True if has type node attached to it. */
12723     /* @internal */
12724     function hasType(node) {
12725         return !!node.type;
12726     }
12727     ts.hasType = hasType;
12728     /** True if has initializer node attached to it. */
12729     /* @internal */
12730     function hasInitializer(node) {
12731         return !!node.initializer;
12732     }
12733     ts.hasInitializer = hasInitializer;
12734     /** True if has initializer node attached to it. */
12735     function hasOnlyExpressionInitializer(node) {
12736         switch (node.kind) {
12737             case 242 /* VariableDeclaration */:
12738             case 156 /* Parameter */:
12739             case 191 /* BindingElement */:
12740             case 158 /* PropertySignature */:
12741             case 159 /* PropertyDeclaration */:
12742             case 281 /* PropertyAssignment */:
12743             case 284 /* EnumMember */:
12744                 return true;
12745             default:
12746                 return false;
12747         }
12748     }
12749     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
12750     function isObjectLiteralElement(node) {
12751         return node.kind === 273 /* JsxAttribute */ || node.kind === 275 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
12752     }
12753     ts.isObjectLiteralElement = isObjectLiteralElement;
12754     /* @internal */
12755     function isTypeReferenceType(node) {
12756         return node.kind === 169 /* TypeReference */ || node.kind === 216 /* ExpressionWithTypeArguments */;
12757     }
12758     ts.isTypeReferenceType = isTypeReferenceType;
12759     var MAX_SMI_X86 = 1073741823;
12760     /* @internal */
12761     function guessIndentation(lines) {
12762         var indentation = MAX_SMI_X86;
12763         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
12764             var line = lines_1[_i];
12765             if (!line.length) {
12766                 continue;
12767             }
12768             var i = 0;
12769             for (; i < line.length && i < indentation; i++) {
12770                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
12771                     break;
12772                 }
12773             }
12774             if (i < indentation) {
12775                 indentation = i;
12776             }
12777             if (indentation === 0) {
12778                 return 0;
12779             }
12780         }
12781         return indentation === MAX_SMI_X86 ? undefined : indentation;
12782     }
12783     ts.guessIndentation = guessIndentation;
12784     function isStringLiteralLike(node) {
12785         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
12786     }
12787     ts.isStringLiteralLike = isStringLiteralLike;
12788     // #endregion
12789 })(ts || (ts = {}));
12790 /* @internal */
12791 var ts;
12792 (function (ts) {
12793     ts.resolvingEmptyArray = [];
12794     ts.emptyMap = ts.createMap();
12795     ts.emptyUnderscoreEscapedMap = ts.emptyMap;
12796     ts.externalHelpersModuleNameText = "tslib";
12797     ts.defaultMaximumTruncationLength = 160;
12798     ts.noTruncationMaximumTruncationLength = 1000000;
12799     function getDeclarationOfKind(symbol, kind) {
12800         var declarations = symbol.declarations;
12801         if (declarations) {
12802             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
12803                 var declaration = declarations_1[_i];
12804                 if (declaration.kind === kind) {
12805                     return declaration;
12806                 }
12807             }
12808         }
12809         return undefined;
12810     }
12811     ts.getDeclarationOfKind = getDeclarationOfKind;
12812     /** Create a new escaped identifier map. */
12813     function createUnderscoreEscapedMap() {
12814         return new ts.Map();
12815     }
12816     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
12817     function hasEntries(map) {
12818         return !!map && !!map.size;
12819     }
12820     ts.hasEntries = hasEntries;
12821     function createSymbolTable(symbols) {
12822         var result = ts.createMap();
12823         if (symbols) {
12824             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
12825                 var symbol = symbols_1[_i];
12826                 result.set(symbol.escapedName, symbol);
12827             }
12828         }
12829         return result;
12830     }
12831     ts.createSymbolTable = createSymbolTable;
12832     function isTransientSymbol(symbol) {
12833         return (symbol.flags & 33554432 /* Transient */) !== 0;
12834     }
12835     ts.isTransientSymbol = isTransientSymbol;
12836     var stringWriter = createSingleLineStringWriter();
12837     function createSingleLineStringWriter() {
12838         var str = "";
12839         var writeText = function (text) { return str += text; };
12840         return {
12841             getText: function () { return str; },
12842             write: writeText,
12843             rawWrite: writeText,
12844             writeKeyword: writeText,
12845             writeOperator: writeText,
12846             writePunctuation: writeText,
12847             writeSpace: writeText,
12848             writeStringLiteral: writeText,
12849             writeLiteral: writeText,
12850             writeParameter: writeText,
12851             writeProperty: writeText,
12852             writeSymbol: function (s, _) { return writeText(s); },
12853             writeTrailingSemicolon: writeText,
12854             writeComment: writeText,
12855             getTextPos: function () { return str.length; },
12856             getLine: function () { return 0; },
12857             getColumn: function () { return 0; },
12858             getIndent: function () { return 0; },
12859             isAtStartOfLine: function () { return false; },
12860             hasTrailingComment: function () { return false; },
12861             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
12862             // Completely ignore indentation for string writers.  And map newlines to
12863             // a single space.
12864             writeLine: function () { return str += " "; },
12865             increaseIndent: ts.noop,
12866             decreaseIndent: ts.noop,
12867             clear: function () { return str = ""; },
12868             trackSymbol: ts.noop,
12869             reportInaccessibleThisError: ts.noop,
12870             reportInaccessibleUniqueSymbolError: ts.noop,
12871             reportPrivateInBaseOfClassExpression: ts.noop,
12872         };
12873     }
12874     function changesAffectModuleResolution(oldOptions, newOptions) {
12875         return oldOptions.configFilePath !== newOptions.configFilePath ||
12876             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
12877     }
12878     ts.changesAffectModuleResolution = changesAffectModuleResolution;
12879     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
12880         return ts.moduleResolutionOptionDeclarations.some(function (o) {
12881             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
12882         });
12883     }
12884     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
12885     function findAncestor(node, callback) {
12886         while (node) {
12887             var result = callback(node);
12888             if (result === "quit") {
12889                 return undefined;
12890             }
12891             else if (result) {
12892                 return node;
12893             }
12894             node = node.parent;
12895         }
12896         return undefined;
12897     }
12898     ts.findAncestor = findAncestor;
12899     function forEachAncestor(node, callback) {
12900         while (true) {
12901             var res = callback(node);
12902             if (res === "quit")
12903                 return undefined;
12904             if (res !== undefined)
12905                 return res;
12906             if (ts.isSourceFile(node))
12907                 return undefined;
12908             node = node.parent;
12909         }
12910     }
12911     ts.forEachAncestor = forEachAncestor;
12912     function forEachEntry(map, callback) {
12913         var iterator = map.entries();
12914         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12915             var _a = iterResult.value, key = _a[0], value = _a[1];
12916             var result = callback(value, key);
12917             if (result) {
12918                 return result;
12919             }
12920         }
12921         return undefined;
12922     }
12923     ts.forEachEntry = forEachEntry;
12924     function forEachKey(map, callback) {
12925         var iterator = map.keys();
12926         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12927             var result = callback(iterResult.value);
12928             if (result) {
12929                 return result;
12930             }
12931         }
12932         return undefined;
12933     }
12934     ts.forEachKey = forEachKey;
12935     function copyEntries(source, target) {
12936         source.forEach(function (value, key) {
12937             target.set(key, value);
12938         });
12939     }
12940     ts.copyEntries = copyEntries;
12941     function arrayToSet(array, makeKey) {
12942         return ts.arrayToMap(array, makeKey || (function (s) { return s; }), ts.returnTrue);
12943     }
12944     ts.arrayToSet = arrayToSet;
12945     function cloneMap(map) {
12946         var clone = ts.createMap();
12947         copyEntries(map, clone);
12948         return clone;
12949     }
12950     ts.cloneMap = cloneMap;
12951     function usingSingleLineStringWriter(action) {
12952         var oldString = stringWriter.getText();
12953         try {
12954             action(stringWriter);
12955             return stringWriter.getText();
12956         }
12957         finally {
12958             stringWriter.clear();
12959             stringWriter.writeKeyword(oldString);
12960         }
12961     }
12962     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
12963     function getFullWidth(node) {
12964         return node.end - node.pos;
12965     }
12966     ts.getFullWidth = getFullWidth;
12967     function getResolvedModule(sourceFile, moduleNameText) {
12968         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
12969     }
12970     ts.getResolvedModule = getResolvedModule;
12971     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
12972         if (!sourceFile.resolvedModules) {
12973             sourceFile.resolvedModules = ts.createMap();
12974         }
12975         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
12976     }
12977     ts.setResolvedModule = setResolvedModule;
12978     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
12979         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
12980             sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
12981         }
12982         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
12983     }
12984     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
12985     function projectReferenceIsEqualTo(oldRef, newRef) {
12986         return oldRef.path === newRef.path &&
12987             !oldRef.prepend === !newRef.prepend &&
12988             !oldRef.circular === !newRef.circular;
12989     }
12990     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
12991     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
12992         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
12993             oldResolution.extension === newResolution.extension &&
12994             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
12995             oldResolution.originalPath === newResolution.originalPath &&
12996             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
12997     }
12998     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
12999     function packageIdIsEqual(a, b) {
13000         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
13001     }
13002     function packageIdToString(_a) {
13003         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
13004         var fullName = subModuleName ? name + "/" + subModuleName : name;
13005         return fullName + "@" + version;
13006     }
13007     ts.packageIdToString = packageIdToString;
13008     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
13009         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
13010     }
13011     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13012     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13013         ts.Debug.assert(names.length === newResolutions.length);
13014         for (var i = 0; i < names.length; i++) {
13015             var newResolution = newResolutions[i];
13016             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13017             var changed = oldResolution
13018                 ? !newResolution || !comparer(oldResolution, newResolution)
13019                 : newResolution;
13020             if (changed) {
13021                 return true;
13022             }
13023         }
13024         return false;
13025     }
13026     ts.hasChangesInResolutions = hasChangesInResolutions;
13027     // Returns true if this node contains a parse error anywhere underneath it.
13028     function containsParseError(node) {
13029         aggregateChildData(node);
13030         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13031     }
13032     ts.containsParseError = containsParseError;
13033     function aggregateChildData(node) {
13034         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13035             // A node is considered to contain a parse error if:
13036             //  a) the parser explicitly marked that it had an error
13037             //  b) any of it's children reported that it had an error.
13038             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13039                 ts.forEachChild(node, containsParseError);
13040             // If so, mark ourselves accordingly.
13041             if (thisNodeOrAnySubNodesHasError) {
13042                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13043             }
13044             // Also mark that we've propagated the child information to this node.  This way we can
13045             // always consult the bit directly on this node without needing to check its children
13046             // again.
13047             node.flags |= 524288 /* HasAggregatedChildData */;
13048         }
13049     }
13050     function getSourceFileOfNode(node) {
13051         while (node && node.kind !== 290 /* SourceFile */) {
13052             node = node.parent;
13053         }
13054         return node;
13055     }
13056     ts.getSourceFileOfNode = getSourceFileOfNode;
13057     function isStatementWithLocals(node) {
13058         switch (node.kind) {
13059             case 223 /* Block */:
13060             case 251 /* CaseBlock */:
13061             case 230 /* ForStatement */:
13062             case 231 /* ForInStatement */:
13063             case 232 /* ForOfStatement */:
13064                 return true;
13065         }
13066         return false;
13067     }
13068     ts.isStatementWithLocals = isStatementWithLocals;
13069     function getStartPositionOfLine(line, sourceFile) {
13070         ts.Debug.assert(line >= 0);
13071         return ts.getLineStarts(sourceFile)[line];
13072     }
13073     ts.getStartPositionOfLine = getStartPositionOfLine;
13074     // This is a useful function for debugging purposes.
13075     function nodePosToString(node) {
13076         var file = getSourceFileOfNode(node);
13077         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13078         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13079     }
13080     ts.nodePosToString = nodePosToString;
13081     function getEndLinePosition(line, sourceFile) {
13082         ts.Debug.assert(line >= 0);
13083         var lineStarts = ts.getLineStarts(sourceFile);
13084         var lineIndex = line;
13085         var sourceText = sourceFile.text;
13086         if (lineIndex + 1 === lineStarts.length) {
13087             // last line - return EOF
13088             return sourceText.length - 1;
13089         }
13090         else {
13091             // current line start
13092             var start = lineStarts[lineIndex];
13093             // take the start position of the next line - 1 = it should be some line break
13094             var pos = lineStarts[lineIndex + 1] - 1;
13095             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13096             // walk backwards skipping line breaks, stop the the beginning of current line.
13097             // i.e:
13098             // <some text>
13099             // $ <- end of line for this position should match the start position
13100             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13101                 pos--;
13102             }
13103             return pos;
13104         }
13105     }
13106     ts.getEndLinePosition = getEndLinePosition;
13107     /**
13108      * Returns a value indicating whether a name is unique globally or within the current file.
13109      * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`.
13110      */
13111     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13112         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13113     }
13114     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13115     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13116     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13117     // in the tree), it is definitely missing. However, a node may be defined, but still be
13118     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13119     // get anything in the source code that it expects at that location. For example:
13120     //
13121     //          let a: ;
13122     //
13123     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13124     // code). So the parser will attempt to parse out a type, and will create an actual node.
13125     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13126     // contained within it.
13127     function nodeIsMissing(node) {
13128         if (node === undefined) {
13129             return true;
13130         }
13131         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13132     }
13133     ts.nodeIsMissing = nodeIsMissing;
13134     function nodeIsPresent(node) {
13135         return !nodeIsMissing(node);
13136     }
13137     ts.nodeIsPresent = nodeIsPresent;
13138     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13139         if (from === undefined || from.length === 0)
13140             return to;
13141         var statementIndex = 0;
13142         // skip all prologue directives to insert at the correct position
13143         for (; statementIndex < to.length; ++statementIndex) {
13144             if (!isPrologueDirective(to[statementIndex])) {
13145                 break;
13146             }
13147         }
13148         to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
13149         return to;
13150     }
13151     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13152         if (statement === undefined)
13153             return to;
13154         var statementIndex = 0;
13155         // skip all prologue directives to insert at the correct position
13156         for (; statementIndex < to.length; ++statementIndex) {
13157             if (!isPrologueDirective(to[statementIndex])) {
13158                 break;
13159             }
13160         }
13161         to.splice(statementIndex, 0, statement);
13162         return to;
13163     }
13164     function isAnyPrologueDirective(node) {
13165         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13166     }
13167     /**
13168      * Prepends statements to an array while taking care of prologue directives.
13169      */
13170     function insertStatementsAfterStandardPrologue(to, from) {
13171         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13172     }
13173     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13174     function insertStatementsAfterCustomPrologue(to, from) {
13175         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13176     }
13177     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13178     /**
13179      * Prepends statements to an array while taking care of prologue directives.
13180      */
13181     function insertStatementAfterStandardPrologue(to, statement) {
13182         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13183     }
13184     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13185     function insertStatementAfterCustomPrologue(to, statement) {
13186         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13187     }
13188     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13189     /**
13190      * Determine if the given comment is a triple-slash
13191      *
13192      * @return true if the comment is a triple-slash comment else false
13193      */
13194     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13195         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13196         // so that we don't end up computing comment string and doing match for all // comments
13197         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13198             commentPos + 2 < commentEnd &&
13199             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13200             var textSubStr = text.substring(commentPos, commentEnd);
13201             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13202                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13203                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13204                 textSubStr.match(defaultLibReferenceRegEx) ?
13205                 true : false;
13206         }
13207         return false;
13208     }
13209     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13210     function isPinnedComment(text, start) {
13211         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13212             text.charCodeAt(start + 2) === 33 /* exclamation */;
13213     }
13214     ts.isPinnedComment = isPinnedComment;
13215     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13216         var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([
13217             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13218             commentDirective,
13219         ]); }));
13220         var usedLines = ts.createMap();
13221         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13222         function getUnusedExpectations() {
13223             return ts.arrayFrom(directivesByLine.entries())
13224                 .filter(function (_a) {
13225                 var line = _a[0], directive = _a[1];
13226                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13227             })
13228                 .map(function (_a) {
13229                 var _ = _a[0], directive = _a[1];
13230                 return directive;
13231             });
13232         }
13233         function markUsed(line) {
13234             if (!directivesByLine.has("" + line)) {
13235                 return false;
13236             }
13237             usedLines.set("" + line, true);
13238             return true;
13239         }
13240     }
13241     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13242     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13243         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13244         // want to skip trivia because this will launch us forward to the next token.
13245         if (nodeIsMissing(node)) {
13246             return node.pos;
13247         }
13248         if (ts.isJSDocNode(node)) {
13249             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13250         }
13251         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13252             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13253         }
13254         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13255         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13256         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13257         // first child to determine the actual position of its first token.
13258         if (node.kind === 324 /* SyntaxList */ && node._children.length > 0) {
13259             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13260         }
13261         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13262     }
13263     ts.getTokenPosOfNode = getTokenPosOfNode;
13264     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13265         if (nodeIsMissing(node) || !node.decorators) {
13266             return getTokenPosOfNode(node, sourceFile);
13267         }
13268         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13269     }
13270     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13271     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13272         if (includeTrivia === void 0) { includeTrivia = false; }
13273         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13274     }
13275     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13276     function isJSDocTypeExpressionOrChild(node) {
13277         return !!findAncestor(node, ts.isJSDocTypeExpression);
13278     }
13279     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13280         if (includeTrivia === void 0) { includeTrivia = false; }
13281         if (nodeIsMissing(node)) {
13282             return "";
13283         }
13284         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13285         if (isJSDocTypeExpressionOrChild(node)) {
13286             // strip space + asterisk at line start
13287             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13288         }
13289         return text;
13290     }
13291     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13292     function getTextOfNode(node, includeTrivia) {
13293         if (includeTrivia === void 0) { includeTrivia = false; }
13294         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13295     }
13296     ts.getTextOfNode = getTextOfNode;
13297     function getPos(range) {
13298         return range.pos;
13299     }
13300     /**
13301      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13302      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13303      */
13304     function indexOfNode(nodeArray, node) {
13305         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13306     }
13307     ts.indexOfNode = indexOfNode;
13308     /**
13309      * Gets flags that control emit behavior of a node.
13310      */
13311     function getEmitFlags(node) {
13312         var emitNode = node.emitNode;
13313         return emitNode && emitNode.flags || 0;
13314     }
13315     ts.getEmitFlags = getEmitFlags;
13316     function getLiteralText(node, sourceFile, neverAsciiEscape, jsxAttributeEscape) {
13317         // If we don't need to downlevel and we can reach the original source text using
13318         // the node's parent reference, then simply get the text as it was originally written.
13319         if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13320             ts.isBigIntLiteral(node))) {
13321             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13322         }
13323         // If we can't reach the original source text, use the canonical form if it's a number,
13324         // or a (possibly escaped) quoted form of the original text if it's string-like.
13325         switch (node.kind) {
13326             case 10 /* StringLiteral */: {
13327                 var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
13328                     neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13329                         escapeNonAsciiString;
13330                 if (node.singleQuote) {
13331                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13332                 }
13333                 else {
13334                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13335                 }
13336             }
13337             case 14 /* NoSubstitutionTemplateLiteral */:
13338             case 15 /* TemplateHead */:
13339             case 16 /* TemplateMiddle */:
13340             case 17 /* TemplateTail */: {
13341                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13342                 // had to include a backslash: `not \${a} substitution`.
13343                 var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13344                     escapeNonAsciiString;
13345                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13346                 switch (node.kind) {
13347                     case 14 /* NoSubstitutionTemplateLiteral */:
13348                         return "`" + rawText + "`";
13349                     case 15 /* TemplateHead */:
13350                         return "`" + rawText + "${";
13351                     case 16 /* TemplateMiddle */:
13352                         return "}" + rawText + "${";
13353                     case 17 /* TemplateTail */:
13354                         return "}" + rawText + "`";
13355                 }
13356                 break;
13357             }
13358             case 8 /* NumericLiteral */:
13359             case 9 /* BigIntLiteral */:
13360             case 13 /* RegularExpressionLiteral */:
13361                 return node.text;
13362         }
13363         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13364     }
13365     ts.getLiteralText = getLiteralText;
13366     function getTextOfConstantValue(value) {
13367         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13368     }
13369     ts.getTextOfConstantValue = getTextOfConstantValue;
13370     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13371     // all non-alphanumeric characters with underscores
13372     function makeIdentifierFromModuleName(moduleName) {
13373         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13374     }
13375     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13376     function isBlockOrCatchScoped(declaration) {
13377         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13378             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13379     }
13380     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13381     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13382         var node = getRootDeclaration(declaration);
13383         return node.kind === 242 /* VariableDeclaration */ && node.parent.kind === 280 /* CatchClause */;
13384     }
13385     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13386     function isAmbientModule(node) {
13387         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13388     }
13389     ts.isAmbientModule = isAmbientModule;
13390     function isModuleWithStringLiteralName(node) {
13391         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13392     }
13393     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13394     function isNonGlobalAmbientModule(node) {
13395         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13396     }
13397     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13398     /**
13399      * An effective module (namespace) declaration is either
13400      * 1. An actual declaration: namespace X { ... }
13401      * 2. A Javascript declaration, which is:
13402      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13403      */
13404     function isEffectiveModuleDeclaration(node) {
13405         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13406     }
13407     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13408     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13409     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13410         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13411     }
13412     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13413     function isShorthandAmbientModule(node) {
13414         // The only kind of module that can be missing a body is a shorthand ambient module.
13415         return node && node.kind === 249 /* ModuleDeclaration */ && (!node.body);
13416     }
13417     function isBlockScopedContainerTopLevel(node) {
13418         return node.kind === 290 /* SourceFile */ ||
13419             node.kind === 249 /* ModuleDeclaration */ ||
13420             ts.isFunctionLike(node);
13421     }
13422     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13423     function isGlobalScopeAugmentation(module) {
13424         return !!(module.flags & 1024 /* GlobalAugmentation */);
13425     }
13426     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13427     function isExternalModuleAugmentation(node) {
13428         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13429     }
13430     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13431     function isModuleAugmentationExternal(node) {
13432         // external module augmentation is a ambient module declaration that is either:
13433         // - defined in the top level scope and source file is an external module
13434         // - defined inside ambient module declaration located in the top level scope and source file not an external module
13435         switch (node.parent.kind) {
13436             case 290 /* SourceFile */:
13437                 return ts.isExternalModule(node.parent);
13438             case 250 /* ModuleBlock */:
13439                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13440         }
13441         return false;
13442     }
13443     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13444     function getNonAugmentationDeclaration(symbol) {
13445         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13446     }
13447     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13448     function isEffectiveExternalModule(node, compilerOptions) {
13449         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13450     }
13451     ts.isEffectiveExternalModule = isEffectiveExternalModule;
13452     /**
13453      * Returns whether the source file will be treated as if it were in strict mode at runtime.
13454      */
13455     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13456         // We can only verify strict mode for JS/TS files
13457         switch (node.scriptKind) {
13458             case 1 /* JS */:
13459             case 3 /* TS */:
13460             case 2 /* JSX */:
13461             case 4 /* TSX */:
13462                 break;
13463             default:
13464                 return false;
13465         }
13466         // Strict mode does not matter for declaration files.
13467         if (node.isDeclarationFile) {
13468             return false;
13469         }
13470         // If `alwaysStrict` is set, then treat the file as strict.
13471         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13472             return true;
13473         }
13474         // Starting with a "use strict" directive indicates the file is strict.
13475         if (ts.startsWithUseStrict(node.statements)) {
13476             return true;
13477         }
13478         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13479             // ECMAScript Modules are always strict.
13480             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13481                 return true;
13482             }
13483             // Other modules are strict unless otherwise specified.
13484             return !compilerOptions.noImplicitUseStrict;
13485         }
13486         return false;
13487     }
13488     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13489     function isBlockScope(node, parentNode) {
13490         switch (node.kind) {
13491             case 290 /* SourceFile */:
13492             case 251 /* CaseBlock */:
13493             case 280 /* CatchClause */:
13494             case 249 /* ModuleDeclaration */:
13495             case 230 /* ForStatement */:
13496             case 231 /* ForInStatement */:
13497             case 232 /* ForOfStatement */:
13498             case 162 /* Constructor */:
13499             case 161 /* MethodDeclaration */:
13500             case 163 /* GetAccessor */:
13501             case 164 /* SetAccessor */:
13502             case 244 /* FunctionDeclaration */:
13503             case 201 /* FunctionExpression */:
13504             case 202 /* ArrowFunction */:
13505                 return true;
13506             case 223 /* Block */:
13507                 // function block is not considered block-scope container
13508                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13509                 return !ts.isFunctionLike(parentNode);
13510         }
13511         return false;
13512     }
13513     ts.isBlockScope = isBlockScope;
13514     function isDeclarationWithTypeParameters(node) {
13515         switch (node.kind) {
13516             case 315 /* JSDocCallbackTag */:
13517             case 322 /* JSDocTypedefTag */:
13518             case 305 /* JSDocSignature */:
13519                 return true;
13520             default:
13521                 ts.assertType(node);
13522                 return isDeclarationWithTypeParameterChildren(node);
13523         }
13524     }
13525     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13526     function isDeclarationWithTypeParameterChildren(node) {
13527         switch (node.kind) {
13528             case 165 /* CallSignature */:
13529             case 166 /* ConstructSignature */:
13530             case 160 /* MethodSignature */:
13531             case 167 /* IndexSignature */:
13532             case 170 /* FunctionType */:
13533             case 171 /* ConstructorType */:
13534             case 300 /* JSDocFunctionType */:
13535             case 245 /* ClassDeclaration */:
13536             case 214 /* ClassExpression */:
13537             case 246 /* InterfaceDeclaration */:
13538             case 247 /* TypeAliasDeclaration */:
13539             case 321 /* JSDocTemplateTag */:
13540             case 244 /* FunctionDeclaration */:
13541             case 161 /* MethodDeclaration */:
13542             case 162 /* Constructor */:
13543             case 163 /* GetAccessor */:
13544             case 164 /* SetAccessor */:
13545             case 201 /* FunctionExpression */:
13546             case 202 /* ArrowFunction */:
13547                 return true;
13548             default:
13549                 ts.assertType(node);
13550                 return false;
13551         }
13552     }
13553     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13554     function isAnyImportSyntax(node) {
13555         switch (node.kind) {
13556             case 254 /* ImportDeclaration */:
13557             case 253 /* ImportEqualsDeclaration */:
13558                 return true;
13559             default:
13560                 return false;
13561         }
13562     }
13563     ts.isAnyImportSyntax = isAnyImportSyntax;
13564     function isLateVisibilityPaintedStatement(node) {
13565         switch (node.kind) {
13566             case 254 /* ImportDeclaration */:
13567             case 253 /* ImportEqualsDeclaration */:
13568             case 225 /* VariableStatement */:
13569             case 245 /* ClassDeclaration */:
13570             case 244 /* FunctionDeclaration */:
13571             case 249 /* ModuleDeclaration */:
13572             case 247 /* TypeAliasDeclaration */:
13573             case 246 /* InterfaceDeclaration */:
13574             case 248 /* EnumDeclaration */:
13575                 return true;
13576             default:
13577                 return false;
13578         }
13579     }
13580     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13581     function isAnyImportOrReExport(node) {
13582         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13583     }
13584     ts.isAnyImportOrReExport = isAnyImportOrReExport;
13585     // Gets the nearest enclosing block scope container that has the provided node
13586     // as a descendant, that is not the provided node.
13587     function getEnclosingBlockScopeContainer(node) {
13588         return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13589     }
13590     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13591     // Return display name of an identifier
13592     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13593     // text of the expression in the computed property.
13594     function declarationNameToString(name) {
13595         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13596     }
13597     ts.declarationNameToString = declarationNameToString;
13598     function getNameFromIndexInfo(info) {
13599         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13600     }
13601     ts.getNameFromIndexInfo = getNameFromIndexInfo;
13602     function isComputedNonLiteralName(name) {
13603         return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13604     }
13605     ts.isComputedNonLiteralName = isComputedNonLiteralName;
13606     function getTextOfPropertyName(name) {
13607         switch (name.kind) {
13608             case 75 /* Identifier */:
13609             case 76 /* PrivateIdentifier */:
13610                 return name.escapedText;
13611             case 10 /* StringLiteral */:
13612             case 8 /* NumericLiteral */:
13613             case 14 /* NoSubstitutionTemplateLiteral */:
13614                 return ts.escapeLeadingUnderscores(name.text);
13615             case 154 /* ComputedPropertyName */:
13616                 if (isStringOrNumericLiteralLike(name.expression))
13617                     return ts.escapeLeadingUnderscores(name.expression.text);
13618                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13619             default:
13620                 return ts.Debug.assertNever(name);
13621         }
13622     }
13623     ts.getTextOfPropertyName = getTextOfPropertyName;
13624     function entityNameToString(name) {
13625         switch (name.kind) {
13626             case 104 /* ThisKeyword */:
13627                 return "this";
13628             case 76 /* PrivateIdentifier */:
13629             case 75 /* Identifier */:
13630                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13631             case 153 /* QualifiedName */:
13632                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13633             case 194 /* PropertyAccessExpression */:
13634                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13635                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13636                 }
13637                 else {
13638                     return ts.Debug.assertNever(name.name);
13639                 }
13640             default:
13641                 return ts.Debug.assertNever(name);
13642         }
13643     }
13644     ts.entityNameToString = entityNameToString;
13645     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
13646         var sourceFile = getSourceFileOfNode(node);
13647         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
13648     }
13649     ts.createDiagnosticForNode = createDiagnosticForNode;
13650     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
13651         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
13652         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
13653     }
13654     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
13655     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
13656         var span = getErrorSpanForNode(sourceFile, node);
13657         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
13658     }
13659     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
13660     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
13661         var sourceFile = getSourceFileOfNode(node);
13662         var span = getErrorSpanForNode(sourceFile, node);
13663         return {
13664             file: sourceFile,
13665             start: span.start,
13666             length: span.length,
13667             code: messageChain.code,
13668             category: messageChain.category,
13669             messageText: messageChain.next ? messageChain : messageChain.messageText,
13670             relatedInformation: relatedInformation
13671         };
13672     }
13673     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
13674     function createDiagnosticForRange(sourceFile, range, message) {
13675         return {
13676             file: sourceFile,
13677             start: range.pos,
13678             length: range.end - range.pos,
13679             code: message.code,
13680             category: message.category,
13681             messageText: message.message,
13682         };
13683     }
13684     ts.createDiagnosticForRange = createDiagnosticForRange;
13685     function getSpanOfTokenAtPosition(sourceFile, pos) {
13686         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
13687         scanner.scan();
13688         var start = scanner.getTokenPos();
13689         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
13690     }
13691     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
13692     function getErrorSpanForArrowFunction(sourceFile, node) {
13693         var pos = ts.skipTrivia(sourceFile.text, node.pos);
13694         if (node.body && node.body.kind === 223 /* Block */) {
13695             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
13696             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
13697             if (startLine < endLine) {
13698                 // The arrow function spans multiple lines,
13699                 // make the error span be the first line, inclusive.
13700                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
13701             }
13702         }
13703         return ts.createTextSpanFromBounds(pos, node.end);
13704     }
13705     function getErrorSpanForNode(sourceFile, node) {
13706         var errorNode = node;
13707         switch (node.kind) {
13708             case 290 /* SourceFile */:
13709                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
13710                 if (pos_1 === sourceFile.text.length) {
13711                     // file is empty - return span for the beginning of the file
13712                     return ts.createTextSpan(0, 0);
13713                 }
13714                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
13715             // This list is a work in progress. Add missing node kinds to improve their error
13716             // spans.
13717             case 242 /* VariableDeclaration */:
13718             case 191 /* BindingElement */:
13719             case 245 /* ClassDeclaration */:
13720             case 214 /* ClassExpression */:
13721             case 246 /* InterfaceDeclaration */:
13722             case 249 /* ModuleDeclaration */:
13723             case 248 /* EnumDeclaration */:
13724             case 284 /* EnumMember */:
13725             case 244 /* FunctionDeclaration */:
13726             case 201 /* FunctionExpression */:
13727             case 161 /* MethodDeclaration */:
13728             case 163 /* GetAccessor */:
13729             case 164 /* SetAccessor */:
13730             case 247 /* TypeAliasDeclaration */:
13731             case 159 /* PropertyDeclaration */:
13732             case 158 /* PropertySignature */:
13733                 errorNode = node.name;
13734                 break;
13735             case 202 /* ArrowFunction */:
13736                 return getErrorSpanForArrowFunction(sourceFile, node);
13737             case 277 /* CaseClause */:
13738             case 278 /* DefaultClause */:
13739                 var start = ts.skipTrivia(sourceFile.text, node.pos);
13740                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
13741                 return ts.createTextSpanFromBounds(start, end);
13742         }
13743         if (errorNode === undefined) {
13744             // If we don't have a better node, then just set the error on the first token of
13745             // construct.
13746             return getSpanOfTokenAtPosition(sourceFile, node.pos);
13747         }
13748         ts.Debug.assert(!ts.isJSDoc(errorNode));
13749         var isMissing = nodeIsMissing(errorNode);
13750         var pos = isMissing || ts.isJsxText(node)
13751             ? errorNode.pos
13752             : ts.skipTrivia(sourceFile.text, errorNode.pos);
13753         // These asserts should all be satisfied for a properly constructed `errorNode`.
13754         if (isMissing) {
13755             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13756             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13757         }
13758         else {
13759             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13760             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13761         }
13762         return ts.createTextSpanFromBounds(pos, errorNode.end);
13763     }
13764     ts.getErrorSpanForNode = getErrorSpanForNode;
13765     function isExternalOrCommonJsModule(file) {
13766         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
13767     }
13768     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
13769     function isJsonSourceFile(file) {
13770         return file.scriptKind === 6 /* JSON */;
13771     }
13772     ts.isJsonSourceFile = isJsonSourceFile;
13773     function isEnumConst(node) {
13774         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
13775     }
13776     ts.isEnumConst = isEnumConst;
13777     function isDeclarationReadonly(declaration) {
13778         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
13779     }
13780     ts.isDeclarationReadonly = isDeclarationReadonly;
13781     function isVarConst(node) {
13782         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
13783     }
13784     ts.isVarConst = isVarConst;
13785     function isLet(node) {
13786         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
13787     }
13788     ts.isLet = isLet;
13789     function isSuperCall(n) {
13790         return n.kind === 196 /* CallExpression */ && n.expression.kind === 102 /* SuperKeyword */;
13791     }
13792     ts.isSuperCall = isSuperCall;
13793     function isImportCall(n) {
13794         return n.kind === 196 /* CallExpression */ && n.expression.kind === 96 /* ImportKeyword */;
13795     }
13796     ts.isImportCall = isImportCall;
13797     function isImportMeta(n) {
13798         return ts.isMetaProperty(n)
13799             && n.keywordToken === 96 /* ImportKeyword */
13800             && n.name.escapedText === "meta";
13801     }
13802     ts.isImportMeta = isImportMeta;
13803     function isLiteralImportTypeNode(n) {
13804         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
13805     }
13806     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
13807     function isPrologueDirective(node) {
13808         return node.kind === 226 /* ExpressionStatement */
13809             && node.expression.kind === 10 /* StringLiteral */;
13810     }
13811     ts.isPrologueDirective = isPrologueDirective;
13812     function isCustomPrologue(node) {
13813         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13814     }
13815     ts.isCustomPrologue = isCustomPrologue;
13816     function isHoistedFunction(node) {
13817         return isCustomPrologue(node)
13818             && ts.isFunctionDeclaration(node);
13819     }
13820     ts.isHoistedFunction = isHoistedFunction;
13821     function isHoistedVariable(node) {
13822         return ts.isIdentifier(node.name)
13823             && !node.initializer;
13824     }
13825     function isHoistedVariableStatement(node) {
13826         return isCustomPrologue(node)
13827             && ts.isVariableStatement(node)
13828             && ts.every(node.declarationList.declarations, isHoistedVariable);
13829     }
13830     ts.isHoistedVariableStatement = isHoistedVariableStatement;
13831     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
13832         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
13833     }
13834     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
13835     function getJSDocCommentRanges(node, text) {
13836         var commentRanges = (node.kind === 156 /* Parameter */ ||
13837             node.kind === 155 /* TypeParameter */ ||
13838             node.kind === 201 /* FunctionExpression */ ||
13839             node.kind === 202 /* ArrowFunction */ ||
13840             node.kind === 200 /* ParenthesizedExpression */) ?
13841             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
13842             ts.getLeadingCommentRanges(text, node.pos);
13843         // True if the comment starts with '/**' but not if it is '/**/'
13844         return ts.filter(commentRanges, function (comment) {
13845             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
13846                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
13847                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
13848         });
13849     }
13850     ts.getJSDocCommentRanges = getJSDocCommentRanges;
13851     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13852     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
13853     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13854     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
13855     function isPartOfTypeNode(node) {
13856         if (168 /* FirstTypeNode */ <= node.kind && node.kind <= 188 /* LastTypeNode */) {
13857             return true;
13858         }
13859         switch (node.kind) {
13860             case 125 /* AnyKeyword */:
13861             case 148 /* UnknownKeyword */:
13862             case 140 /* NumberKeyword */:
13863             case 151 /* BigIntKeyword */:
13864             case 143 /* StringKeyword */:
13865             case 128 /* BooleanKeyword */:
13866             case 144 /* SymbolKeyword */:
13867             case 141 /* ObjectKeyword */:
13868             case 146 /* UndefinedKeyword */:
13869             case 137 /* NeverKeyword */:
13870                 return true;
13871             case 110 /* VoidKeyword */:
13872                 return node.parent.kind !== 205 /* VoidExpression */;
13873             case 216 /* ExpressionWithTypeArguments */:
13874                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
13875             case 155 /* TypeParameter */:
13876                 return node.parent.kind === 186 /* MappedType */ || node.parent.kind === 181 /* InferType */;
13877             // Identifiers and qualified names may be type nodes, depending on their context. Climb
13878             // above them to find the lowest container
13879             case 75 /* Identifier */:
13880                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
13881                 if (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) {
13882                     node = node.parent;
13883                 }
13884                 else if (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node) {
13885                     node = node.parent;
13886                 }
13887                 // At this point, node is either a qualified name or an identifier
13888                 ts.Debug.assert(node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */ || node.kind === 194 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
13889             // falls through
13890             case 153 /* QualifiedName */:
13891             case 194 /* PropertyAccessExpression */:
13892             case 104 /* ThisKeyword */: {
13893                 var parent = node.parent;
13894                 if (parent.kind === 172 /* TypeQuery */) {
13895                     return false;
13896                 }
13897                 if (parent.kind === 188 /* ImportType */) {
13898                     return !parent.isTypeOf;
13899                 }
13900                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
13901                 //
13902                 //     let a: A.B.C;
13903                 //
13904                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
13905                 // Only C and A.B.C are type nodes.
13906                 if (168 /* FirstTypeNode */ <= parent.kind && parent.kind <= 188 /* LastTypeNode */) {
13907                     return true;
13908                 }
13909                 switch (parent.kind) {
13910                     case 216 /* ExpressionWithTypeArguments */:
13911                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
13912                     case 155 /* TypeParameter */:
13913                         return node === parent.constraint;
13914                     case 321 /* JSDocTemplateTag */:
13915                         return node === parent.constraint;
13916                     case 159 /* PropertyDeclaration */:
13917                     case 158 /* PropertySignature */:
13918                     case 156 /* Parameter */:
13919                     case 242 /* VariableDeclaration */:
13920                         return node === parent.type;
13921                     case 244 /* FunctionDeclaration */:
13922                     case 201 /* FunctionExpression */:
13923                     case 202 /* ArrowFunction */:
13924                     case 162 /* Constructor */:
13925                     case 161 /* MethodDeclaration */:
13926                     case 160 /* MethodSignature */:
13927                     case 163 /* GetAccessor */:
13928                     case 164 /* SetAccessor */:
13929                         return node === parent.type;
13930                     case 165 /* CallSignature */:
13931                     case 166 /* ConstructSignature */:
13932                     case 167 /* IndexSignature */:
13933                         return node === parent.type;
13934                     case 199 /* TypeAssertionExpression */:
13935                         return node === parent.type;
13936                     case 196 /* CallExpression */:
13937                     case 197 /* NewExpression */:
13938                         return ts.contains(parent.typeArguments, node);
13939                     case 198 /* TaggedTemplateExpression */:
13940                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
13941                         return false;
13942                 }
13943             }
13944         }
13945         return false;
13946     }
13947     ts.isPartOfTypeNode = isPartOfTypeNode;
13948     function isChildOfNodeWithKind(node, kind) {
13949         while (node) {
13950             if (node.kind === kind) {
13951                 return true;
13952             }
13953             node = node.parent;
13954         }
13955         return false;
13956     }
13957     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
13958     // Warning: This has the same semantics as the forEach family of functions,
13959     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
13960     function forEachReturnStatement(body, visitor) {
13961         return traverse(body);
13962         function traverse(node) {
13963             switch (node.kind) {
13964                 case 235 /* ReturnStatement */:
13965                     return visitor(node);
13966                 case 251 /* CaseBlock */:
13967                 case 223 /* Block */:
13968                 case 227 /* IfStatement */:
13969                 case 228 /* DoStatement */:
13970                 case 229 /* WhileStatement */:
13971                 case 230 /* ForStatement */:
13972                 case 231 /* ForInStatement */:
13973                 case 232 /* ForOfStatement */:
13974                 case 236 /* WithStatement */:
13975                 case 237 /* SwitchStatement */:
13976                 case 277 /* CaseClause */:
13977                 case 278 /* DefaultClause */:
13978                 case 238 /* LabeledStatement */:
13979                 case 240 /* TryStatement */:
13980                 case 280 /* CatchClause */:
13981                     return ts.forEachChild(node, traverse);
13982             }
13983         }
13984     }
13985     ts.forEachReturnStatement = forEachReturnStatement;
13986     function forEachYieldExpression(body, visitor) {
13987         return traverse(body);
13988         function traverse(node) {
13989             switch (node.kind) {
13990                 case 212 /* YieldExpression */:
13991                     visitor(node);
13992                     var operand = node.expression;
13993                     if (operand) {
13994                         traverse(operand);
13995                     }
13996                     return;
13997                 case 248 /* EnumDeclaration */:
13998                 case 246 /* InterfaceDeclaration */:
13999                 case 249 /* ModuleDeclaration */:
14000                 case 247 /* TypeAliasDeclaration */:
14001                     // These are not allowed inside a generator now, but eventually they may be allowed
14002                     // as local types. Regardless, skip them to avoid the work.
14003                     return;
14004                 default:
14005                     if (ts.isFunctionLike(node)) {
14006                         if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
14007                             // Note that we will not include methods/accessors of a class because they would require
14008                             // first descending into the class. This is by design.
14009                             traverse(node.name.expression);
14010                             return;
14011                         }
14012                     }
14013                     else if (!isPartOfTypeNode(node)) {
14014                         // This is the general case, which should include mostly expressions and statements.
14015                         // Also includes NodeArrays.
14016                         ts.forEachChild(node, traverse);
14017                     }
14018             }
14019         }
14020     }
14021     ts.forEachYieldExpression = forEachYieldExpression;
14022     /**
14023      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14024      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14025      *
14026      * @param node The type node.
14027      */
14028     function getRestParameterElementType(node) {
14029         if (node && node.kind === 174 /* ArrayType */) {
14030             return node.elementType;
14031         }
14032         else if (node && node.kind === 169 /* TypeReference */) {
14033             return ts.singleOrUndefined(node.typeArguments);
14034         }
14035         else {
14036             return undefined;
14037         }
14038     }
14039     ts.getRestParameterElementType = getRestParameterElementType;
14040     function getMembersOfDeclaration(node) {
14041         switch (node.kind) {
14042             case 246 /* InterfaceDeclaration */:
14043             case 245 /* ClassDeclaration */:
14044             case 214 /* ClassExpression */:
14045             case 173 /* TypeLiteral */:
14046                 return node.members;
14047             case 193 /* ObjectLiteralExpression */:
14048                 return node.properties;
14049         }
14050     }
14051     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14052     function isVariableLike(node) {
14053         if (node) {
14054             switch (node.kind) {
14055                 case 191 /* BindingElement */:
14056                 case 284 /* EnumMember */:
14057                 case 156 /* Parameter */:
14058                 case 281 /* PropertyAssignment */:
14059                 case 159 /* PropertyDeclaration */:
14060                 case 158 /* PropertySignature */:
14061                 case 282 /* ShorthandPropertyAssignment */:
14062                 case 242 /* VariableDeclaration */:
14063                     return true;
14064             }
14065         }
14066         return false;
14067     }
14068     ts.isVariableLike = isVariableLike;
14069     function isVariableLikeOrAccessor(node) {
14070         return isVariableLike(node) || ts.isAccessor(node);
14071     }
14072     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14073     function isVariableDeclarationInVariableStatement(node) {
14074         return node.parent.kind === 243 /* VariableDeclarationList */
14075             && node.parent.parent.kind === 225 /* VariableStatement */;
14076     }
14077     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14078     function isValidESSymbolDeclaration(node) {
14079         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14080             ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
14081                 ts.isPropertySignature(node) && hasReadonlyModifier(node);
14082     }
14083     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14084     function introducesArgumentsExoticObject(node) {
14085         switch (node.kind) {
14086             case 161 /* MethodDeclaration */:
14087             case 160 /* MethodSignature */:
14088             case 162 /* Constructor */:
14089             case 163 /* GetAccessor */:
14090             case 164 /* SetAccessor */:
14091             case 244 /* FunctionDeclaration */:
14092             case 201 /* FunctionExpression */:
14093                 return true;
14094         }
14095         return false;
14096     }
14097     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14098     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14099         while (true) {
14100             if (beforeUnwrapLabelCallback) {
14101                 beforeUnwrapLabelCallback(node);
14102             }
14103             if (node.statement.kind !== 238 /* LabeledStatement */) {
14104                 return node.statement;
14105             }
14106             node = node.statement;
14107         }
14108     }
14109     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14110     function isFunctionBlock(node) {
14111         return node && node.kind === 223 /* Block */ && ts.isFunctionLike(node.parent);
14112     }
14113     ts.isFunctionBlock = isFunctionBlock;
14114     function isObjectLiteralMethod(node) {
14115         return node && node.kind === 161 /* MethodDeclaration */ && node.parent.kind === 193 /* ObjectLiteralExpression */;
14116     }
14117     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14118     function isObjectLiteralOrClassExpressionMethod(node) {
14119         return node.kind === 161 /* MethodDeclaration */ &&
14120             (node.parent.kind === 193 /* ObjectLiteralExpression */ ||
14121                 node.parent.kind === 214 /* ClassExpression */);
14122     }
14123     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14124     function isIdentifierTypePredicate(predicate) {
14125         return predicate && predicate.kind === 1 /* Identifier */;
14126     }
14127     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14128     function isThisTypePredicate(predicate) {
14129         return predicate && predicate.kind === 0 /* This */;
14130     }
14131     ts.isThisTypePredicate = isThisTypePredicate;
14132     function getPropertyAssignment(objectLiteral, key, key2) {
14133         return objectLiteral.properties.filter(function (property) {
14134             if (property.kind === 281 /* PropertyAssignment */) {
14135                 var propName = getTextOfPropertyName(property.name);
14136                 return key === propName || (!!key2 && key2 === propName);
14137             }
14138             return false;
14139         });
14140     }
14141     ts.getPropertyAssignment = getPropertyAssignment;
14142     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14143         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14144             var expression = tsConfigSourceFile.statements[0].expression;
14145             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14146         }
14147     }
14148     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14149     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14150         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14151             return ts.isArrayLiteralExpression(property.initializer) ?
14152                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14153                 undefined;
14154         });
14155     }
14156     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14157     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14158         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14159         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14160     }
14161     ts.getTsConfigPropArray = getTsConfigPropArray;
14162     function getContainingFunction(node) {
14163         return findAncestor(node.parent, ts.isFunctionLike);
14164     }
14165     ts.getContainingFunction = getContainingFunction;
14166     function getContainingFunctionDeclaration(node) {
14167         return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14168     }
14169     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14170     function getContainingClass(node) {
14171         return findAncestor(node.parent, ts.isClassLike);
14172     }
14173     ts.getContainingClass = getContainingClass;
14174     function getThisContainer(node, includeArrowFunctions) {
14175         ts.Debug.assert(node.kind !== 290 /* SourceFile */);
14176         while (true) {
14177             node = node.parent;
14178             if (!node) {
14179                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14180             }
14181             switch (node.kind) {
14182                 case 154 /* ComputedPropertyName */:
14183                     // If the grandparent node is an object literal (as opposed to a class),
14184                     // then the computed property is not a 'this' container.
14185                     // A computed property name in a class needs to be a this container
14186                     // so that we can error on it.
14187                     if (ts.isClassLike(node.parent.parent)) {
14188                         return node;
14189                     }
14190                     // If this is a computed property, then the parent should not
14191                     // make it a this container. The parent might be a property
14192                     // in an object literal, like a method or accessor. But in order for
14193                     // such a parent to be a this container, the reference must be in
14194                     // the *body* of the container.
14195                     node = node.parent;
14196                     break;
14197                 case 157 /* Decorator */:
14198                     // Decorators are always applied outside of the body of a class or method.
14199                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14200                         // If the decorator's parent is a Parameter, we resolve the this container from
14201                         // the grandparent class declaration.
14202                         node = node.parent.parent;
14203                     }
14204                     else if (ts.isClassElement(node.parent)) {
14205                         // If the decorator's parent is a class element, we resolve the 'this' container
14206                         // from the parent class declaration.
14207                         node = node.parent;
14208                     }
14209                     break;
14210                 case 202 /* ArrowFunction */:
14211                     if (!includeArrowFunctions) {
14212                         continue;
14213                     }
14214                 // falls through
14215                 case 244 /* FunctionDeclaration */:
14216                 case 201 /* FunctionExpression */:
14217                 case 249 /* ModuleDeclaration */:
14218                 case 159 /* PropertyDeclaration */:
14219                 case 158 /* PropertySignature */:
14220                 case 161 /* MethodDeclaration */:
14221                 case 160 /* MethodSignature */:
14222                 case 162 /* Constructor */:
14223                 case 163 /* GetAccessor */:
14224                 case 164 /* SetAccessor */:
14225                 case 165 /* CallSignature */:
14226                 case 166 /* ConstructSignature */:
14227                 case 167 /* IndexSignature */:
14228                 case 248 /* EnumDeclaration */:
14229                 case 290 /* SourceFile */:
14230                     return node;
14231             }
14232         }
14233     }
14234     ts.getThisContainer = getThisContainer;
14235     function getNewTargetContainer(node) {
14236         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14237         if (container) {
14238             switch (container.kind) {
14239                 case 162 /* Constructor */:
14240                 case 244 /* FunctionDeclaration */:
14241                 case 201 /* FunctionExpression */:
14242                     return container;
14243             }
14244         }
14245         return undefined;
14246     }
14247     ts.getNewTargetContainer = getNewTargetContainer;
14248     /**
14249      * Given an super call/property node, returns the closest node where
14250      * - a super call/property access is legal in the node and not legal in the parent node the node.
14251      *   i.e. super call is legal in constructor but not legal in the class body.
14252      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14253      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14254      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14255      */
14256     function getSuperContainer(node, stopOnFunctions) {
14257         while (true) {
14258             node = node.parent;
14259             if (!node) {
14260                 return node;
14261             }
14262             switch (node.kind) {
14263                 case 154 /* ComputedPropertyName */:
14264                     node = node.parent;
14265                     break;
14266                 case 244 /* FunctionDeclaration */:
14267                 case 201 /* FunctionExpression */:
14268                 case 202 /* ArrowFunction */:
14269                     if (!stopOnFunctions) {
14270                         continue;
14271                     }
14272                 // falls through
14273                 case 159 /* PropertyDeclaration */:
14274                 case 158 /* PropertySignature */:
14275                 case 161 /* MethodDeclaration */:
14276                 case 160 /* MethodSignature */:
14277                 case 162 /* Constructor */:
14278                 case 163 /* GetAccessor */:
14279                 case 164 /* SetAccessor */:
14280                     return node;
14281                 case 157 /* Decorator */:
14282                     // Decorators are always applied outside of the body of a class or method.
14283                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14284                         // If the decorator's parent is a Parameter, we resolve the this container from
14285                         // the grandparent class declaration.
14286                         node = node.parent.parent;
14287                     }
14288                     else if (ts.isClassElement(node.parent)) {
14289                         // If the decorator's parent is a class element, we resolve the 'this' container
14290                         // from the parent class declaration.
14291                         node = node.parent;
14292                     }
14293                     break;
14294             }
14295         }
14296     }
14297     ts.getSuperContainer = getSuperContainer;
14298     function getImmediatelyInvokedFunctionExpression(func) {
14299         if (func.kind === 201 /* FunctionExpression */ || func.kind === 202 /* ArrowFunction */) {
14300             var prev = func;
14301             var parent = func.parent;
14302             while (parent.kind === 200 /* ParenthesizedExpression */) {
14303                 prev = parent;
14304                 parent = parent.parent;
14305             }
14306             if (parent.kind === 196 /* CallExpression */ && parent.expression === prev) {
14307                 return parent;
14308             }
14309         }
14310     }
14311     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14312     function isSuperOrSuperProperty(node) {
14313         return node.kind === 102 /* SuperKeyword */
14314             || isSuperProperty(node);
14315     }
14316     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14317     /**
14318      * Determines whether a node is a property or element access expression for `super`.
14319      */
14320     function isSuperProperty(node) {
14321         var kind = node.kind;
14322         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14323             && node.expression.kind === 102 /* SuperKeyword */;
14324     }
14325     ts.isSuperProperty = isSuperProperty;
14326     /**
14327      * Determines whether a node is a property or element access expression for `this`.
14328      */
14329     function isThisProperty(node) {
14330         var kind = node.kind;
14331         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14332             && node.expression.kind === 104 /* ThisKeyword */;
14333     }
14334     ts.isThisProperty = isThisProperty;
14335     function getEntityNameFromTypeNode(node) {
14336         switch (node.kind) {
14337             case 169 /* TypeReference */:
14338                 return node.typeName;
14339             case 216 /* ExpressionWithTypeArguments */:
14340                 return isEntityNameExpression(node.expression)
14341                     ? node.expression
14342                     : undefined;
14343             case 75 /* Identifier */:
14344             case 153 /* QualifiedName */:
14345                 return node;
14346         }
14347         return undefined;
14348     }
14349     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14350     function getInvokedExpression(node) {
14351         switch (node.kind) {
14352             case 198 /* TaggedTemplateExpression */:
14353                 return node.tag;
14354             case 268 /* JsxOpeningElement */:
14355             case 267 /* JsxSelfClosingElement */:
14356                 return node.tagName;
14357             default:
14358                 return node.expression;
14359         }
14360     }
14361     ts.getInvokedExpression = getInvokedExpression;
14362     function nodeCanBeDecorated(node, parent, grandparent) {
14363         // private names cannot be used with decorators yet
14364         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14365             return false;
14366         }
14367         switch (node.kind) {
14368             case 245 /* ClassDeclaration */:
14369                 // classes are valid targets
14370                 return true;
14371             case 159 /* PropertyDeclaration */:
14372                 // property declarations are valid if their parent is a class declaration.
14373                 return parent.kind === 245 /* ClassDeclaration */;
14374             case 163 /* GetAccessor */:
14375             case 164 /* SetAccessor */:
14376             case 161 /* MethodDeclaration */:
14377                 // if this method has a body and its parent is a class declaration, this is a valid target.
14378                 return node.body !== undefined
14379                     && parent.kind === 245 /* ClassDeclaration */;
14380             case 156 /* Parameter */:
14381                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14382                 return parent.body !== undefined
14383                     && (parent.kind === 162 /* Constructor */
14384                         || parent.kind === 161 /* MethodDeclaration */
14385                         || parent.kind === 164 /* SetAccessor */)
14386                     && grandparent.kind === 245 /* ClassDeclaration */;
14387         }
14388         return false;
14389     }
14390     ts.nodeCanBeDecorated = nodeCanBeDecorated;
14391     function nodeIsDecorated(node, parent, grandparent) {
14392         return node.decorators !== undefined
14393             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14394     }
14395     ts.nodeIsDecorated = nodeIsDecorated;
14396     function nodeOrChildIsDecorated(node, parent, grandparent) {
14397         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14398     }
14399     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14400     function childIsDecorated(node, parent) {
14401         switch (node.kind) {
14402             case 245 /* ClassDeclaration */:
14403                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14404             case 161 /* MethodDeclaration */:
14405             case 164 /* SetAccessor */:
14406                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14407             default:
14408                 return false;
14409         }
14410     }
14411     ts.childIsDecorated = childIsDecorated;
14412     function isJSXTagName(node) {
14413         var parent = node.parent;
14414         if (parent.kind === 268 /* JsxOpeningElement */ ||
14415             parent.kind === 267 /* JsxSelfClosingElement */ ||
14416             parent.kind === 269 /* JsxClosingElement */) {
14417             return parent.tagName === node;
14418         }
14419         return false;
14420     }
14421     ts.isJSXTagName = isJSXTagName;
14422     function isExpressionNode(node) {
14423         switch (node.kind) {
14424             case 102 /* SuperKeyword */:
14425             case 100 /* NullKeyword */:
14426             case 106 /* TrueKeyword */:
14427             case 91 /* FalseKeyword */:
14428             case 13 /* RegularExpressionLiteral */:
14429             case 192 /* ArrayLiteralExpression */:
14430             case 193 /* ObjectLiteralExpression */:
14431             case 194 /* PropertyAccessExpression */:
14432             case 195 /* ElementAccessExpression */:
14433             case 196 /* CallExpression */:
14434             case 197 /* NewExpression */:
14435             case 198 /* TaggedTemplateExpression */:
14436             case 217 /* AsExpression */:
14437             case 199 /* TypeAssertionExpression */:
14438             case 218 /* NonNullExpression */:
14439             case 200 /* ParenthesizedExpression */:
14440             case 201 /* FunctionExpression */:
14441             case 214 /* ClassExpression */:
14442             case 202 /* ArrowFunction */:
14443             case 205 /* VoidExpression */:
14444             case 203 /* DeleteExpression */:
14445             case 204 /* TypeOfExpression */:
14446             case 207 /* PrefixUnaryExpression */:
14447             case 208 /* PostfixUnaryExpression */:
14448             case 209 /* BinaryExpression */:
14449             case 210 /* ConditionalExpression */:
14450             case 213 /* SpreadElement */:
14451             case 211 /* TemplateExpression */:
14452             case 215 /* OmittedExpression */:
14453             case 266 /* JsxElement */:
14454             case 267 /* JsxSelfClosingElement */:
14455             case 270 /* JsxFragment */:
14456             case 212 /* YieldExpression */:
14457             case 206 /* AwaitExpression */:
14458             case 219 /* MetaProperty */:
14459                 return true;
14460             case 153 /* QualifiedName */:
14461                 while (node.parent.kind === 153 /* QualifiedName */) {
14462                     node = node.parent;
14463                 }
14464                 return node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node);
14465             case 75 /* Identifier */:
14466                 if (node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node)) {
14467                     return true;
14468                 }
14469             // falls through
14470             case 8 /* NumericLiteral */:
14471             case 9 /* BigIntLiteral */:
14472             case 10 /* StringLiteral */:
14473             case 14 /* NoSubstitutionTemplateLiteral */:
14474             case 104 /* ThisKeyword */:
14475                 return isInExpressionContext(node);
14476             default:
14477                 return false;
14478         }
14479     }
14480     ts.isExpressionNode = isExpressionNode;
14481     function isInExpressionContext(node) {
14482         var parent = node.parent;
14483         switch (parent.kind) {
14484             case 242 /* VariableDeclaration */:
14485             case 156 /* Parameter */:
14486             case 159 /* PropertyDeclaration */:
14487             case 158 /* PropertySignature */:
14488             case 284 /* EnumMember */:
14489             case 281 /* PropertyAssignment */:
14490             case 191 /* BindingElement */:
14491                 return parent.initializer === node;
14492             case 226 /* ExpressionStatement */:
14493             case 227 /* IfStatement */:
14494             case 228 /* DoStatement */:
14495             case 229 /* WhileStatement */:
14496             case 235 /* ReturnStatement */:
14497             case 236 /* WithStatement */:
14498             case 237 /* SwitchStatement */:
14499             case 277 /* CaseClause */:
14500             case 239 /* ThrowStatement */:
14501                 return parent.expression === node;
14502             case 230 /* ForStatement */:
14503                 var forStatement = parent;
14504                 return (forStatement.initializer === node && forStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14505                     forStatement.condition === node ||
14506                     forStatement.incrementor === node;
14507             case 231 /* ForInStatement */:
14508             case 232 /* ForOfStatement */:
14509                 var forInStatement = parent;
14510                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14511                     forInStatement.expression === node;
14512             case 199 /* TypeAssertionExpression */:
14513             case 217 /* AsExpression */:
14514                 return node === parent.expression;
14515             case 221 /* TemplateSpan */:
14516                 return node === parent.expression;
14517             case 154 /* ComputedPropertyName */:
14518                 return node === parent.expression;
14519             case 157 /* Decorator */:
14520             case 276 /* JsxExpression */:
14521             case 275 /* JsxSpreadAttribute */:
14522             case 283 /* SpreadAssignment */:
14523                 return true;
14524             case 216 /* ExpressionWithTypeArguments */:
14525                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14526             case 282 /* ShorthandPropertyAssignment */:
14527                 return parent.objectAssignmentInitializer === node;
14528             default:
14529                 return isExpressionNode(parent);
14530         }
14531     }
14532     ts.isInExpressionContext = isInExpressionContext;
14533     function isPartOfTypeQuery(node) {
14534         while (node.kind === 153 /* QualifiedName */ || node.kind === 75 /* Identifier */) {
14535             node = node.parent;
14536         }
14537         return node.kind === 172 /* TypeQuery */;
14538     }
14539     ts.isPartOfTypeQuery = isPartOfTypeQuery;
14540     function isExternalModuleImportEqualsDeclaration(node) {
14541         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */;
14542     }
14543     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14544     function getExternalModuleImportEqualsDeclarationExpression(node) {
14545         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14546         return node.moduleReference.expression;
14547     }
14548     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14549     function isInternalModuleImportEqualsDeclaration(node) {
14550         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 265 /* ExternalModuleReference */;
14551     }
14552     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14553     function isSourceFileJS(file) {
14554         return isInJSFile(file);
14555     }
14556     ts.isSourceFileJS = isSourceFileJS;
14557     function isSourceFileNotJS(file) {
14558         return !isInJSFile(file);
14559     }
14560     ts.isSourceFileNotJS = isSourceFileNotJS;
14561     function isInJSFile(node) {
14562         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14563     }
14564     ts.isInJSFile = isInJSFile;
14565     function isInJsonFile(node) {
14566         return !!node && !!(node.flags & 33554432 /* JsonFile */);
14567     }
14568     ts.isInJsonFile = isInJsonFile;
14569     function isSourceFileNotJson(file) {
14570         return !isJsonSourceFile(file);
14571     }
14572     ts.isSourceFileNotJson = isSourceFileNotJson;
14573     function isInJSDoc(node) {
14574         return !!node && !!(node.flags & 4194304 /* JSDoc */);
14575     }
14576     ts.isInJSDoc = isInJSDoc;
14577     function isJSDocIndexSignature(node) {
14578         return ts.isTypeReferenceNode(node) &&
14579             ts.isIdentifier(node.typeName) &&
14580             node.typeName.escapedText === "Object" &&
14581             node.typeArguments && node.typeArguments.length === 2 &&
14582             (node.typeArguments[0].kind === 143 /* StringKeyword */ || node.typeArguments[0].kind === 140 /* NumberKeyword */);
14583     }
14584     ts.isJSDocIndexSignature = isJSDocIndexSignature;
14585     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14586         if (callExpression.kind !== 196 /* CallExpression */) {
14587             return false;
14588         }
14589         var _a = callExpression, expression = _a.expression, args = _a.arguments;
14590         if (expression.kind !== 75 /* Identifier */ || expression.escapedText !== "require") {
14591             return false;
14592         }
14593         if (args.length !== 1) {
14594             return false;
14595         }
14596         var arg = args[0];
14597         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14598     }
14599     ts.isRequireCall = isRequireCall;
14600     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14601         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument);
14602     }
14603     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
14604     function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) {
14605         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
14606         return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
14607     }
14608     ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement;
14609     function isSingleOrDoubleQuote(charCode) {
14610         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
14611     }
14612     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
14613     function isStringDoubleQuoted(str, sourceFile) {
14614         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
14615     }
14616     ts.isStringDoubleQuoted = isStringDoubleQuoted;
14617     function getDeclarationOfExpando(node) {
14618         if (!node.parent) {
14619             return undefined;
14620         }
14621         var name;
14622         var decl;
14623         if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
14624             if (!isInJSFile(node) && !isVarConst(node.parent)) {
14625                 return undefined;
14626             }
14627             name = node.parent.name;
14628             decl = node.parent;
14629         }
14630         else if (ts.isBinaryExpression(node.parent)) {
14631             var parentNode = node.parent;
14632             var parentNodeOperator = node.parent.operatorToken.kind;
14633             if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
14634                 name = parentNode.left;
14635                 decl = name;
14636             }
14637             else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
14638                 if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
14639                     name = parentNode.parent.name;
14640                     decl = parentNode.parent;
14641                 }
14642                 else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
14643                     name = parentNode.parent.left;
14644                     decl = name;
14645                 }
14646                 if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
14647                     return undefined;
14648                 }
14649             }
14650         }
14651         if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
14652             return undefined;
14653         }
14654         return decl;
14655     }
14656     ts.getDeclarationOfExpando = getDeclarationOfExpando;
14657     function isAssignmentDeclaration(decl) {
14658         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
14659     }
14660     ts.isAssignmentDeclaration = isAssignmentDeclaration;
14661     /** Get the initializer, taking into account defaulted Javascript initializers */
14662     function getEffectiveInitializer(node) {
14663         if (isInJSFile(node) && node.initializer &&
14664             ts.isBinaryExpression(node.initializer) &&
14665             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
14666             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
14667             return node.initializer.right;
14668         }
14669         return node.initializer;
14670     }
14671     ts.getEffectiveInitializer = getEffectiveInitializer;
14672     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
14673     function getDeclaredExpandoInitializer(node) {
14674         var init = getEffectiveInitializer(node);
14675         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
14676     }
14677     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
14678     function hasExpandoValueProperty(node, isPrototypeAssignment) {
14679         return ts.forEach(node.properties, function (p) {
14680             return ts.isPropertyAssignment(p) &&
14681                 ts.isIdentifier(p.name) &&
14682                 p.name.escapedText === "value" &&
14683                 p.initializer &&
14684                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
14685         });
14686     }
14687     /**
14688      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
14689      * We treat the right hand side of assignments with container-like initalizers as declarations.
14690      */
14691     function getAssignedExpandoInitializer(node) {
14692         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
14693             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
14694             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
14695                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
14696         }
14697         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
14698             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
14699             if (result) {
14700                 return result;
14701             }
14702         }
14703     }
14704     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
14705     /**
14706      * Recognized expando initializers are:
14707      * 1. (function() {})() -- IIFEs
14708      * 2. function() { } -- Function expressions
14709      * 3. class { } -- Class expressions
14710      * 4. {} -- Empty object literals
14711      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
14712      *
14713      * This function returns the provided initializer, or undefined if it is not valid.
14714      */
14715     function getExpandoInitializer(initializer, isPrototypeAssignment) {
14716         if (ts.isCallExpression(initializer)) {
14717             var e = skipParentheses(initializer.expression);
14718             return e.kind === 201 /* FunctionExpression */ || e.kind === 202 /* ArrowFunction */ ? initializer : undefined;
14719         }
14720         if (initializer.kind === 201 /* FunctionExpression */ ||
14721             initializer.kind === 214 /* ClassExpression */ ||
14722             initializer.kind === 202 /* ArrowFunction */) {
14723             return initializer;
14724         }
14725         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
14726             return initializer;
14727         }
14728     }
14729     ts.getExpandoInitializer = getExpandoInitializer;
14730     /**
14731      * A defaulted expando initializer matches the pattern
14732      * `Lhs = Lhs || ExpandoInitializer`
14733      * or `var Lhs = Lhs || ExpandoInitializer`
14734      *
14735      * The second Lhs is required to be the same as the first except that it may be prefixed with
14736      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
14737      */
14738     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
14739         var e = ts.isBinaryExpression(initializer)
14740             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
14741             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
14742         if (e && isSameEntityName(name, initializer.left)) {
14743             return e;
14744         }
14745     }
14746     function isDefaultedExpandoInitializer(node) {
14747         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
14748             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
14749                 undefined;
14750         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
14751     }
14752     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
14753     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
14754     function getNameOfExpando(node) {
14755         if (ts.isBinaryExpression(node.parent)) {
14756             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
14757             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
14758                 return parent.left;
14759             }
14760         }
14761         else if (ts.isVariableDeclaration(node.parent)) {
14762             return node.parent.name;
14763         }
14764     }
14765     ts.getNameOfExpando = getNameOfExpando;
14766     /**
14767      * Is the 'declared' name the same as the one in the initializer?
14768      * @return true for identical entity names, as well as ones where the initializer is prefixed with
14769      * 'window', 'self' or 'global'. For example:
14770      *
14771      * var my = my || {}
14772      * var min = window.min || {}
14773      * my.app = self.my.app || class { }
14774      */
14775     function isSameEntityName(name, initializer) {
14776         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
14777             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(name);
14778         }
14779         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
14780             (initializer.expression.kind === 104 /* ThisKeyword */ ||
14781                 ts.isIdentifier(initializer.expression) &&
14782                     (initializer.expression.escapedText === "window" ||
14783                         initializer.expression.escapedText === "self" ||
14784                         initializer.expression.escapedText === "global"))) {
14785             var nameOrArgument = getNameOrArgument(initializer);
14786             if (ts.isPrivateIdentifier(nameOrArgument)) {
14787                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
14788             }
14789             return isSameEntityName(name, nameOrArgument);
14790         }
14791         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
14792             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
14793                 && isSameEntityName(name.expression, initializer.expression);
14794         }
14795         return false;
14796     }
14797     function getRightMostAssignedExpression(node) {
14798         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
14799             node = node.right;
14800         }
14801         return node;
14802     }
14803     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
14804     function isExportsIdentifier(node) {
14805         return ts.isIdentifier(node) && node.escapedText === "exports";
14806     }
14807     ts.isExportsIdentifier = isExportsIdentifier;
14808     function isModuleIdentifier(node) {
14809         return ts.isIdentifier(node) && node.escapedText === "module";
14810     }
14811     ts.isModuleIdentifier = isModuleIdentifier;
14812     function isModuleExportsAccessExpression(node) {
14813         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
14814             && isModuleIdentifier(node.expression)
14815             && getElementOrPropertyAccessName(node) === "exports";
14816     }
14817     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
14818     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
14819     /// assignments we treat as special in the binder
14820     function getAssignmentDeclarationKind(expr) {
14821         var special = getAssignmentDeclarationKindWorker(expr);
14822         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
14823     }
14824     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
14825     function isBindableObjectDefinePropertyCall(expr) {
14826         return ts.length(expr.arguments) === 3 &&
14827             ts.isPropertyAccessExpression(expr.expression) &&
14828             ts.isIdentifier(expr.expression.expression) &&
14829             ts.idText(expr.expression.expression) === "Object" &&
14830             ts.idText(expr.expression.name) === "defineProperty" &&
14831             isStringOrNumericLiteralLike(expr.arguments[1]) &&
14832             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
14833     }
14834     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
14835     /** x.y OR x[0] */
14836     function isLiteralLikeAccess(node) {
14837         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
14838     }
14839     ts.isLiteralLikeAccess = isLiteralLikeAccess;
14840     /** x[0] OR x['a'] OR x[Symbol.y] */
14841     function isLiteralLikeElementAccess(node) {
14842         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
14843             isWellKnownSymbolSyntactically(node.argumentExpression));
14844     }
14845     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
14846     /** Any series of property and element accesses. */
14847     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
14848         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
14849             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
14850     }
14851     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
14852     /** Any series of property and element accesses, ending in a literal element access */
14853     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
14854         return isLiteralLikeElementAccess(node)
14855             && ((!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */) ||
14856                 isEntityNameExpression(node.expression) ||
14857                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
14858     }
14859     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
14860     function isBindableStaticNameExpression(node, excludeThisKeyword) {
14861         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
14862     }
14863     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
14864     function getNameOrArgument(expr) {
14865         if (ts.isPropertyAccessExpression(expr)) {
14866             return expr.name;
14867         }
14868         return expr.argumentExpression;
14869     }
14870     ts.getNameOrArgument = getNameOrArgument;
14871     function getAssignmentDeclarationKindWorker(expr) {
14872         if (ts.isCallExpression(expr)) {
14873             if (!isBindableObjectDefinePropertyCall(expr)) {
14874                 return 0 /* None */;
14875             }
14876             var entityName = expr.arguments[0];
14877             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
14878                 return 8 /* ObjectDefinePropertyExports */;
14879             }
14880             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
14881                 return 9 /* ObjectDefinePrototypeProperty */;
14882             }
14883             return 7 /* ObjectDefinePropertyValue */;
14884         }
14885         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) {
14886             return 0 /* None */;
14887         }
14888         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
14889             // F.prototype = { ... }
14890             return 6 /* Prototype */;
14891         }
14892         return getAssignmentDeclarationPropertyAccessKind(expr.left);
14893     }
14894     /**
14895      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
14896      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
14897      */
14898     /* @internal */
14899     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
14900         if (ts.isPropertyAccessExpression(node)) {
14901             return node.name;
14902         }
14903         var arg = skipParentheses(node.argumentExpression);
14904         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
14905             return arg;
14906         }
14907         return node;
14908     }
14909     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
14910     function getElementOrPropertyAccessName(node) {
14911         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
14912         if (name) {
14913             if (ts.isIdentifier(name)) {
14914                 return name.escapedText;
14915             }
14916             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
14917                 return ts.escapeLeadingUnderscores(name.text);
14918             }
14919         }
14920         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
14921             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
14922         }
14923         return undefined;
14924     }
14925     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
14926     function getAssignmentDeclarationPropertyAccessKind(lhs) {
14927         if (lhs.expression.kind === 104 /* ThisKeyword */) {
14928             return 4 /* ThisProperty */;
14929         }
14930         else if (isModuleExportsAccessExpression(lhs)) {
14931             // module.exports = expr
14932             return 2 /* ModuleExports */;
14933         }
14934         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
14935             if (isPrototypeAccess(lhs.expression)) {
14936                 // F.G....prototype.x = expr
14937                 return 3 /* PrototypeProperty */;
14938             }
14939             var nextToLast = lhs;
14940             while (!ts.isIdentifier(nextToLast.expression)) {
14941                 nextToLast = nextToLast.expression;
14942             }
14943             var id = nextToLast.expression;
14944             if ((id.escapedText === "exports" ||
14945                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
14946                 // ExportsProperty does not support binding with computed names
14947                 isBindableStaticAccessExpression(lhs)) {
14948                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
14949                 return 1 /* ExportsProperty */;
14950             }
14951             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
14952                 // F.G...x = expr
14953                 return 5 /* Property */;
14954             }
14955         }
14956         return 0 /* None */;
14957     }
14958     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
14959     function getInitializerOfBinaryExpression(expr) {
14960         while (ts.isBinaryExpression(expr.right)) {
14961             expr = expr.right;
14962         }
14963         return expr.right;
14964     }
14965     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
14966     function isPrototypePropertyAssignment(node) {
14967         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
14968     }
14969     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
14970     function isSpecialPropertyDeclaration(expr) {
14971         return isInJSFile(expr) &&
14972             expr.parent && expr.parent.kind === 226 /* ExpressionStatement */ &&
14973             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
14974             !!ts.getJSDocTypeTag(expr.parent);
14975     }
14976     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
14977     function setValueDeclaration(symbol, node) {
14978         var valueDeclaration = symbol.valueDeclaration;
14979         if (!valueDeclaration ||
14980             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
14981                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
14982             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
14983             // other kinds of value declarations take precedence over modules and assignment declarations
14984             symbol.valueDeclaration = node;
14985         }
14986     }
14987     ts.setValueDeclaration = setValueDeclaration;
14988     function isFunctionSymbol(symbol) {
14989         if (!symbol || !symbol.valueDeclaration) {
14990             return false;
14991         }
14992         var decl = symbol.valueDeclaration;
14993         return decl.kind === 244 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
14994     }
14995     ts.isFunctionSymbol = isFunctionSymbol;
14996     function importFromModuleSpecifier(node) {
14997         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
14998     }
14999     ts.importFromModuleSpecifier = importFromModuleSpecifier;
15000     function tryGetImportFromModuleSpecifier(node) {
15001         switch (node.parent.kind) {
15002             case 254 /* ImportDeclaration */:
15003             case 260 /* ExportDeclaration */:
15004                 return node.parent;
15005             case 265 /* ExternalModuleReference */:
15006                 return node.parent.parent;
15007             case 196 /* CallExpression */:
15008                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
15009             case 187 /* LiteralType */:
15010                 ts.Debug.assert(ts.isStringLiteral(node));
15011                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15012             default:
15013                 return undefined;
15014         }
15015     }
15016     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15017     function getExternalModuleName(node) {
15018         switch (node.kind) {
15019             case 254 /* ImportDeclaration */:
15020             case 260 /* ExportDeclaration */:
15021                 return node.moduleSpecifier;
15022             case 253 /* ImportEqualsDeclaration */:
15023                 return node.moduleReference.kind === 265 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15024             case 188 /* ImportType */:
15025                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15026             default:
15027                 return ts.Debug.assertNever(node);
15028         }
15029     }
15030     ts.getExternalModuleName = getExternalModuleName;
15031     function getNamespaceDeclarationNode(node) {
15032         switch (node.kind) {
15033             case 254 /* ImportDeclaration */:
15034                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15035             case 253 /* ImportEqualsDeclaration */:
15036                 return node;
15037             case 260 /* ExportDeclaration */:
15038                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15039             default:
15040                 return ts.Debug.assertNever(node);
15041         }
15042     }
15043     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15044     function isDefaultImport(node) {
15045         return node.kind === 254 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15046     }
15047     ts.isDefaultImport = isDefaultImport;
15048     function forEachImportClauseDeclaration(node, action) {
15049         if (node.name) {
15050             var result = action(node);
15051             if (result)
15052                 return result;
15053         }
15054         if (node.namedBindings) {
15055             var result = ts.isNamespaceImport(node.namedBindings)
15056                 ? action(node.namedBindings)
15057                 : ts.forEach(node.namedBindings.elements, action);
15058             if (result)
15059                 return result;
15060         }
15061     }
15062     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15063     function hasQuestionToken(node) {
15064         if (node) {
15065             switch (node.kind) {
15066                 case 156 /* Parameter */:
15067                 case 161 /* MethodDeclaration */:
15068                 case 160 /* MethodSignature */:
15069                 case 282 /* ShorthandPropertyAssignment */:
15070                 case 281 /* PropertyAssignment */:
15071                 case 159 /* PropertyDeclaration */:
15072                 case 158 /* PropertySignature */:
15073                     return node.questionToken !== undefined;
15074             }
15075         }
15076         return false;
15077     }
15078     ts.hasQuestionToken = hasQuestionToken;
15079     function isJSDocConstructSignature(node) {
15080         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15081         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15082         return !!name && name.escapedText === "new";
15083     }
15084     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15085     function isJSDocTypeAlias(node) {
15086         return node.kind === 322 /* JSDocTypedefTag */ || node.kind === 315 /* JSDocCallbackTag */ || node.kind === 316 /* JSDocEnumTag */;
15087     }
15088     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15089     function isTypeAlias(node) {
15090         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15091     }
15092     ts.isTypeAlias = isTypeAlias;
15093     function getSourceOfAssignment(node) {
15094         return ts.isExpressionStatement(node) &&
15095             ts.isBinaryExpression(node.expression) &&
15096             node.expression.operatorToken.kind === 62 /* EqualsToken */
15097             ? getRightMostAssignedExpression(node.expression)
15098             : undefined;
15099     }
15100     function getSourceOfDefaultedAssignment(node) {
15101         return ts.isExpressionStatement(node) &&
15102             ts.isBinaryExpression(node.expression) &&
15103             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15104             ts.isBinaryExpression(node.expression.right) &&
15105             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15106             ? node.expression.right.right
15107             : undefined;
15108     }
15109     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15110         switch (node.kind) {
15111             case 225 /* VariableStatement */:
15112                 var v = getSingleVariableOfVariableStatement(node);
15113                 return v && v.initializer;
15114             case 159 /* PropertyDeclaration */:
15115                 return node.initializer;
15116             case 281 /* PropertyAssignment */:
15117                 return node.initializer;
15118         }
15119     }
15120     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15121     function getSingleVariableOfVariableStatement(node) {
15122         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15123     }
15124     function getNestedModuleDeclaration(node) {
15125         return ts.isModuleDeclaration(node) &&
15126             node.body &&
15127             node.body.kind === 249 /* ModuleDeclaration */
15128             ? node.body
15129             : undefined;
15130     }
15131     function getJSDocCommentsAndTags(hostNode) {
15132         var result;
15133         // Pull parameter comments from declaring function as well
15134         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15135             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15136         }
15137         var node = hostNode;
15138         while (node && node.parent) {
15139             if (ts.hasJSDocNodes(node)) {
15140                 result = ts.append(result, ts.last(node.jsDoc));
15141             }
15142             if (node.kind === 156 /* Parameter */) {
15143                 result = ts.addRange(result, ts.getJSDocParameterTags(node));
15144                 break;
15145             }
15146             if (node.kind === 155 /* TypeParameter */) {
15147                 result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
15148                 break;
15149             }
15150             node = getNextJSDocCommentLocation(node);
15151         }
15152         return result || ts.emptyArray;
15153     }
15154     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15155     function getNextJSDocCommentLocation(node) {
15156         var parent = node.parent;
15157         if (parent.kind === 281 /* PropertyAssignment */ ||
15158             parent.kind === 259 /* ExportAssignment */ ||
15159             parent.kind === 159 /* PropertyDeclaration */ ||
15160             parent.kind === 226 /* ExpressionStatement */ && node.kind === 194 /* PropertyAccessExpression */ ||
15161             getNestedModuleDeclaration(parent) ||
15162             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15163             return parent;
15164         }
15165         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15166         // /**
15167         //   * @param {number} name
15168         //   * @returns {number}
15169         //   */
15170         // var x = function(name) { return name.length; }
15171         else if (parent.parent &&
15172             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15173                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15174             return parent.parent;
15175         }
15176         else if (parent.parent && parent.parent.parent &&
15177             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15178                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15179                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15180             return parent.parent.parent;
15181         }
15182     }
15183     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15184     function getParameterSymbolFromJSDoc(node) {
15185         if (node.symbol) {
15186             return node.symbol;
15187         }
15188         if (!ts.isIdentifier(node.name)) {
15189             return undefined;
15190         }
15191         var name = node.name.escapedText;
15192         var decl = getHostSignatureFromJSDoc(node);
15193         if (!decl) {
15194             return undefined;
15195         }
15196         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 75 /* Identifier */ && p.name.escapedText === name; });
15197         return parameter && parameter.symbol;
15198     }
15199     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15200     function getHostSignatureFromJSDoc(node) {
15201         var host = getEffectiveJSDocHost(node);
15202         return host && ts.isFunctionLike(host) ? host : undefined;
15203     }
15204     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15205     function getEffectiveJSDocHost(node) {
15206         var host = getJSDocHost(node);
15207         var decl = getSourceOfDefaultedAssignment(host) ||
15208             getSourceOfAssignment(host) ||
15209             getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
15210             getSingleVariableOfVariableStatement(host) ||
15211             getNestedModuleDeclaration(host) ||
15212             host;
15213         return decl;
15214     }
15215     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15216     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments.  */
15217     function getJSDocHost(node) {
15218         return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
15219     }
15220     ts.getJSDocHost = getJSDocHost;
15221     function getTypeParameterFromJsDoc(node) {
15222         var name = node.name.escapedText;
15223         var typeParameters = node.parent.parent.parent.typeParameters;
15224         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15225     }
15226     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15227     function hasRestParameter(s) {
15228         var last = ts.lastOrUndefined(s.parameters);
15229         return !!last && isRestParameter(last);
15230     }
15231     ts.hasRestParameter = hasRestParameter;
15232     function isRestParameter(node) {
15233         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15234         return node.dotDotDotToken !== undefined || !!type && type.kind === 301 /* JSDocVariadicType */;
15235     }
15236     ts.isRestParameter = isRestParameter;
15237     function hasTypeArguments(node) {
15238         return !!node.typeArguments;
15239     }
15240     ts.hasTypeArguments = hasTypeArguments;
15241     var AssignmentKind;
15242     (function (AssignmentKind) {
15243         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15244         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15245         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15246     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15247     function getAssignmentTargetKind(node) {
15248         var parent = node.parent;
15249         while (true) {
15250             switch (parent.kind) {
15251                 case 209 /* BinaryExpression */:
15252                     var binaryOperator = parent.operatorToken.kind;
15253                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15254                         binaryOperator === 62 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
15255                         0 /* None */;
15256                 case 207 /* PrefixUnaryExpression */:
15257                 case 208 /* PostfixUnaryExpression */:
15258                     var unaryOperator = parent.operator;
15259                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15260                 case 231 /* ForInStatement */:
15261                 case 232 /* ForOfStatement */:
15262                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15263                 case 200 /* ParenthesizedExpression */:
15264                 case 192 /* ArrayLiteralExpression */:
15265                 case 213 /* SpreadElement */:
15266                 case 218 /* NonNullExpression */:
15267                     node = parent;
15268                     break;
15269                 case 282 /* ShorthandPropertyAssignment */:
15270                     if (parent.name !== node) {
15271                         return 0 /* None */;
15272                     }
15273                     node = parent.parent;
15274                     break;
15275                 case 281 /* PropertyAssignment */:
15276                     if (parent.name === node) {
15277                         return 0 /* None */;
15278                     }
15279                     node = parent.parent;
15280                     break;
15281                 default:
15282                     return 0 /* None */;
15283             }
15284             parent = node.parent;
15285         }
15286     }
15287     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15288     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15289     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15290     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15291     // (Note that `p` is not a target in the above examples, only `a`.)
15292     function isAssignmentTarget(node) {
15293         return getAssignmentTargetKind(node) !== 0 /* None */;
15294     }
15295     ts.isAssignmentTarget = isAssignmentTarget;
15296     /**
15297      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15298      * the same `var` declaration scope as the node's parent.
15299      */
15300     function isNodeWithPossibleHoistedDeclaration(node) {
15301         switch (node.kind) {
15302             case 223 /* Block */:
15303             case 225 /* VariableStatement */:
15304             case 236 /* WithStatement */:
15305             case 227 /* IfStatement */:
15306             case 237 /* SwitchStatement */:
15307             case 251 /* CaseBlock */:
15308             case 277 /* CaseClause */:
15309             case 278 /* DefaultClause */:
15310             case 238 /* LabeledStatement */:
15311             case 230 /* ForStatement */:
15312             case 231 /* ForInStatement */:
15313             case 232 /* ForOfStatement */:
15314             case 228 /* DoStatement */:
15315             case 229 /* WhileStatement */:
15316             case 240 /* TryStatement */:
15317             case 280 /* CatchClause */:
15318                 return true;
15319         }
15320         return false;
15321     }
15322     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15323     function isValueSignatureDeclaration(node) {
15324         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15325     }
15326     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15327     function walkUp(node, kind) {
15328         while (node && node.kind === kind) {
15329             node = node.parent;
15330         }
15331         return node;
15332     }
15333     function walkUpParenthesizedTypes(node) {
15334         return walkUp(node, 182 /* ParenthesizedType */);
15335     }
15336     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15337     function walkUpParenthesizedExpressions(node) {
15338         return walkUp(node, 200 /* ParenthesizedExpression */);
15339     }
15340     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15341     function skipParentheses(node) {
15342         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15343     }
15344     ts.skipParentheses = skipParentheses;
15345     function skipParenthesesUp(node) {
15346         while (node.kind === 200 /* ParenthesizedExpression */) {
15347             node = node.parent;
15348         }
15349         return node;
15350     }
15351     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15352     function isDeleteTarget(node) {
15353         if (node.kind !== 194 /* PropertyAccessExpression */ && node.kind !== 195 /* ElementAccessExpression */) {
15354             return false;
15355         }
15356         node = walkUpParenthesizedExpressions(node.parent);
15357         return node && node.kind === 203 /* DeleteExpression */;
15358     }
15359     ts.isDeleteTarget = isDeleteTarget;
15360     function isNodeDescendantOf(node, ancestor) {
15361         while (node) {
15362             if (node === ancestor)
15363                 return true;
15364             node = node.parent;
15365         }
15366         return false;
15367     }
15368     ts.isNodeDescendantOf = isNodeDescendantOf;
15369     // True if `name` is the name of a declaration node
15370     function isDeclarationName(name) {
15371         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15372     }
15373     ts.isDeclarationName = isDeclarationName;
15374     // See GH#16030
15375     function getDeclarationFromName(name) {
15376         var parent = name.parent;
15377         switch (name.kind) {
15378             case 10 /* StringLiteral */:
15379             case 14 /* NoSubstitutionTemplateLiteral */:
15380             case 8 /* NumericLiteral */:
15381                 if (ts.isComputedPropertyName(parent))
15382                     return parent.parent;
15383             // falls through
15384             case 75 /* Identifier */:
15385                 if (ts.isDeclaration(parent)) {
15386                     return parent.name === name ? parent : undefined;
15387                 }
15388                 else if (ts.isQualifiedName(parent)) {
15389                     var tag = parent.parent;
15390                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15391                 }
15392                 else {
15393                     var binExp = parent.parent;
15394                     return ts.isBinaryExpression(binExp) &&
15395                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15396                         (binExp.left.symbol || binExp.symbol) &&
15397                         ts.getNameOfDeclaration(binExp) === name
15398                         ? binExp
15399                         : undefined;
15400                 }
15401             case 76 /* PrivateIdentifier */:
15402                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15403             default:
15404                 return undefined;
15405         }
15406     }
15407     ts.getDeclarationFromName = getDeclarationFromName;
15408     function isLiteralComputedPropertyDeclarationName(node) {
15409         return isStringOrNumericLiteralLike(node) &&
15410             node.parent.kind === 154 /* ComputedPropertyName */ &&
15411             ts.isDeclaration(node.parent.parent);
15412     }
15413     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15414     // Return true if the given identifier is classified as an IdentifierName
15415     function isIdentifierName(node) {
15416         var parent = node.parent;
15417         switch (parent.kind) {
15418             case 159 /* PropertyDeclaration */:
15419             case 158 /* PropertySignature */:
15420             case 161 /* MethodDeclaration */:
15421             case 160 /* MethodSignature */:
15422             case 163 /* GetAccessor */:
15423             case 164 /* SetAccessor */:
15424             case 284 /* EnumMember */:
15425             case 281 /* PropertyAssignment */:
15426             case 194 /* PropertyAccessExpression */:
15427                 // Name in member declaration or property name in property access
15428                 return parent.name === node;
15429             case 153 /* QualifiedName */:
15430                 // Name on right hand side of dot in a type query or type reference
15431                 if (parent.right === node) {
15432                     while (parent.kind === 153 /* QualifiedName */) {
15433                         parent = parent.parent;
15434                     }
15435                     return parent.kind === 172 /* TypeQuery */ || parent.kind === 169 /* TypeReference */;
15436                 }
15437                 return false;
15438             case 191 /* BindingElement */:
15439             case 258 /* ImportSpecifier */:
15440                 // Property name in binding element or import specifier
15441                 return parent.propertyName === node;
15442             case 263 /* ExportSpecifier */:
15443             case 273 /* JsxAttribute */:
15444                 // Any name in an export specifier or JSX Attribute
15445                 return true;
15446         }
15447         return false;
15448     }
15449     ts.isIdentifierName = isIdentifierName;
15450     // An alias symbol is created by one of the following declarations:
15451     // import <symbol> = ...
15452     // import <symbol> from ...
15453     // import * as <symbol> from ...
15454     // import { x as <symbol> } from ...
15455     // export { x as <symbol> } from ...
15456     // export * as ns <symbol> from ...
15457     // export = <EntityNameExpression>
15458     // export default <EntityNameExpression>
15459     // module.exports = <EntityNameExpression>
15460     // {<Identifier>}
15461     // {name: <EntityNameExpression>}
15462     function isAliasSymbolDeclaration(node) {
15463         return node.kind === 253 /* ImportEqualsDeclaration */ ||
15464             node.kind === 252 /* NamespaceExportDeclaration */ ||
15465             node.kind === 255 /* ImportClause */ && !!node.name ||
15466             node.kind === 256 /* NamespaceImport */ ||
15467             node.kind === 262 /* NamespaceExport */ ||
15468             node.kind === 258 /* ImportSpecifier */ ||
15469             node.kind === 263 /* ExportSpecifier */ ||
15470             node.kind === 259 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15471             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15472             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15473             node.kind === 282 /* ShorthandPropertyAssignment */ ||
15474             node.kind === 281 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15475     }
15476     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15477     function getAliasDeclarationFromName(node) {
15478         switch (node.parent.kind) {
15479             case 255 /* ImportClause */:
15480             case 258 /* ImportSpecifier */:
15481             case 256 /* NamespaceImport */:
15482             case 263 /* ExportSpecifier */:
15483             case 259 /* ExportAssignment */:
15484             case 253 /* ImportEqualsDeclaration */:
15485                 return node.parent;
15486             case 153 /* QualifiedName */:
15487                 do {
15488                     node = node.parent;
15489                 } while (node.parent.kind === 153 /* QualifiedName */);
15490                 return getAliasDeclarationFromName(node);
15491         }
15492     }
15493     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15494     function isAliasableExpression(e) {
15495         return isEntityNameExpression(e) || ts.isClassExpression(e);
15496     }
15497     ts.isAliasableExpression = isAliasableExpression;
15498     function exportAssignmentIsAlias(node) {
15499         var e = getExportAssignmentExpression(node);
15500         return isAliasableExpression(e);
15501     }
15502     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15503     function getExportAssignmentExpression(node) {
15504         return ts.isExportAssignment(node) ? node.expression : node.right;
15505     }
15506     ts.getExportAssignmentExpression = getExportAssignmentExpression;
15507     function getPropertyAssignmentAliasLikeExpression(node) {
15508         return node.kind === 282 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 281 /* PropertyAssignment */ ? node.initializer :
15509             node.parent.right;
15510     }
15511     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15512     function getEffectiveBaseTypeNode(node) {
15513         var baseType = getClassExtendsHeritageElement(node);
15514         if (baseType && isInJSFile(node)) {
15515             // Prefer an @augments tag because it may have type parameters.
15516             var tag = ts.getJSDocAugmentsTag(node);
15517             if (tag) {
15518                 return tag.class;
15519             }
15520         }
15521         return baseType;
15522     }
15523     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15524     function getClassExtendsHeritageElement(node) {
15525         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15526         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15527     }
15528     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15529     function getEffectiveImplementsTypeNodes(node) {
15530         if (isInJSFile(node)) {
15531             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15532         }
15533         else {
15534             var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */);
15535             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15536         }
15537     }
15538     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15539     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15540     function getAllSuperTypeNodes(node) {
15541         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15542             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15543                 ts.emptyArray;
15544     }
15545     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15546     function getInterfaceBaseTypeNodes(node) {
15547         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15548         return heritageClause ? heritageClause.types : undefined;
15549     }
15550     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15551     function getHeritageClause(clauses, kind) {
15552         if (clauses) {
15553             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15554                 var clause = clauses_1[_i];
15555                 if (clause.token === kind) {
15556                     return clause;
15557                 }
15558             }
15559         }
15560         return undefined;
15561     }
15562     ts.getHeritageClause = getHeritageClause;
15563     function getAncestor(node, kind) {
15564         while (node) {
15565             if (node.kind === kind) {
15566                 return node;
15567             }
15568             node = node.parent;
15569         }
15570         return undefined;
15571     }
15572     ts.getAncestor = getAncestor;
15573     function isKeyword(token) {
15574         return 77 /* FirstKeyword */ <= token && token <= 152 /* LastKeyword */;
15575     }
15576     ts.isKeyword = isKeyword;
15577     function isContextualKeyword(token) {
15578         return 122 /* FirstContextualKeyword */ <= token && token <= 152 /* LastContextualKeyword */;
15579     }
15580     ts.isContextualKeyword = isContextualKeyword;
15581     function isNonContextualKeyword(token) {
15582         return isKeyword(token) && !isContextualKeyword(token);
15583     }
15584     ts.isNonContextualKeyword = isNonContextualKeyword;
15585     function isFutureReservedKeyword(token) {
15586         return 113 /* FirstFutureReservedWord */ <= token && token <= 121 /* LastFutureReservedWord */;
15587     }
15588     ts.isFutureReservedKeyword = isFutureReservedKeyword;
15589     function isStringANonContextualKeyword(name) {
15590         var token = ts.stringToToken(name);
15591         return token !== undefined && isNonContextualKeyword(token);
15592     }
15593     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15594     function isStringAKeyword(name) {
15595         var token = ts.stringToToken(name);
15596         return token !== undefined && isKeyword(token);
15597     }
15598     ts.isStringAKeyword = isStringAKeyword;
15599     function isIdentifierANonContextualKeyword(_a) {
15600         var originalKeywordKind = _a.originalKeywordKind;
15601         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15602     }
15603     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15604     function isTrivia(token) {
15605         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15606     }
15607     ts.isTrivia = isTrivia;
15608     var FunctionFlags;
15609     (function (FunctionFlags) {
15610         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15611         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15612         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15613         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15614         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15615     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15616     function getFunctionFlags(node) {
15617         if (!node) {
15618             return 4 /* Invalid */;
15619         }
15620         var flags = 0 /* Normal */;
15621         switch (node.kind) {
15622             case 244 /* FunctionDeclaration */:
15623             case 201 /* FunctionExpression */:
15624             case 161 /* MethodDeclaration */:
15625                 if (node.asteriskToken) {
15626                     flags |= 1 /* Generator */;
15627                 }
15628             // falls through
15629             case 202 /* ArrowFunction */:
15630                 if (hasModifier(node, 256 /* Async */)) {
15631                     flags |= 2 /* Async */;
15632                 }
15633                 break;
15634         }
15635         if (!node.body) {
15636             flags |= 4 /* Invalid */;
15637         }
15638         return flags;
15639     }
15640     ts.getFunctionFlags = getFunctionFlags;
15641     function isAsyncFunction(node) {
15642         switch (node.kind) {
15643             case 244 /* FunctionDeclaration */:
15644             case 201 /* FunctionExpression */:
15645             case 202 /* ArrowFunction */:
15646             case 161 /* MethodDeclaration */:
15647                 return node.body !== undefined
15648                     && node.asteriskToken === undefined
15649                     && hasModifier(node, 256 /* Async */);
15650         }
15651         return false;
15652     }
15653     ts.isAsyncFunction = isAsyncFunction;
15654     function isStringOrNumericLiteralLike(node) {
15655         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
15656     }
15657     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
15658     function isSignedNumericLiteral(node) {
15659         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
15660     }
15661     ts.isSignedNumericLiteral = isSignedNumericLiteral;
15662     /**
15663      * A declaration has a dynamic name if all of the following are true:
15664      *   1. The declaration has a computed property name.
15665      *   2. The computed name is *not* expressed as a StringLiteral.
15666      *   3. The computed name is *not* expressed as a NumericLiteral.
15667      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
15668      *      immediately followed by a NumericLiteral.
15669      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
15670      *      is a property of the Symbol constructor that denotes a built-in
15671      *      Symbol.
15672      */
15673     function hasDynamicName(declaration) {
15674         var name = ts.getNameOfDeclaration(declaration);
15675         return !!name && isDynamicName(name);
15676     }
15677     ts.hasDynamicName = hasDynamicName;
15678     function isDynamicName(name) {
15679         if (!(name.kind === 154 /* ComputedPropertyName */ || name.kind === 195 /* ElementAccessExpression */)) {
15680             return false;
15681         }
15682         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
15683         return !isStringOrNumericLiteralLike(expr) &&
15684             !isSignedNumericLiteral(expr) &&
15685             !isWellKnownSymbolSyntactically(expr);
15686     }
15687     ts.isDynamicName = isDynamicName;
15688     /**
15689      * Checks if the expression is of the form:
15690      *    Symbol.name
15691      * where Symbol is literally the word "Symbol", and name is any identifierName
15692      */
15693     function isWellKnownSymbolSyntactically(node) {
15694         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
15695     }
15696     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
15697     function getPropertyNameForPropertyNameNode(name) {
15698         switch (name.kind) {
15699             case 75 /* Identifier */:
15700             case 76 /* PrivateIdentifier */:
15701                 return name.escapedText;
15702             case 10 /* StringLiteral */:
15703             case 8 /* NumericLiteral */:
15704                 return ts.escapeLeadingUnderscores(name.text);
15705             case 154 /* ComputedPropertyName */:
15706                 var nameExpression = name.expression;
15707                 if (isWellKnownSymbolSyntactically(nameExpression)) {
15708                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
15709                 }
15710                 else if (isStringOrNumericLiteralLike(nameExpression)) {
15711                     return ts.escapeLeadingUnderscores(nameExpression.text);
15712                 }
15713                 return undefined;
15714             default:
15715                 return ts.Debug.assertNever(name);
15716         }
15717     }
15718     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
15719     function isPropertyNameLiteral(node) {
15720         switch (node.kind) {
15721             case 75 /* Identifier */:
15722             case 10 /* StringLiteral */:
15723             case 14 /* NoSubstitutionTemplateLiteral */:
15724             case 8 /* NumericLiteral */:
15725                 return true;
15726             default:
15727                 return false;
15728         }
15729     }
15730     ts.isPropertyNameLiteral = isPropertyNameLiteral;
15731     function getTextOfIdentifierOrLiteral(node) {
15732         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
15733     }
15734     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
15735     function getEscapedTextOfIdentifierOrLiteral(node) {
15736         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
15737     }
15738     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
15739     function getPropertyNameForUniqueESSymbol(symbol) {
15740         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
15741     }
15742     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
15743     function getPropertyNameForKnownSymbolName(symbolName) {
15744         return "__@" + symbolName;
15745     }
15746     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
15747     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
15748         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
15749     }
15750     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
15751     function isKnownSymbol(symbol) {
15752         return ts.startsWith(symbol.escapedName, "__@");
15753     }
15754     ts.isKnownSymbol = isKnownSymbol;
15755     /**
15756      * Includes the word "Symbol" with unicode escapes
15757      */
15758     function isESSymbolIdentifier(node) {
15759         return node.kind === 75 /* Identifier */ && node.escapedText === "Symbol";
15760     }
15761     ts.isESSymbolIdentifier = isESSymbolIdentifier;
15762     function isPushOrUnshiftIdentifier(node) {
15763         return node.escapedText === "push" || node.escapedText === "unshift";
15764     }
15765     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
15766     function isParameterDeclaration(node) {
15767         var root = getRootDeclaration(node);
15768         return root.kind === 156 /* Parameter */;
15769     }
15770     ts.isParameterDeclaration = isParameterDeclaration;
15771     function getRootDeclaration(node) {
15772         while (node.kind === 191 /* BindingElement */) {
15773             node = node.parent.parent;
15774         }
15775         return node;
15776     }
15777     ts.getRootDeclaration = getRootDeclaration;
15778     function nodeStartsNewLexicalEnvironment(node) {
15779         var kind = node.kind;
15780         return kind === 162 /* Constructor */
15781             || kind === 201 /* FunctionExpression */
15782             || kind === 244 /* FunctionDeclaration */
15783             || kind === 202 /* ArrowFunction */
15784             || kind === 161 /* MethodDeclaration */
15785             || kind === 163 /* GetAccessor */
15786             || kind === 164 /* SetAccessor */
15787             || kind === 249 /* ModuleDeclaration */
15788             || kind === 290 /* SourceFile */;
15789     }
15790     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
15791     function nodeIsSynthesized(range) {
15792         return positionIsSynthesized(range.pos)
15793             || positionIsSynthesized(range.end);
15794     }
15795     ts.nodeIsSynthesized = nodeIsSynthesized;
15796     function getOriginalSourceFile(sourceFile) {
15797         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
15798     }
15799     ts.getOriginalSourceFile = getOriginalSourceFile;
15800     var Associativity;
15801     (function (Associativity) {
15802         Associativity[Associativity["Left"] = 0] = "Left";
15803         Associativity[Associativity["Right"] = 1] = "Right";
15804     })(Associativity = ts.Associativity || (ts.Associativity = {}));
15805     function getExpressionAssociativity(expression) {
15806         var operator = getOperator(expression);
15807         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15808         return getOperatorAssociativity(expression.kind, operator, hasArguments);
15809     }
15810     ts.getExpressionAssociativity = getExpressionAssociativity;
15811     function getOperatorAssociativity(kind, operator, hasArguments) {
15812         switch (kind) {
15813             case 197 /* NewExpression */:
15814                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
15815             case 207 /* PrefixUnaryExpression */:
15816             case 204 /* TypeOfExpression */:
15817             case 205 /* VoidExpression */:
15818             case 203 /* DeleteExpression */:
15819             case 206 /* AwaitExpression */:
15820             case 210 /* ConditionalExpression */:
15821             case 212 /* YieldExpression */:
15822                 return 1 /* Right */;
15823             case 209 /* BinaryExpression */:
15824                 switch (operator) {
15825                     case 42 /* AsteriskAsteriskToken */:
15826                     case 62 /* EqualsToken */:
15827                     case 63 /* PlusEqualsToken */:
15828                     case 64 /* MinusEqualsToken */:
15829                     case 66 /* AsteriskAsteriskEqualsToken */:
15830                     case 65 /* AsteriskEqualsToken */:
15831                     case 67 /* SlashEqualsToken */:
15832                     case 68 /* PercentEqualsToken */:
15833                     case 69 /* LessThanLessThanEqualsToken */:
15834                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15835                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15836                     case 72 /* AmpersandEqualsToken */:
15837                     case 74 /* CaretEqualsToken */:
15838                     case 73 /* BarEqualsToken */:
15839                         return 1 /* Right */;
15840                 }
15841         }
15842         return 0 /* Left */;
15843     }
15844     ts.getOperatorAssociativity = getOperatorAssociativity;
15845     function getExpressionPrecedence(expression) {
15846         var operator = getOperator(expression);
15847         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15848         return getOperatorPrecedence(expression.kind, operator, hasArguments);
15849     }
15850     ts.getExpressionPrecedence = getExpressionPrecedence;
15851     function getOperator(expression) {
15852         if (expression.kind === 209 /* BinaryExpression */) {
15853             return expression.operatorToken.kind;
15854         }
15855         else if (expression.kind === 207 /* PrefixUnaryExpression */ || expression.kind === 208 /* PostfixUnaryExpression */) {
15856             return expression.operator;
15857         }
15858         else {
15859             return expression.kind;
15860         }
15861     }
15862     ts.getOperator = getOperator;
15863     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
15864         switch (nodeKind) {
15865             case 327 /* CommaListExpression */:
15866                 return 0;
15867             case 213 /* SpreadElement */:
15868                 return 1;
15869             case 212 /* YieldExpression */:
15870                 return 2;
15871             case 210 /* ConditionalExpression */:
15872                 return 4;
15873             case 209 /* BinaryExpression */:
15874                 switch (operatorKind) {
15875                     case 27 /* CommaToken */:
15876                         return 0;
15877                     case 62 /* EqualsToken */:
15878                     case 63 /* PlusEqualsToken */:
15879                     case 64 /* MinusEqualsToken */:
15880                     case 66 /* AsteriskAsteriskEqualsToken */:
15881                     case 65 /* AsteriskEqualsToken */:
15882                     case 67 /* SlashEqualsToken */:
15883                     case 68 /* PercentEqualsToken */:
15884                     case 69 /* LessThanLessThanEqualsToken */:
15885                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15886                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15887                     case 72 /* AmpersandEqualsToken */:
15888                     case 74 /* CaretEqualsToken */:
15889                     case 73 /* BarEqualsToken */:
15890                         return 3;
15891                     default:
15892                         return getBinaryOperatorPrecedence(operatorKind);
15893                 }
15894             case 207 /* PrefixUnaryExpression */:
15895             case 204 /* TypeOfExpression */:
15896             case 205 /* VoidExpression */:
15897             case 203 /* DeleteExpression */:
15898             case 206 /* AwaitExpression */:
15899                 return 16;
15900             case 208 /* PostfixUnaryExpression */:
15901                 return 17;
15902             case 196 /* CallExpression */:
15903                 return 18;
15904             case 197 /* NewExpression */:
15905                 return hasArguments ? 19 : 18;
15906             case 198 /* TaggedTemplateExpression */:
15907             case 194 /* PropertyAccessExpression */:
15908             case 195 /* ElementAccessExpression */:
15909                 return 19;
15910             case 104 /* ThisKeyword */:
15911             case 102 /* SuperKeyword */:
15912             case 75 /* Identifier */:
15913             case 100 /* NullKeyword */:
15914             case 106 /* TrueKeyword */:
15915             case 91 /* FalseKeyword */:
15916             case 8 /* NumericLiteral */:
15917             case 9 /* BigIntLiteral */:
15918             case 10 /* StringLiteral */:
15919             case 192 /* ArrayLiteralExpression */:
15920             case 193 /* ObjectLiteralExpression */:
15921             case 201 /* FunctionExpression */:
15922             case 202 /* ArrowFunction */:
15923             case 214 /* ClassExpression */:
15924             case 266 /* JsxElement */:
15925             case 267 /* JsxSelfClosingElement */:
15926             case 270 /* JsxFragment */:
15927             case 13 /* RegularExpressionLiteral */:
15928             case 14 /* NoSubstitutionTemplateLiteral */:
15929             case 211 /* TemplateExpression */:
15930             case 200 /* ParenthesizedExpression */:
15931             case 215 /* OmittedExpression */:
15932                 return 20;
15933             default:
15934                 return -1;
15935         }
15936     }
15937     ts.getOperatorPrecedence = getOperatorPrecedence;
15938     function getBinaryOperatorPrecedence(kind) {
15939         switch (kind) {
15940             case 60 /* QuestionQuestionToken */:
15941                 return 4;
15942             case 56 /* BarBarToken */:
15943                 return 5;
15944             case 55 /* AmpersandAmpersandToken */:
15945                 return 6;
15946             case 51 /* BarToken */:
15947                 return 7;
15948             case 52 /* CaretToken */:
15949                 return 8;
15950             case 50 /* AmpersandToken */:
15951                 return 9;
15952             case 34 /* EqualsEqualsToken */:
15953             case 35 /* ExclamationEqualsToken */:
15954             case 36 /* EqualsEqualsEqualsToken */:
15955             case 37 /* ExclamationEqualsEqualsToken */:
15956                 return 10;
15957             case 29 /* LessThanToken */:
15958             case 31 /* GreaterThanToken */:
15959             case 32 /* LessThanEqualsToken */:
15960             case 33 /* GreaterThanEqualsToken */:
15961             case 98 /* InstanceOfKeyword */:
15962             case 97 /* InKeyword */:
15963             case 123 /* AsKeyword */:
15964                 return 11;
15965             case 47 /* LessThanLessThanToken */:
15966             case 48 /* GreaterThanGreaterThanToken */:
15967             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
15968                 return 12;
15969             case 39 /* PlusToken */:
15970             case 40 /* MinusToken */:
15971                 return 13;
15972             case 41 /* AsteriskToken */:
15973             case 43 /* SlashToken */:
15974             case 44 /* PercentToken */:
15975                 return 14;
15976             case 42 /* AsteriskAsteriskToken */:
15977                 return 15;
15978         }
15979         // -1 is lower than all other precedences.  Returning it will cause binary expression
15980         // parsing to stop.
15981         return -1;
15982     }
15983     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
15984     function createDiagnosticCollection() {
15985         var nonFileDiagnostics = []; // See GH#19873
15986         var filesWithDiagnostics = [];
15987         var fileDiagnostics = ts.createMap();
15988         var hasReadNonFileDiagnostics = false;
15989         return {
15990             add: add,
15991             lookup: lookup,
15992             getGlobalDiagnostics: getGlobalDiagnostics,
15993             getDiagnostics: getDiagnostics,
15994             reattachFileDiagnostics: reattachFileDiagnostics
15995         };
15996         function reattachFileDiagnostics(newFile) {
15997             ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
15998         }
15999         function lookup(diagnostic) {
16000             var diagnostics;
16001             if (diagnostic.file) {
16002                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16003             }
16004             else {
16005                 diagnostics = nonFileDiagnostics;
16006             }
16007             if (!diagnostics) {
16008                 return undefined;
16009             }
16010             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
16011             if (result >= 0) {
16012                 return diagnostics[result];
16013             }
16014             return undefined;
16015         }
16016         function add(diagnostic) {
16017             var diagnostics;
16018             if (diagnostic.file) {
16019                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16020                 if (!diagnostics) {
16021                     diagnostics = []; // See GH#19873
16022                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16023                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16024                 }
16025             }
16026             else {
16027                 // If we've already read the non-file diagnostics, do not modify the existing array.
16028                 if (hasReadNonFileDiagnostics) {
16029                     hasReadNonFileDiagnostics = false;
16030                     nonFileDiagnostics = nonFileDiagnostics.slice();
16031                 }
16032                 diagnostics = nonFileDiagnostics;
16033             }
16034             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16035         }
16036         function getGlobalDiagnostics() {
16037             hasReadNonFileDiagnostics = true;
16038             return nonFileDiagnostics;
16039         }
16040         function getDiagnostics(fileName) {
16041             if (fileName) {
16042                 return fileDiagnostics.get(fileName) || [];
16043             }
16044             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16045             if (!nonFileDiagnostics.length) {
16046                 return fileDiags;
16047             }
16048             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16049             return fileDiags;
16050         }
16051     }
16052     ts.createDiagnosticCollection = createDiagnosticCollection;
16053     var templateSubstitutionRegExp = /\$\{/g;
16054     function escapeTemplateSubstitution(str) {
16055         return str.replace(templateSubstitutionRegExp, "\\${");
16056     }
16057     /** @internal */
16058     function hasInvalidEscape(template) {
16059         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16060             ? template.templateFlags
16061             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16062     }
16063     ts.hasInvalidEscape = hasInvalidEscape;
16064     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16065     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16066     // the language service. These characters should be escaped when printing, and if any characters are added,
16067     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16068     // There is no reason for this other than that JSON.stringify does not handle it either.
16069     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16070     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16071     // Template strings should be preserved as much as possible
16072     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16073     var escapedCharsMap = ts.createMapFromTemplate({
16074         "\t": "\\t",
16075         "\v": "\\v",
16076         "\f": "\\f",
16077         "\b": "\\b",
16078         "\r": "\\r",
16079         "\n": "\\n",
16080         "\\": "\\\\",
16081         "\"": "\\\"",
16082         "\'": "\\\'",
16083         "\`": "\\\`",
16084         "\u2028": "\\u2028",
16085         "\u2029": "\\u2029",
16086         "\u0085": "\\u0085" // nextLine
16087     });
16088     function encodeUtf16EscapeSequence(charCode) {
16089         var hexCharCode = charCode.toString(16).toUpperCase();
16090         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16091         return "\\u" + paddedHexCode;
16092     }
16093     function getReplacement(c, offset, input) {
16094         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16095             var lookAhead = input.charCodeAt(offset + c.length);
16096             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16097                 // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode)
16098                 return "\\x00";
16099             }
16100             // Otherwise, keep printing a literal \0 for the null character
16101             return "\\0";
16102         }
16103         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16104     }
16105     /**
16106      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16107      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16108      * Note that this doesn't actually wrap the input in double quotes.
16109      */
16110     function escapeString(s, quoteChar) {
16111         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16112             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16113                 doubleQuoteEscapedCharsRegExp;
16114         return s.replace(escapedCharsRegExp, getReplacement);
16115     }
16116     ts.escapeString = escapeString;
16117     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16118     function escapeNonAsciiString(s, quoteChar) {
16119         s = escapeString(s, quoteChar);
16120         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16121         // Otherwise just return the original string.
16122         return nonAsciiCharacters.test(s) ?
16123             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16124             s;
16125     }
16126     ts.escapeNonAsciiString = escapeNonAsciiString;
16127     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16128     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16129     // the language service. These characters should be escaped when printing, and if any characters are added,
16130     // the map below must be updated.
16131     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16132     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16133     var jsxEscapedCharsMap = ts.createMapFromTemplate({
16134         "\"": "&quot;",
16135         "\'": "&apos;"
16136     });
16137     function encodeJsxCharacterEntity(charCode) {
16138         var hexCharCode = charCode.toString(16).toUpperCase();
16139         return "&#x" + hexCharCode + ";";
16140     }
16141     function getJsxAttributeStringReplacement(c) {
16142         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16143             return "&#0;";
16144         }
16145         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16146     }
16147     function escapeJsxAttributeString(s, quoteChar) {
16148         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16149             jsxDoubleQuoteEscapedCharsRegExp;
16150         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16151     }
16152     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16153     /**
16154      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16155      *
16156      * @return non-quoted string
16157      */
16158     function stripQuotes(name) {
16159         var length = name.length;
16160         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16161             return name.substring(1, length - 1);
16162         }
16163         return name;
16164     }
16165     ts.stripQuotes = stripQuotes;
16166     function isQuoteOrBacktick(charCode) {
16167         return charCode === 39 /* singleQuote */ ||
16168             charCode === 34 /* doubleQuote */ ||
16169             charCode === 96 /* backtick */;
16170     }
16171     function isIntrinsicJsxName(name) {
16172         var ch = name.charCodeAt(0);
16173         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16174     }
16175     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16176     var indentStrings = ["", "    "];
16177     function getIndentString(level) {
16178         if (indentStrings[level] === undefined) {
16179             indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
16180         }
16181         return indentStrings[level];
16182     }
16183     ts.getIndentString = getIndentString;
16184     function getIndentSize() {
16185         return indentStrings[1].length;
16186     }
16187     ts.getIndentSize = getIndentSize;
16188     function createTextWriter(newLine) {
16189         var output;
16190         var indent;
16191         var lineStart;
16192         var lineCount;
16193         var linePos;
16194         var hasTrailingComment = false;
16195         function updateLineCountAndPosFor(s) {
16196             var lineStartsOfS = ts.computeLineStarts(s);
16197             if (lineStartsOfS.length > 1) {
16198                 lineCount = lineCount + lineStartsOfS.length - 1;
16199                 linePos = output.length - s.length + ts.last(lineStartsOfS);
16200                 lineStart = (linePos - output.length) === 0;
16201             }
16202             else {
16203                 lineStart = false;
16204             }
16205         }
16206         function writeText(s) {
16207             if (s && s.length) {
16208                 if (lineStart) {
16209                     s = getIndentString(indent) + s;
16210                     lineStart = false;
16211                 }
16212                 output += s;
16213                 updateLineCountAndPosFor(s);
16214             }
16215         }
16216         function write(s) {
16217             if (s)
16218                 hasTrailingComment = false;
16219             writeText(s);
16220         }
16221         function writeComment(s) {
16222             if (s)
16223                 hasTrailingComment = true;
16224             writeText(s);
16225         }
16226         function reset() {
16227             output = "";
16228             indent = 0;
16229             lineStart = true;
16230             lineCount = 0;
16231             linePos = 0;
16232             hasTrailingComment = false;
16233         }
16234         function rawWrite(s) {
16235             if (s !== undefined) {
16236                 output += s;
16237                 updateLineCountAndPosFor(s);
16238                 hasTrailingComment = false;
16239             }
16240         }
16241         function writeLiteral(s) {
16242             if (s && s.length) {
16243                 write(s);
16244             }
16245         }
16246         function writeLine(force) {
16247             if (!lineStart || force) {
16248                 output += newLine;
16249                 lineCount++;
16250                 linePos = output.length;
16251                 lineStart = true;
16252                 hasTrailingComment = false;
16253             }
16254         }
16255         function getTextPosWithWriteLine() {
16256             return lineStart ? output.length : (output.length + newLine.length);
16257         }
16258         reset();
16259         return {
16260             write: write,
16261             rawWrite: rawWrite,
16262             writeLiteral: writeLiteral,
16263             writeLine: writeLine,
16264             increaseIndent: function () { indent++; },
16265             decreaseIndent: function () { indent--; },
16266             getIndent: function () { return indent; },
16267             getTextPos: function () { return output.length; },
16268             getLine: function () { return lineCount; },
16269             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16270             getText: function () { return output; },
16271             isAtStartOfLine: function () { return lineStart; },
16272             hasTrailingComment: function () { return hasTrailingComment; },
16273             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16274             clear: reset,
16275             reportInaccessibleThisError: ts.noop,
16276             reportPrivateInBaseOfClassExpression: ts.noop,
16277             reportInaccessibleUniqueSymbolError: ts.noop,
16278             trackSymbol: ts.noop,
16279             writeKeyword: write,
16280             writeOperator: write,
16281             writeParameter: write,
16282             writeProperty: write,
16283             writePunctuation: write,
16284             writeSpace: write,
16285             writeStringLiteral: write,
16286             writeSymbol: function (s, _) { return write(s); },
16287             writeTrailingSemicolon: write,
16288             writeComment: writeComment,
16289             getTextPosWithWriteLine: getTextPosWithWriteLine
16290         };
16291     }
16292     ts.createTextWriter = createTextWriter;
16293     function getTrailingSemicolonDeferringWriter(writer) {
16294         var pendingTrailingSemicolon = false;
16295         function commitPendingTrailingSemicolon() {
16296             if (pendingTrailingSemicolon) {
16297                 writer.writeTrailingSemicolon(";");
16298                 pendingTrailingSemicolon = false;
16299             }
16300         }
16301         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16302                 pendingTrailingSemicolon = true;
16303             },
16304             writeLiteral: function (s) {
16305                 commitPendingTrailingSemicolon();
16306                 writer.writeLiteral(s);
16307             },
16308             writeStringLiteral: function (s) {
16309                 commitPendingTrailingSemicolon();
16310                 writer.writeStringLiteral(s);
16311             },
16312             writeSymbol: function (s, sym) {
16313                 commitPendingTrailingSemicolon();
16314                 writer.writeSymbol(s, sym);
16315             },
16316             writePunctuation: function (s) {
16317                 commitPendingTrailingSemicolon();
16318                 writer.writePunctuation(s);
16319             },
16320             writeKeyword: function (s) {
16321                 commitPendingTrailingSemicolon();
16322                 writer.writeKeyword(s);
16323             },
16324             writeOperator: function (s) {
16325                 commitPendingTrailingSemicolon();
16326                 writer.writeOperator(s);
16327             },
16328             writeParameter: function (s) {
16329                 commitPendingTrailingSemicolon();
16330                 writer.writeParameter(s);
16331             },
16332             writeSpace: function (s) {
16333                 commitPendingTrailingSemicolon();
16334                 writer.writeSpace(s);
16335             },
16336             writeProperty: function (s) {
16337                 commitPendingTrailingSemicolon();
16338                 writer.writeProperty(s);
16339             },
16340             writeComment: function (s) {
16341                 commitPendingTrailingSemicolon();
16342                 writer.writeComment(s);
16343             },
16344             writeLine: function () {
16345                 commitPendingTrailingSemicolon();
16346                 writer.writeLine();
16347             },
16348             increaseIndent: function () {
16349                 commitPendingTrailingSemicolon();
16350                 writer.increaseIndent();
16351             },
16352             decreaseIndent: function () {
16353                 commitPendingTrailingSemicolon();
16354                 writer.decreaseIndent();
16355             } });
16356     }
16357     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16358     function hostUsesCaseSensitiveFileNames(host) {
16359         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16360     }
16361     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16362     function hostGetCanonicalFileName(host) {
16363         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16364     }
16365     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16366     function getResolvedExternalModuleName(host, file, referenceFile) {
16367         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16368     }
16369     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16370     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16371         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16372         if (!file || file.isDeclarationFile) {
16373             return undefined;
16374         }
16375         return getResolvedExternalModuleName(host, file);
16376     }
16377     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16378     /**
16379      * Resolves a local path to a path which is absolute to the base of the emit
16380      */
16381     function getExternalModuleNameFromPath(host, fileName, referencePath) {
16382         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16383         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16384         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16385         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16386         var extensionless = removeFileExtension(relativePath);
16387         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16388     }
16389     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16390     function getOwnEmitOutputFilePath(fileName, host, extension) {
16391         var compilerOptions = host.getCompilerOptions();
16392         var emitOutputFilePathWithoutExtension;
16393         if (compilerOptions.outDir) {
16394             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16395         }
16396         else {
16397             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16398         }
16399         return emitOutputFilePathWithoutExtension + extension;
16400     }
16401     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16402     function getDeclarationEmitOutputFilePath(fileName, host) {
16403         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16404     }
16405     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16406     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16407         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16408         var path = outputDir
16409             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16410             : fileName;
16411         return removeFileExtension(path) + ".d.ts" /* Dts */;
16412     }
16413     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16414     /**
16415      * Gets the source files that are expected to have an emit output.
16416      *
16417      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
16418      * transformations.
16419      *
16420      * @param host An EmitHost.
16421      * @param targetSourceFile An optional target source file to emit.
16422      */
16423     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
16424         var options = host.getCompilerOptions();
16425         if (options.outFile || options.out) {
16426             var moduleKind = getEmitModuleKind(options);
16427             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
16428             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
16429             return ts.filter(host.getSourceFiles(), function (sourceFile) {
16430                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
16431                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
16432             });
16433         }
16434         else {
16435             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
16436             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
16437         }
16438     }
16439     ts.getSourceFilesToEmit = getSourceFilesToEmit;
16440     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
16441     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
16442         var options = host.getCompilerOptions();
16443         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
16444             !sourceFile.isDeclarationFile &&
16445             !host.isSourceFileFromExternalLibrary(sourceFile) &&
16446             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
16447             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
16448     }
16449     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
16450     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
16451         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16452     }
16453     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
16454     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16455         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
16456         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
16457         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
16458         return ts.combinePaths(newDirPath, sourceFilePath);
16459     }
16460     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
16461     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
16462         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
16463             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
16464         }, sourceFiles);
16465     }
16466     ts.writeFile = writeFile;
16467     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
16468         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
16469             var parentDirectory = ts.getDirectoryPath(directoryPath);
16470             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
16471             createDirectory(directoryPath);
16472         }
16473     }
16474     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
16475         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
16476         // and fall back to creating it if the file write fails.
16477         try {
16478             writeFile(path, data, writeByteOrderMark);
16479         }
16480         catch (_a) {
16481             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
16482             writeFile(path, data, writeByteOrderMark);
16483         }
16484     }
16485     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
16486     function getLineOfLocalPosition(sourceFile, pos) {
16487         var lineStarts = ts.getLineStarts(sourceFile);
16488         return ts.computeLineOfPosition(lineStarts, pos);
16489     }
16490     ts.getLineOfLocalPosition = getLineOfLocalPosition;
16491     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
16492         return ts.computeLineOfPosition(lineMap, pos);
16493     }
16494     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
16495     function getFirstConstructorWithBody(node) {
16496         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
16497     }
16498     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
16499     function getSetAccessorValueParameter(accessor) {
16500         if (accessor && accessor.parameters.length > 0) {
16501             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
16502             return accessor.parameters[hasThis ? 1 : 0];
16503         }
16504     }
16505     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
16506     /** Get the type annotation for the value parameter. */
16507     function getSetAccessorTypeAnnotationNode(accessor) {
16508         var parameter = getSetAccessorValueParameter(accessor);
16509         return parameter && parameter.type;
16510     }
16511     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
16512     function getThisParameter(signature) {
16513         // callback tags do not currently support this parameters
16514         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
16515             var thisParameter = signature.parameters[0];
16516             if (parameterIsThisKeyword(thisParameter)) {
16517                 return thisParameter;
16518             }
16519         }
16520     }
16521     ts.getThisParameter = getThisParameter;
16522     function parameterIsThisKeyword(parameter) {
16523         return isThisIdentifier(parameter.name);
16524     }
16525     ts.parameterIsThisKeyword = parameterIsThisKeyword;
16526     function isThisIdentifier(node) {
16527         return !!node && node.kind === 75 /* Identifier */ && identifierIsThisKeyword(node);
16528     }
16529     ts.isThisIdentifier = isThisIdentifier;
16530     function identifierIsThisKeyword(id) {
16531         return id.originalKeywordKind === 104 /* ThisKeyword */;
16532     }
16533     ts.identifierIsThisKeyword = identifierIsThisKeyword;
16534     function getAllAccessorDeclarations(declarations, accessor) {
16535         // TODO: GH#18217
16536         var firstAccessor;
16537         var secondAccessor;
16538         var getAccessor;
16539         var setAccessor;
16540         if (hasDynamicName(accessor)) {
16541             firstAccessor = accessor;
16542             if (accessor.kind === 163 /* GetAccessor */) {
16543                 getAccessor = accessor;
16544             }
16545             else if (accessor.kind === 164 /* SetAccessor */) {
16546                 setAccessor = accessor;
16547             }
16548             else {
16549                 ts.Debug.fail("Accessor has wrong kind");
16550             }
16551         }
16552         else {
16553             ts.forEach(declarations, function (member) {
16554                 if (ts.isAccessor(member)
16555                     && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
16556                     var memberName = getPropertyNameForPropertyNameNode(member.name);
16557                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
16558                     if (memberName === accessorName) {
16559                         if (!firstAccessor) {
16560                             firstAccessor = member;
16561                         }
16562                         else if (!secondAccessor) {
16563                             secondAccessor = member;
16564                         }
16565                         if (member.kind === 163 /* GetAccessor */ && !getAccessor) {
16566                             // eslint-disable-next-line
16567                             getAccessor = member;
16568                         }
16569                         if (member.kind === 164 /* SetAccessor */ && !setAccessor) {
16570                             // eslint-disable-next-line
16571                             setAccessor = member;
16572                         }
16573                     }
16574                 }
16575             });
16576         }
16577         return {
16578             firstAccessor: firstAccessor,
16579             secondAccessor: secondAccessor,
16580             getAccessor: getAccessor,
16581             setAccessor: setAccessor
16582         };
16583     }
16584     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
16585     /**
16586      * Gets the effective type annotation of a variable, parameter, or property. If the node was
16587      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
16588      * functions only the JSDoc case.
16589      */
16590     function getEffectiveTypeAnnotationNode(node) {
16591         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
16592             return undefined;
16593         var type = node.type;
16594         if (type || !isInJSFile(node))
16595             return type;
16596         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
16597     }
16598     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
16599     function getTypeAnnotationNode(node) {
16600         return node.type;
16601     }
16602     ts.getTypeAnnotationNode = getTypeAnnotationNode;
16603     /**
16604      * Gets the effective return type annotation of a signature. If the node was parsed in a
16605      * JavaScript file, gets the return type annotation from JSDoc.
16606      */
16607     function getEffectiveReturnTypeNode(node) {
16608         return ts.isJSDocSignature(node) ?
16609             node.type && node.type.typeExpression && node.type.typeExpression.type :
16610             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
16611     }
16612     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
16613     function getJSDocTypeParameterDeclarations(node) {
16614         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
16615     }
16616     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
16617     /** template tags are only available when a typedef isn't already using them */
16618     function isNonTypeAliasTemplate(tag) {
16619         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 303 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
16620     }
16621     /**
16622      * Gets the effective type annotation of the value parameter of a set accessor. If the node
16623      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
16624      */
16625     function getEffectiveSetAccessorTypeAnnotationNode(node) {
16626         var parameter = getSetAccessorValueParameter(node);
16627         return parameter && getEffectiveTypeAnnotationNode(parameter);
16628     }
16629     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
16630     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
16631         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
16632     }
16633     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
16634     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
16635         // If the leading comments start on different line than the start of node, write new line
16636         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
16637             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
16638             writer.writeLine();
16639         }
16640     }
16641     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
16642     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
16643         // If the leading comments start on different line than the start of node, write new line
16644         if (pos !== commentPos &&
16645             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
16646             writer.writeLine();
16647         }
16648     }
16649     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
16650     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
16651         if (comments && comments.length > 0) {
16652             if (leadingSeparator) {
16653                 writer.writeSpace(" ");
16654             }
16655             var emitInterveningSeparator = false;
16656             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
16657                 var comment = comments_1[_i];
16658                 if (emitInterveningSeparator) {
16659                     writer.writeSpace(" ");
16660                     emitInterveningSeparator = false;
16661                 }
16662                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
16663                 if (comment.hasTrailingNewLine) {
16664                     writer.writeLine();
16665                 }
16666                 else {
16667                     emitInterveningSeparator = true;
16668                 }
16669             }
16670             if (emitInterveningSeparator && trailingSeparator) {
16671                 writer.writeSpace(" ");
16672             }
16673         }
16674     }
16675     ts.emitComments = emitComments;
16676     /**
16677      * Detached comment is a comment at the top of file or function body that is separated from
16678      * the next statement by space.
16679      */
16680     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
16681         var leadingComments;
16682         var currentDetachedCommentInfo;
16683         if (removeComments) {
16684             // removeComments is true, only reserve pinned comment at the top of file
16685             // For example:
16686             //      /*! Pinned Comment */
16687             //
16688             //      var x = 10;
16689             if (node.pos === 0) {
16690                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
16691             }
16692         }
16693         else {
16694             // removeComments is false, just get detached as normal and bypass the process to filter comment
16695             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
16696         }
16697         if (leadingComments) {
16698             var detachedComments = [];
16699             var lastComment = void 0;
16700             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
16701                 var comment = leadingComments_1[_i];
16702                 if (lastComment) {
16703                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
16704                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
16705                     if (commentLine >= lastCommentLine + 2) {
16706                         // There was a blank line between the last comment and this comment.  This
16707                         // comment is not part of the copyright comments.  Return what we have so
16708                         // far.
16709                         break;
16710                     }
16711                 }
16712                 detachedComments.push(comment);
16713                 lastComment = comment;
16714             }
16715             if (detachedComments.length) {
16716                 // All comments look like they could have been part of the copyright header.  Make
16717                 // sure there is at least one blank line between it and the node.  If not, it's not
16718                 // a copyright header.
16719                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
16720                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
16721                 if (nodeLine >= lastCommentLine + 2) {
16722                     // Valid detachedComments
16723                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
16724                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
16725                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
16726                 }
16727             }
16728         }
16729         return currentDetachedCommentInfo;
16730         function isPinnedCommentLocal(comment) {
16731             return isPinnedComment(text, comment.pos);
16732         }
16733     }
16734     ts.emitDetachedComments = emitDetachedComments;
16735     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
16736         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
16737             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
16738             var lineCount = lineMap.length;
16739             var firstCommentLineIndent = void 0;
16740             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
16741                 var nextLineStart = (currentLine + 1) === lineCount
16742                     ? text.length + 1
16743                     : lineMap[currentLine + 1];
16744                 if (pos !== commentPos) {
16745                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
16746                     if (firstCommentLineIndent === undefined) {
16747                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
16748                     }
16749                     // These are number of spaces writer is going to write at current indent
16750                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
16751                     // Number of spaces we want to be writing
16752                     // eg: Assume writer indent
16753                     // module m {
16754                     //         /* starts at character 9 this is line 1
16755                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
16756                     //   More left indented comment */                            --2  = 8 - 8 + 2
16757                     //     class c { }
16758                     // }
16759                     // module m {
16760                     //     /* this is line 1 -- Assume current writer indent 8
16761                     //      * line                                                --3 = 8 - 4 + 5
16762                     //            More right indented comment */                  --4 = 8 - 4 + 11
16763                     //     class c { }
16764                     // }
16765                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
16766                     if (spacesToEmit > 0) {
16767                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
16768                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
16769                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
16770                         writer.rawWrite(indentSizeSpaceString);
16771                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
16772                         while (numberOfSingleSpacesToEmit) {
16773                             writer.rawWrite(" ");
16774                             numberOfSingleSpacesToEmit--;
16775                         }
16776                     }
16777                     else {
16778                         // No spaces to emit write empty string
16779                         writer.rawWrite("");
16780                     }
16781                 }
16782                 // Write the comment line text
16783                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
16784                 pos = nextLineStart;
16785             }
16786         }
16787         else {
16788             // Single line comment of style //....
16789             writer.writeComment(text.substring(commentPos, commentEnd));
16790         }
16791     }
16792     ts.writeCommentRange = writeCommentRange;
16793     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
16794         var end = Math.min(commentEnd, nextLineStart - 1);
16795         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
16796         if (currentLineText) {
16797             // trimmed forward and ending spaces text
16798             writer.writeComment(currentLineText);
16799             if (end !== commentEnd) {
16800                 writer.writeLine();
16801             }
16802         }
16803         else {
16804             // Empty string - make sure we write empty line
16805             writer.rawWrite(newLine);
16806         }
16807     }
16808     function calculateIndent(text, pos, end) {
16809         var currentLineIndent = 0;
16810         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
16811             if (text.charCodeAt(pos) === 9 /* tab */) {
16812                 // Tabs = TabSize = indent size and go to next tabStop
16813                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
16814             }
16815             else {
16816                 // Single space
16817                 currentLineIndent++;
16818             }
16819         }
16820         return currentLineIndent;
16821     }
16822     function hasModifiers(node) {
16823         return getModifierFlags(node) !== 0 /* None */;
16824     }
16825     ts.hasModifiers = hasModifiers;
16826     function hasModifier(node, flags) {
16827         return !!getSelectedModifierFlags(node, flags);
16828     }
16829     ts.hasModifier = hasModifier;
16830     function hasStaticModifier(node) {
16831         return hasModifier(node, 32 /* Static */);
16832     }
16833     ts.hasStaticModifier = hasStaticModifier;
16834     function hasReadonlyModifier(node) {
16835         return hasModifier(node, 64 /* Readonly */);
16836     }
16837     ts.hasReadonlyModifier = hasReadonlyModifier;
16838     function getSelectedModifierFlags(node, flags) {
16839         return getModifierFlags(node) & flags;
16840     }
16841     ts.getSelectedModifierFlags = getSelectedModifierFlags;
16842     function getModifierFlags(node) {
16843         if (node.kind >= 0 /* FirstToken */ && node.kind <= 152 /* LastToken */) {
16844             return 0 /* None */;
16845         }
16846         if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
16847             return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
16848         }
16849         var flags = getModifierFlagsNoCache(node);
16850         node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
16851         return flags;
16852     }
16853     ts.getModifierFlags = getModifierFlags;
16854     function getModifierFlagsNoCache(node) {
16855         var flags = 0 /* None */;
16856         if (node.modifiers) {
16857             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
16858                 var modifier = _a[_i];
16859                 flags |= modifierToFlag(modifier.kind);
16860             }
16861         }
16862         if (isInJSFile(node) && !!node.parent) {
16863             // getModifierFlagsNoCache should only be called when parent pointers are set,
16864             // or when !(node.flags & NodeFlags.Synthesized) && node.kind !== SyntaxKind.SourceFile)
16865             var tags = (ts.getJSDocPublicTag(node) ? 4 /* Public */ : 0 /* None */)
16866                 | (ts.getJSDocPrivateTag(node) ? 8 /* Private */ : 0 /* None */)
16867                 | (ts.getJSDocProtectedTag(node) ? 16 /* Protected */ : 0 /* None */)
16868                 | (ts.getJSDocReadonlyTag(node) ? 64 /* Readonly */ : 0 /* None */);
16869             flags |= tags;
16870         }
16871         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 75 /* Identifier */ && node.isInJSDocNamespace)) {
16872             flags |= 1 /* Export */;
16873         }
16874         return flags;
16875     }
16876     ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
16877     function modifierToFlag(token) {
16878         switch (token) {
16879             case 120 /* StaticKeyword */: return 32 /* Static */;
16880             case 119 /* PublicKeyword */: return 4 /* Public */;
16881             case 118 /* ProtectedKeyword */: return 16 /* Protected */;
16882             case 117 /* PrivateKeyword */: return 8 /* Private */;
16883             case 122 /* AbstractKeyword */: return 128 /* Abstract */;
16884             case 89 /* ExportKeyword */: return 1 /* Export */;
16885             case 130 /* DeclareKeyword */: return 2 /* Ambient */;
16886             case 81 /* ConstKeyword */: return 2048 /* Const */;
16887             case 84 /* DefaultKeyword */: return 512 /* Default */;
16888             case 126 /* AsyncKeyword */: return 256 /* Async */;
16889             case 138 /* ReadonlyKeyword */: return 64 /* Readonly */;
16890         }
16891         return 0 /* None */;
16892     }
16893     ts.modifierToFlag = modifierToFlag;
16894     function isLogicalOperator(token) {
16895         return token === 56 /* BarBarToken */
16896             || token === 55 /* AmpersandAmpersandToken */
16897             || token === 53 /* ExclamationToken */;
16898     }
16899     ts.isLogicalOperator = isLogicalOperator;
16900     function isAssignmentOperator(token) {
16901         return token >= 62 /* FirstAssignment */ && token <= 74 /* LastAssignment */;
16902     }
16903     ts.isAssignmentOperator = isAssignmentOperator;
16904     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
16905     function tryGetClassExtendingExpressionWithTypeArguments(node) {
16906         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
16907         return cls && !cls.isImplements ? cls.class : undefined;
16908     }
16909     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
16910     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
16911         return ts.isExpressionWithTypeArguments(node)
16912             && ts.isHeritageClause(node.parent)
16913             && ts.isClassLike(node.parent.parent)
16914             ? { class: node.parent.parent, isImplements: node.parent.token === 113 /* ImplementsKeyword */ }
16915             : undefined;
16916     }
16917     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
16918     function isAssignmentExpression(node, excludeCompoundAssignment) {
16919         return ts.isBinaryExpression(node)
16920             && (excludeCompoundAssignment
16921                 ? node.operatorToken.kind === 62 /* EqualsToken */
16922                 : isAssignmentOperator(node.operatorToken.kind))
16923             && ts.isLeftHandSideExpression(node.left);
16924     }
16925     ts.isAssignmentExpression = isAssignmentExpression;
16926     function isDestructuringAssignment(node) {
16927         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
16928             var kind = node.left.kind;
16929             return kind === 193 /* ObjectLiteralExpression */
16930                 || kind === 192 /* ArrayLiteralExpression */;
16931         }
16932         return false;
16933     }
16934     ts.isDestructuringAssignment = isDestructuringAssignment;
16935     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
16936         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
16937     }
16938     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
16939     function isEntityNameExpression(node) {
16940         return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
16941     }
16942     ts.isEntityNameExpression = isEntityNameExpression;
16943     function getFirstIdentifier(node) {
16944         switch (node.kind) {
16945             case 75 /* Identifier */:
16946                 return node;
16947             case 153 /* QualifiedName */:
16948                 do {
16949                     node = node.left;
16950                 } while (node.kind !== 75 /* Identifier */);
16951                 return node;
16952             case 194 /* PropertyAccessExpression */:
16953                 do {
16954                     node = node.expression;
16955                 } while (node.kind !== 75 /* Identifier */);
16956                 return node;
16957         }
16958     }
16959     ts.getFirstIdentifier = getFirstIdentifier;
16960     function isDottedName(node) {
16961         return node.kind === 75 /* Identifier */ || node.kind === 104 /* ThisKeyword */ || node.kind === 102 /* SuperKeyword */ ||
16962             node.kind === 194 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
16963             node.kind === 200 /* ParenthesizedExpression */ && isDottedName(node.expression);
16964     }
16965     ts.isDottedName = isDottedName;
16966     function isPropertyAccessEntityNameExpression(node) {
16967         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
16968     }
16969     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
16970     function tryGetPropertyAccessOrIdentifierToString(expr) {
16971         if (ts.isPropertyAccessExpression(expr)) {
16972             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
16973             if (baseStr !== undefined) {
16974                 return baseStr + "." + expr.name;
16975             }
16976         }
16977         else if (ts.isIdentifier(expr)) {
16978             return ts.unescapeLeadingUnderscores(expr.escapedText);
16979         }
16980         return undefined;
16981     }
16982     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
16983     function isPrototypeAccess(node) {
16984         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
16985     }
16986     ts.isPrototypeAccess = isPrototypeAccess;
16987     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
16988         return (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) ||
16989             (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node);
16990     }
16991     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
16992     function isEmptyObjectLiteral(expression) {
16993         return expression.kind === 193 /* ObjectLiteralExpression */ &&
16994             expression.properties.length === 0;
16995     }
16996     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
16997     function isEmptyArrayLiteral(expression) {
16998         return expression.kind === 192 /* ArrayLiteralExpression */ &&
16999             expression.elements.length === 0;
17000     }
17001     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
17002     function getLocalSymbolForExportDefault(symbol) {
17003         return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
17004     }
17005     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
17006     function isExportDefaultSymbol(symbol) {
17007         return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
17008     }
17009     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
17010     function tryExtractTSExtension(fileName) {
17011         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17012     }
17013     ts.tryExtractTSExtension = tryExtractTSExtension;
17014     /**
17015      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17016      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17017      */
17018     function getExpandedCharCodes(input) {
17019         var output = [];
17020         var length = input.length;
17021         for (var i = 0; i < length; i++) {
17022             var charCode = input.charCodeAt(i);
17023             // handle utf8
17024             if (charCode < 0x80) {
17025                 output.push(charCode);
17026             }
17027             else if (charCode < 0x800) {
17028                 output.push((charCode >> 6) | 192);
17029                 output.push((charCode & 63) | 128);
17030             }
17031             else if (charCode < 0x10000) {
17032                 output.push((charCode >> 12) | 224);
17033                 output.push(((charCode >> 6) & 63) | 128);
17034                 output.push((charCode & 63) | 128);
17035             }
17036             else if (charCode < 0x20000) {
17037                 output.push((charCode >> 18) | 240);
17038                 output.push(((charCode >> 12) & 63) | 128);
17039                 output.push(((charCode >> 6) & 63) | 128);
17040                 output.push((charCode & 63) | 128);
17041             }
17042             else {
17043                 ts.Debug.assert(false, "Unexpected code point");
17044             }
17045         }
17046         return output;
17047     }
17048     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17049     /**
17050      * Converts a string to a base-64 encoded ASCII string.
17051      */
17052     function convertToBase64(input) {
17053         var result = "";
17054         var charCodes = getExpandedCharCodes(input);
17055         var i = 0;
17056         var length = charCodes.length;
17057         var byte1, byte2, byte3, byte4;
17058         while (i < length) {
17059             // Convert every 6-bits in the input 3 character points
17060             // into a base64 digit
17061             byte1 = charCodes[i] >> 2;
17062             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17063             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17064             byte4 = charCodes[i + 2] & 63;
17065             // We are out of characters in the input, set the extra
17066             // digits to 64 (padding character).
17067             if (i + 1 >= length) {
17068                 byte3 = byte4 = 64;
17069             }
17070             else if (i + 2 >= length) {
17071                 byte4 = 64;
17072             }
17073             // Write to the output
17074             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17075             i += 3;
17076         }
17077         return result;
17078     }
17079     ts.convertToBase64 = convertToBase64;
17080     function getStringFromExpandedCharCodes(codes) {
17081         var output = "";
17082         var i = 0;
17083         var length = codes.length;
17084         while (i < length) {
17085             var charCode = codes[i];
17086             if (charCode < 0x80) {
17087                 output += String.fromCharCode(charCode);
17088                 i++;
17089             }
17090             else if ((charCode & 192) === 192) {
17091                 var value = charCode & 63;
17092                 i++;
17093                 var nextCode = codes[i];
17094                 while ((nextCode & 192) === 128) {
17095                     value = (value << 6) | (nextCode & 63);
17096                     i++;
17097                     nextCode = codes[i];
17098                 }
17099                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17100                 output += String.fromCharCode(value);
17101             }
17102             else {
17103                 // We don't want to kill the process when decoding fails (due to a following char byte not
17104                 // following a leading char), so we just print the (bad) value
17105                 output += String.fromCharCode(charCode);
17106                 i++;
17107             }
17108         }
17109         return output;
17110     }
17111     function base64encode(host, input) {
17112         if (host && host.base64encode) {
17113             return host.base64encode(input);
17114         }
17115         return convertToBase64(input);
17116     }
17117     ts.base64encode = base64encode;
17118     function base64decode(host, input) {
17119         if (host && host.base64decode) {
17120             return host.base64decode(input);
17121         }
17122         var length = input.length;
17123         var expandedCharCodes = [];
17124         var i = 0;
17125         while (i < length) {
17126             // Stop decoding once padding characters are present
17127             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17128                 break;
17129             }
17130             // convert 4 input digits into three characters, ignoring padding characters at the end
17131             var ch1 = base64Digits.indexOf(input[i]);
17132             var ch2 = base64Digits.indexOf(input[i + 1]);
17133             var ch3 = base64Digits.indexOf(input[i + 2]);
17134             var ch4 = base64Digits.indexOf(input[i + 3]);
17135             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17136             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17137             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17138             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17139                 expandedCharCodes.push(code1);
17140             }
17141             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17142                 expandedCharCodes.push(code1, code2);
17143             }
17144             else {
17145                 expandedCharCodes.push(code1, code2, code3);
17146             }
17147             i += 4;
17148         }
17149         return getStringFromExpandedCharCodes(expandedCharCodes);
17150     }
17151     ts.base64decode = base64decode;
17152     function readJson(path, host) {
17153         try {
17154             var jsonText = host.readFile(path);
17155             if (!jsonText)
17156                 return {};
17157             var result = ts.parseConfigFileTextToJson(path, jsonText);
17158             if (result.error) {
17159                 return {};
17160             }
17161             return result.config;
17162         }
17163         catch (e) {
17164             // gracefully handle if readFile fails or returns not JSON
17165             return {};
17166         }
17167     }
17168     ts.readJson = readJson;
17169     function directoryProbablyExists(directoryName, host) {
17170         // if host does not support 'directoryExists' assume that directory will exist
17171         return !host.directoryExists || host.directoryExists(directoryName);
17172     }
17173     ts.directoryProbablyExists = directoryProbablyExists;
17174     var carriageReturnLineFeed = "\r\n";
17175     var lineFeed = "\n";
17176     function getNewLineCharacter(options, getNewLine) {
17177         switch (options.newLine) {
17178             case 0 /* CarriageReturnLineFeed */:
17179                 return carriageReturnLineFeed;
17180             case 1 /* LineFeed */:
17181                 return lineFeed;
17182         }
17183         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17184     }
17185     ts.getNewLineCharacter = getNewLineCharacter;
17186     /**
17187      * Creates a new TextRange from the provided pos and end.
17188      *
17189      * @param pos The start position.
17190      * @param end The end position.
17191      */
17192     function createRange(pos, end) {
17193         if (end === void 0) { end = pos; }
17194         ts.Debug.assert(end >= pos || end === -1);
17195         return { pos: pos, end: end };
17196     }
17197     ts.createRange = createRange;
17198     /**
17199      * Creates a new TextRange from a provided range with a new end position.
17200      *
17201      * @param range A TextRange.
17202      * @param end The new end position.
17203      */
17204     function moveRangeEnd(range, end) {
17205         return createRange(range.pos, end);
17206     }
17207     ts.moveRangeEnd = moveRangeEnd;
17208     /**
17209      * Creates a new TextRange from a provided range with a new start position.
17210      *
17211      * @param range A TextRange.
17212      * @param pos The new Start position.
17213      */
17214     function moveRangePos(range, pos) {
17215         return createRange(pos, range.end);
17216     }
17217     ts.moveRangePos = moveRangePos;
17218     /**
17219      * Moves the start position of a range past any decorators.
17220      */
17221     function moveRangePastDecorators(node) {
17222         return node.decorators && node.decorators.length > 0
17223             ? moveRangePos(node, node.decorators.end)
17224             : node;
17225     }
17226     ts.moveRangePastDecorators = moveRangePastDecorators;
17227     /**
17228      * Moves the start position of a range past any decorators or modifiers.
17229      */
17230     function moveRangePastModifiers(node) {
17231         return node.modifiers && node.modifiers.length > 0
17232             ? moveRangePos(node, node.modifiers.end)
17233             : moveRangePastDecorators(node);
17234     }
17235     ts.moveRangePastModifiers = moveRangePastModifiers;
17236     /**
17237      * Determines whether a TextRange has the same start and end positions.
17238      *
17239      * @param range A TextRange.
17240      */
17241     function isCollapsedRange(range) {
17242         return range.pos === range.end;
17243     }
17244     ts.isCollapsedRange = isCollapsedRange;
17245     /**
17246      * Creates a new TextRange for a token at the provides start position.
17247      *
17248      * @param pos The start position.
17249      * @param token The token.
17250      */
17251     function createTokenRange(pos, token) {
17252         return createRange(pos, pos + ts.tokenToString(token).length);
17253     }
17254     ts.createTokenRange = createTokenRange;
17255     function rangeIsOnSingleLine(range, sourceFile) {
17256         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17257     }
17258     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17259     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17260         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17261     }
17262     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17263     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17264         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17265     }
17266     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17267     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17268         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17269     }
17270     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17271     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17272         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17273     }
17274     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17275     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17276         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17277         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17278     }
17279     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17280     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17281         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17282     }
17283     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17284     function isNodeArrayMultiLine(list, sourceFile) {
17285         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17286     }
17287     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17288     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17289         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17290     }
17291     ts.positionsAreOnSameLine = positionsAreOnSameLine;
17292     function getStartPositionOfRange(range, sourceFile, includeComments) {
17293         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17294     }
17295     ts.getStartPositionOfRange = getStartPositionOfRange;
17296     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17297         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17298         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17299         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17300     }
17301     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17302     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17303         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17304         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17305     }
17306     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17307     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17308         if (stopPos === void 0) { stopPos = 0; }
17309         while (pos-- > stopPos) {
17310             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17311                 return pos;
17312             }
17313         }
17314     }
17315     /**
17316      * Determines whether a name was originally the declaration name of an enum or namespace
17317      * declaration.
17318      */
17319     function isDeclarationNameOfEnumOrNamespace(node) {
17320         var parseNode = ts.getParseTreeNode(node);
17321         if (parseNode) {
17322             switch (parseNode.parent.kind) {
17323                 case 248 /* EnumDeclaration */:
17324                 case 249 /* ModuleDeclaration */:
17325                     return parseNode === parseNode.parent.name;
17326             }
17327         }
17328         return false;
17329     }
17330     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17331     function getInitializedVariables(node) {
17332         return ts.filter(node.declarations, isInitializedVariable);
17333     }
17334     ts.getInitializedVariables = getInitializedVariables;
17335     function isInitializedVariable(node) {
17336         return node.initializer !== undefined;
17337     }
17338     function isWatchSet(options) {
17339         // Firefox has Object.prototype.watch
17340         return options.watch && options.hasOwnProperty("watch");
17341     }
17342     ts.isWatchSet = isWatchSet;
17343     function closeFileWatcher(watcher) {
17344         watcher.close();
17345     }
17346     ts.closeFileWatcher = closeFileWatcher;
17347     function getCheckFlags(symbol) {
17348         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
17349     }
17350     ts.getCheckFlags = getCheckFlags;
17351     function getDeclarationModifierFlagsFromSymbol(s) {
17352         if (s.valueDeclaration) {
17353             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
17354             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
17355         }
17356         if (getCheckFlags(s) & 6 /* Synthetic */) {
17357             var checkFlags = s.checkFlags;
17358             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
17359                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
17360                     16 /* Protected */;
17361             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
17362             return accessModifier | staticModifier;
17363         }
17364         if (s.flags & 4194304 /* Prototype */) {
17365             return 4 /* Public */ | 32 /* Static */;
17366         }
17367         return 0;
17368     }
17369     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
17370     function skipAlias(symbol, checker) {
17371         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
17372     }
17373     ts.skipAlias = skipAlias;
17374     /** See comment on `declareModuleMember` in `binder.ts`. */
17375     function getCombinedLocalAndExportSymbolFlags(symbol) {
17376         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
17377     }
17378     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
17379     function isWriteOnlyAccess(node) {
17380         return accessKind(node) === 1 /* Write */;
17381     }
17382     ts.isWriteOnlyAccess = isWriteOnlyAccess;
17383     function isWriteAccess(node) {
17384         return accessKind(node) !== 0 /* Read */;
17385     }
17386     ts.isWriteAccess = isWriteAccess;
17387     var AccessKind;
17388     (function (AccessKind) {
17389         /** Only reads from a variable. */
17390         AccessKind[AccessKind["Read"] = 0] = "Read";
17391         /** Only writes to a variable without using the result. E.g.: `x++;`. */
17392         AccessKind[AccessKind["Write"] = 1] = "Write";
17393         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
17394         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
17395     })(AccessKind || (AccessKind = {}));
17396     function accessKind(node) {
17397         var parent = node.parent;
17398         if (!parent)
17399             return 0 /* Read */;
17400         switch (parent.kind) {
17401             case 200 /* ParenthesizedExpression */:
17402                 return accessKind(parent);
17403             case 208 /* PostfixUnaryExpression */:
17404             case 207 /* PrefixUnaryExpression */:
17405                 var operator = parent.operator;
17406                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
17407             case 209 /* BinaryExpression */:
17408                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
17409                 return left === node && isAssignmentOperator(operatorToken.kind) ?
17410                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
17411                     : 0 /* Read */;
17412             case 194 /* PropertyAccessExpression */:
17413                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
17414             case 281 /* PropertyAssignment */: {
17415                 var parentAccess = accessKind(parent.parent);
17416                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
17417                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
17418             }
17419             case 282 /* ShorthandPropertyAssignment */:
17420                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
17421                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
17422             case 192 /* ArrayLiteralExpression */:
17423                 return accessKind(parent);
17424             default:
17425                 return 0 /* Read */;
17426         }
17427         function writeOrReadWrite() {
17428             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
17429             return parent.parent && skipParenthesesUp(parent.parent).kind === 226 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
17430         }
17431     }
17432     function reverseAccessKind(a) {
17433         switch (a) {
17434             case 0 /* Read */:
17435                 return 1 /* Write */;
17436             case 1 /* Write */:
17437                 return 0 /* Read */;
17438             case 2 /* ReadWrite */:
17439                 return 2 /* ReadWrite */;
17440             default:
17441                 return ts.Debug.assertNever(a);
17442         }
17443     }
17444     function compareDataObjects(dst, src) {
17445         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
17446             return false;
17447         }
17448         for (var e in dst) {
17449             if (typeof dst[e] === "object") {
17450                 if (!compareDataObjects(dst[e], src[e])) {
17451                     return false;
17452                 }
17453             }
17454             else if (typeof dst[e] !== "function") {
17455                 if (dst[e] !== src[e]) {
17456                     return false;
17457                 }
17458             }
17459         }
17460         return true;
17461     }
17462     ts.compareDataObjects = compareDataObjects;
17463     /**
17464      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
17465      */
17466     function clearMap(map, onDeleteValue) {
17467         // Remove all
17468         map.forEach(onDeleteValue);
17469         map.clear();
17470     }
17471     ts.clearMap = clearMap;
17472     /**
17473      * Mutates the map with newMap such that keys in map will be same as newMap.
17474      */
17475     function mutateMapSkippingNewValues(map, newMap, options) {
17476         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
17477         // Needs update
17478         map.forEach(function (existingValue, key) {
17479             var valueInNewMap = newMap.get(key);
17480             // Not present any more in new map, remove it
17481             if (valueInNewMap === undefined) {
17482                 map.delete(key);
17483                 onDeleteValue(existingValue, key);
17484             }
17485             // If present notify about existing values
17486             else if (onExistingValue) {
17487                 onExistingValue(existingValue, valueInNewMap, key);
17488             }
17489         });
17490     }
17491     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
17492     /**
17493      * Mutates the map with newMap such that keys in map will be same as newMap.
17494      */
17495     function mutateMap(map, newMap, options) {
17496         // Needs update
17497         mutateMapSkippingNewValues(map, newMap, options);
17498         var createNewValue = options.createNewValue;
17499         // Add new values that are not already present
17500         newMap.forEach(function (valueInNewMap, key) {
17501             if (!map.has(key)) {
17502                 // New values
17503                 map.set(key, createNewValue(key, valueInNewMap));
17504             }
17505         });
17506     }
17507     ts.mutateMap = mutateMap;
17508     // Return true if the given type is the constructor type for an abstract class
17509     function isAbstractConstructorType(type) {
17510         return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
17511     }
17512     ts.isAbstractConstructorType = isAbstractConstructorType;
17513     function isAbstractConstructorSymbol(symbol) {
17514         if (symbol.flags & 32 /* Class */) {
17515             var declaration = getClassLikeDeclarationOfSymbol(symbol);
17516             return !!declaration && hasModifier(declaration, 128 /* Abstract */);
17517         }
17518         return false;
17519     }
17520     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
17521     function getClassLikeDeclarationOfSymbol(symbol) {
17522         return ts.find(symbol.declarations, ts.isClassLike);
17523     }
17524     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
17525     function getObjectFlags(type) {
17526         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
17527     }
17528     ts.getObjectFlags = getObjectFlags;
17529     function typeHasCallOrConstructSignatures(type, checker) {
17530         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
17531     }
17532     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
17533     function forSomeAncestorDirectory(directory, callback) {
17534         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
17535     }
17536     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
17537     function isUMDExportSymbol(symbol) {
17538         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
17539     }
17540     ts.isUMDExportSymbol = isUMDExportSymbol;
17541     function showModuleSpecifier(_a) {
17542         var moduleSpecifier = _a.moduleSpecifier;
17543         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
17544     }
17545     ts.showModuleSpecifier = showModuleSpecifier;
17546     function getLastChild(node) {
17547         var lastChild;
17548         ts.forEachChild(node, function (child) {
17549             if (nodeIsPresent(child))
17550                 lastChild = child;
17551         }, function (children) {
17552             // As an optimization, jump straight to the end of the list.
17553             for (var i = children.length - 1; i >= 0; i--) {
17554                 if (nodeIsPresent(children[i])) {
17555                     lastChild = children[i];
17556                     break;
17557                 }
17558             }
17559         });
17560         return lastChild;
17561     }
17562     ts.getLastChild = getLastChild;
17563     function addToSeen(seen, key, value) {
17564         if (value === void 0) { value = true; }
17565         key = String(key);
17566         if (seen.has(key)) {
17567             return false;
17568         }
17569         seen.set(key, value);
17570         return true;
17571     }
17572     ts.addToSeen = addToSeen;
17573     function isObjectTypeDeclaration(node) {
17574         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
17575     }
17576     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
17577     function isTypeNodeKind(kind) {
17578         return (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */)
17579             || kind === 125 /* AnyKeyword */
17580             || kind === 148 /* UnknownKeyword */
17581             || kind === 140 /* NumberKeyword */
17582             || kind === 151 /* BigIntKeyword */
17583             || kind === 141 /* ObjectKeyword */
17584             || kind === 128 /* BooleanKeyword */
17585             || kind === 143 /* StringKeyword */
17586             || kind === 144 /* SymbolKeyword */
17587             || kind === 104 /* ThisKeyword */
17588             || kind === 110 /* VoidKeyword */
17589             || kind === 146 /* UndefinedKeyword */
17590             || kind === 100 /* NullKeyword */
17591             || kind === 137 /* NeverKeyword */
17592             || kind === 216 /* ExpressionWithTypeArguments */
17593             || kind === 295 /* JSDocAllType */
17594             || kind === 296 /* JSDocUnknownType */
17595             || kind === 297 /* JSDocNullableType */
17596             || kind === 298 /* JSDocNonNullableType */
17597             || kind === 299 /* JSDocOptionalType */
17598             || kind === 300 /* JSDocFunctionType */
17599             || kind === 301 /* JSDocVariadicType */;
17600     }
17601     ts.isTypeNodeKind = isTypeNodeKind;
17602     function isAccessExpression(node) {
17603         return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */;
17604     }
17605     ts.isAccessExpression = isAccessExpression;
17606     function getNameOfAccessExpression(node) {
17607         if (node.kind === 194 /* PropertyAccessExpression */) {
17608             return node.name;
17609         }
17610         ts.Debug.assert(node.kind === 195 /* ElementAccessExpression */);
17611         return node.argumentExpression;
17612     }
17613     ts.getNameOfAccessExpression = getNameOfAccessExpression;
17614     function isBundleFileTextLike(section) {
17615         switch (section.kind) {
17616             case "text" /* Text */:
17617             case "internal" /* Internal */:
17618                 return true;
17619             default:
17620                 return false;
17621         }
17622     }
17623     ts.isBundleFileTextLike = isBundleFileTextLike;
17624     function isNamedImportsOrExports(node) {
17625         return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */;
17626     }
17627     ts.isNamedImportsOrExports = isNamedImportsOrExports;
17628     function Symbol(flags, name) {
17629         this.flags = flags;
17630         this.escapedName = name;
17631         this.declarations = undefined;
17632         this.valueDeclaration = undefined;
17633         this.id = undefined;
17634         this.mergeId = undefined;
17635         this.parent = undefined;
17636     }
17637     function Type(checker, flags) {
17638         this.flags = flags;
17639         if (ts.Debug.isDebugging) {
17640             this.checker = checker;
17641         }
17642     }
17643     function Signature(checker, flags) {
17644         this.flags = flags;
17645         if (ts.Debug.isDebugging) {
17646             this.checker = checker;
17647         }
17648     }
17649     function Node(kind, pos, end) {
17650         this.pos = pos;
17651         this.end = end;
17652         this.kind = kind;
17653         this.id = 0;
17654         this.flags = 0 /* None */;
17655         this.modifierFlagsCache = 0 /* None */;
17656         this.transformFlags = 0 /* None */;
17657         this.parent = undefined;
17658         this.original = undefined;
17659     }
17660     function Token(kind, pos, end) {
17661         this.pos = pos;
17662         this.end = end;
17663         this.kind = kind;
17664         this.id = 0;
17665         this.flags = 0 /* None */;
17666         this.transformFlags = 0 /* None */;
17667         this.parent = undefined;
17668     }
17669     function Identifier(kind, pos, end) {
17670         this.pos = pos;
17671         this.end = end;
17672         this.kind = kind;
17673         this.id = 0;
17674         this.flags = 0 /* None */;
17675         this.transformFlags = 0 /* None */;
17676         this.parent = undefined;
17677         this.original = undefined;
17678         this.flowNode = undefined;
17679     }
17680     function SourceMapSource(fileName, text, skipTrivia) {
17681         this.fileName = fileName;
17682         this.text = text;
17683         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
17684     }
17685     // eslint-disable-next-line prefer-const
17686     ts.objectAllocator = {
17687         getNodeConstructor: function () { return Node; },
17688         getTokenConstructor: function () { return Token; },
17689         getIdentifierConstructor: function () { return Identifier; },
17690         getPrivateIdentifierConstructor: function () { return Node; },
17691         getSourceFileConstructor: function () { return Node; },
17692         getSymbolConstructor: function () { return Symbol; },
17693         getTypeConstructor: function () { return Type; },
17694         getSignatureConstructor: function () { return Signature; },
17695         getSourceMapSourceConstructor: function () { return SourceMapSource; },
17696     };
17697     function setObjectAllocator(alloc) {
17698         ts.objectAllocator = alloc;
17699     }
17700     ts.setObjectAllocator = setObjectAllocator;
17701     function formatStringFromArgs(text, args, baseIndex) {
17702         if (baseIndex === void 0) { baseIndex = 0; }
17703         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
17704     }
17705     ts.formatStringFromArgs = formatStringFromArgs;
17706     /* @internal */
17707     function setLocalizedDiagnosticMessages(messages) {
17708         ts.localizedDiagnosticMessages = messages;
17709     }
17710     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
17711     function getLocaleSpecificMessage(message) {
17712         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
17713     }
17714     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
17715     function createFileDiagnostic(file, start, length, message) {
17716         ts.Debug.assertGreaterThanOrEqual(start, 0);
17717         ts.Debug.assertGreaterThanOrEqual(length, 0);
17718         if (file) {
17719             ts.Debug.assertLessThanOrEqual(start, file.text.length);
17720             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
17721         }
17722         var text = getLocaleSpecificMessage(message);
17723         if (arguments.length > 4) {
17724             text = formatStringFromArgs(text, arguments, 4);
17725         }
17726         return {
17727             file: file,
17728             start: start,
17729             length: length,
17730             messageText: text,
17731             category: message.category,
17732             code: message.code,
17733             reportsUnnecessary: message.reportsUnnecessary,
17734         };
17735     }
17736     ts.createFileDiagnostic = createFileDiagnostic;
17737     function formatMessage(_dummy, message) {
17738         var text = getLocaleSpecificMessage(message);
17739         if (arguments.length > 2) {
17740             text = formatStringFromArgs(text, arguments, 2);
17741         }
17742         return text;
17743     }
17744     ts.formatMessage = formatMessage;
17745     function createCompilerDiagnostic(message) {
17746         var text = getLocaleSpecificMessage(message);
17747         if (arguments.length > 1) {
17748             text = formatStringFromArgs(text, arguments, 1);
17749         }
17750         return {
17751             file: undefined,
17752             start: undefined,
17753             length: undefined,
17754             messageText: text,
17755             category: message.category,
17756             code: message.code,
17757             reportsUnnecessary: message.reportsUnnecessary,
17758         };
17759     }
17760     ts.createCompilerDiagnostic = createCompilerDiagnostic;
17761     function createCompilerDiagnosticFromMessageChain(chain) {
17762         return {
17763             file: undefined,
17764             start: undefined,
17765             length: undefined,
17766             code: chain.code,
17767             category: chain.category,
17768             messageText: chain.next ? chain : chain.messageText,
17769         };
17770     }
17771     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
17772     function chainDiagnosticMessages(details, message) {
17773         var text = getLocaleSpecificMessage(message);
17774         if (arguments.length > 2) {
17775             text = formatStringFromArgs(text, arguments, 2);
17776         }
17777         return {
17778             messageText: text,
17779             category: message.category,
17780             code: message.code,
17781             next: details === undefined || Array.isArray(details) ? details : [details]
17782         };
17783     }
17784     ts.chainDiagnosticMessages = chainDiagnosticMessages;
17785     function concatenateDiagnosticMessageChains(headChain, tailChain) {
17786         var lastChain = headChain;
17787         while (lastChain.next) {
17788             lastChain = lastChain.next[0];
17789         }
17790         lastChain.next = [tailChain];
17791     }
17792     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
17793     function getDiagnosticFilePath(diagnostic) {
17794         return diagnostic.file ? diagnostic.file.path : undefined;
17795     }
17796     function compareDiagnostics(d1, d2) {
17797         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
17798             compareRelatedInformation(d1, d2) ||
17799             0 /* EqualTo */;
17800     }
17801     ts.compareDiagnostics = compareDiagnostics;
17802     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
17803         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
17804             ts.compareValues(d1.start, d2.start) ||
17805             ts.compareValues(d1.length, d2.length) ||
17806             ts.compareValues(d1.code, d2.code) ||
17807             compareMessageText(d1.messageText, d2.messageText) ||
17808             0 /* EqualTo */;
17809     }
17810     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
17811     function compareRelatedInformation(d1, d2) {
17812         if (!d1.relatedInformation && !d2.relatedInformation) {
17813             return 0 /* EqualTo */;
17814         }
17815         if (d1.relatedInformation && d2.relatedInformation) {
17816             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
17817                 var d2i = d2.relatedInformation[index];
17818                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
17819             }) || 0 /* EqualTo */;
17820         }
17821         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
17822     }
17823     function compareMessageText(t1, t2) {
17824         if (typeof t1 === "string" && typeof t2 === "string") {
17825             return ts.compareStringsCaseSensitive(t1, t2);
17826         }
17827         else if (typeof t1 === "string") {
17828             return -1 /* LessThan */;
17829         }
17830         else if (typeof t2 === "string") {
17831             return 1 /* GreaterThan */;
17832         }
17833         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
17834         if (res) {
17835             return res;
17836         }
17837         if (!t1.next && !t2.next) {
17838             return 0 /* EqualTo */;
17839         }
17840         if (!t1.next) {
17841             return -1 /* LessThan */;
17842         }
17843         if (!t2.next) {
17844             return 1 /* GreaterThan */;
17845         }
17846         var len = Math.min(t1.next.length, t2.next.length);
17847         for (var i = 0; i < len; i++) {
17848             res = compareMessageText(t1.next[i], t2.next[i]);
17849             if (res) {
17850                 return res;
17851             }
17852         }
17853         if (t1.next.length < t2.next.length) {
17854             return -1 /* LessThan */;
17855         }
17856         else if (t1.next.length > t2.next.length) {
17857             return 1 /* GreaterThan */;
17858         }
17859         return 0 /* EqualTo */;
17860     }
17861     function getEmitScriptTarget(compilerOptions) {
17862         return compilerOptions.target || 0 /* ES3 */;
17863     }
17864     ts.getEmitScriptTarget = getEmitScriptTarget;
17865     function getEmitModuleKind(compilerOptions) {
17866         return typeof compilerOptions.module === "number" ?
17867             compilerOptions.module :
17868             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
17869     }
17870     ts.getEmitModuleKind = getEmitModuleKind;
17871     function getEmitModuleResolutionKind(compilerOptions) {
17872         var moduleResolution = compilerOptions.moduleResolution;
17873         if (moduleResolution === undefined) {
17874             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
17875         }
17876         return moduleResolution;
17877     }
17878     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
17879     function hasJsonModuleEmitEnabled(options) {
17880         switch (getEmitModuleKind(options)) {
17881             case ts.ModuleKind.CommonJS:
17882             case ts.ModuleKind.AMD:
17883             case ts.ModuleKind.ES2015:
17884             case ts.ModuleKind.ES2020:
17885             case ts.ModuleKind.ESNext:
17886                 return true;
17887             default:
17888                 return false;
17889         }
17890     }
17891     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
17892     function unreachableCodeIsError(options) {
17893         return options.allowUnreachableCode === false;
17894     }
17895     ts.unreachableCodeIsError = unreachableCodeIsError;
17896     function unusedLabelIsError(options) {
17897         return options.allowUnusedLabels === false;
17898     }
17899     ts.unusedLabelIsError = unusedLabelIsError;
17900     function getAreDeclarationMapsEnabled(options) {
17901         return !!(getEmitDeclarations(options) && options.declarationMap);
17902     }
17903     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
17904     function getAllowSyntheticDefaultImports(compilerOptions) {
17905         var moduleKind = getEmitModuleKind(compilerOptions);
17906         return compilerOptions.allowSyntheticDefaultImports !== undefined
17907             ? compilerOptions.allowSyntheticDefaultImports
17908             : compilerOptions.esModuleInterop ||
17909                 moduleKind === ts.ModuleKind.System;
17910     }
17911     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
17912     function getEmitDeclarations(compilerOptions) {
17913         return !!(compilerOptions.declaration || compilerOptions.composite);
17914     }
17915     ts.getEmitDeclarations = getEmitDeclarations;
17916     function isIncrementalCompilation(options) {
17917         return !!(options.incremental || options.composite);
17918     }
17919     ts.isIncrementalCompilation = isIncrementalCompilation;
17920     function getStrictOptionValue(compilerOptions, flag) {
17921         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
17922     }
17923     ts.getStrictOptionValue = getStrictOptionValue;
17924     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
17925         return oldOptions !== newOptions &&
17926             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17927     }
17928     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
17929     function compilerOptionsAffectEmit(newOptions, oldOptions) {
17930         return oldOptions !== newOptions &&
17931             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17932     }
17933     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
17934     function getCompilerOptionValue(options, option) {
17935         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
17936     }
17937     ts.getCompilerOptionValue = getCompilerOptionValue;
17938     function hasZeroOrOneAsteriskCharacter(str) {
17939         var seenAsterisk = false;
17940         for (var i = 0; i < str.length; i++) {
17941             if (str.charCodeAt(i) === 42 /* asterisk */) {
17942                 if (!seenAsterisk) {
17943                     seenAsterisk = true;
17944                 }
17945                 else {
17946                     // have already seen asterisk
17947                     return false;
17948                 }
17949             }
17950         }
17951         return true;
17952     }
17953     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
17954     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
17955         var result = ts.createMap();
17956         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
17957             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
17958                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
17959             })));
17960         }));
17961         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
17962             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
17963             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
17964             result.set(commonOriginal, commonResolved);
17965         }
17966         return result;
17967     }
17968     ts.discoverProbableSymlinks = discoverProbableSymlinks;
17969     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
17970         var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
17971         var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
17972         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
17973             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
17974             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
17975             aParts.pop();
17976             bParts.pop();
17977         }
17978         return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
17979     }
17980     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
17981     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
17982     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
17983         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
17984     }
17985     function stripLeadingDirectorySeparator(s) {
17986         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
17987     }
17988     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
17989         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
17990         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
17991     }
17992     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
17993     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
17994     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
17995     // proof.
17996     var reservedCharacterPattern = /[^\w\s\/]/g;
17997     function regExpEscape(text) {
17998         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
17999     }
18000     ts.regExpEscape = regExpEscape;
18001     function escapeRegExpCharacter(match) {
18002         return "\\" + match;
18003     }
18004     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
18005     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
18006     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
18007     var filesMatcher = {
18008         /**
18009          * Matches any single directory segment unless it is the last segment and a .min.js file
18010          * Breakdown:
18011          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
18012          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
18013          */
18014         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18015         /**
18016          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18017          * files or directories, does not match subdirectories that start with a . character
18018          */
18019         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18020         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18021     };
18022     var directoriesMatcher = {
18023         singleAsteriskRegexFragment: "[^/]*",
18024         /**
18025          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18026          * files or directories, does not match subdirectories that start with a . character
18027          */
18028         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18029         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18030     };
18031     var excludeMatcher = {
18032         singleAsteriskRegexFragment: "[^/]*",
18033         doubleAsteriskRegexFragment: "(/.+?)?",
18034         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18035     };
18036     var wildcardMatchers = {
18037         files: filesMatcher,
18038         directories: directoriesMatcher,
18039         exclude: excludeMatcher
18040     };
18041     function getRegularExpressionForWildcard(specs, basePath, usage) {
18042         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18043         if (!patterns || !patterns.length) {
18044             return undefined;
18045         }
18046         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18047         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18048         var terminator = usage === "exclude" ? "($|/)" : "$";
18049         return "^(" + pattern + ")" + terminator;
18050     }
18051     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18052     function getRegularExpressionsForWildcards(specs, basePath, usage) {
18053         if (specs === undefined || specs.length === 0) {
18054             return undefined;
18055         }
18056         return ts.flatMap(specs, function (spec) {
18057             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18058         });
18059     }
18060     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18061     /**
18062      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18063      * and does not contain any glob characters itself.
18064      */
18065     function isImplicitGlob(lastPathComponent) {
18066         return !/[.*?]/.test(lastPathComponent);
18067     }
18068     ts.isImplicitGlob = isImplicitGlob;
18069     function getSubPatternFromSpec(spec, basePath, usage, _a) {
18070         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18071         var subpattern = "";
18072         var hasWrittenComponent = false;
18073         var components = ts.getNormalizedPathComponents(spec, basePath);
18074         var lastComponent = ts.last(components);
18075         if (usage !== "exclude" && lastComponent === "**") {
18076             return undefined;
18077         }
18078         // getNormalizedPathComponents includes the separator for the root component.
18079         // We need to remove to create our regex correctly.
18080         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18081         if (isImplicitGlob(lastComponent)) {
18082             components.push("**", "*");
18083         }
18084         var optionalCount = 0;
18085         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18086             var component = components_1[_i];
18087             if (component === "**") {
18088                 subpattern += doubleAsteriskRegexFragment;
18089             }
18090             else {
18091                 if (usage === "directories") {
18092                     subpattern += "(";
18093                     optionalCount++;
18094                 }
18095                 if (hasWrittenComponent) {
18096                     subpattern += ts.directorySeparator;
18097                 }
18098                 if (usage !== "exclude") {
18099                     var componentPattern = "";
18100                     // The * and ? wildcards should not match directories or files that start with . if they
18101                     // appear first in a component. Dotted directories and files can be included explicitly
18102                     // like so: **/.*/.*
18103                     if (component.charCodeAt(0) === 42 /* asterisk */) {
18104                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18105                         component = component.substr(1);
18106                     }
18107                     else if (component.charCodeAt(0) === 63 /* question */) {
18108                         componentPattern += "[^./]";
18109                         component = component.substr(1);
18110                     }
18111                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18112                     // Patterns should not include subfolders like node_modules unless they are
18113                     // explicitly included as part of the path.
18114                     //
18115                     // As an optimization, if the component pattern is the same as the component,
18116                     // then there definitely were no wildcard characters and we do not need to
18117                     // add the exclusion pattern.
18118                     if (componentPattern !== component) {
18119                         subpattern += implicitExcludePathRegexPattern;
18120                     }
18121                     subpattern += componentPattern;
18122                 }
18123                 else {
18124                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18125                 }
18126             }
18127             hasWrittenComponent = true;
18128         }
18129         while (optionalCount > 0) {
18130             subpattern += ")?";
18131             optionalCount--;
18132         }
18133         return subpattern;
18134     }
18135     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18136         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18137     }
18138     /** @param path directory of the tsconfig.json */
18139     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18140         path = ts.normalizePath(path);
18141         currentDirectory = ts.normalizePath(currentDirectory);
18142         var absolutePath = ts.combinePaths(currentDirectory, path);
18143         return {
18144             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18145             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18146             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18147             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18148             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18149         };
18150     }
18151     ts.getFileMatcherPatterns = getFileMatcherPatterns;
18152     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18153         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18154     }
18155     ts.getRegexFromPattern = getRegexFromPattern;
18156     /** @param path directory of the tsconfig.json */
18157     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18158         path = ts.normalizePath(path);
18159         currentDirectory = ts.normalizePath(currentDirectory);
18160         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18161         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18162         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18163         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18164         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18165         // If there are no "includes", then just put everything in results[0].
18166         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18167         var visited = ts.createMap();
18168         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18169         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18170             var basePath = _a[_i];
18171             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18172         }
18173         return ts.flatten(results);
18174         function visitDirectory(path, absolutePath, depth) {
18175             var canonicalPath = toCanonical(realpath(absolutePath));
18176             if (visited.has(canonicalPath))
18177                 return;
18178             visited.set(canonicalPath, true);
18179             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18180             var _loop_1 = function (current) {
18181                 var name = ts.combinePaths(path, current);
18182                 var absoluteName = ts.combinePaths(absolutePath, current);
18183                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18184                     return "continue";
18185                 if (excludeRegex && excludeRegex.test(absoluteName))
18186                     return "continue";
18187                 if (!includeFileRegexes) {
18188                     results[0].push(name);
18189                 }
18190                 else {
18191                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
18192                     if (includeIndex !== -1) {
18193                         results[includeIndex].push(name);
18194                     }
18195                 }
18196             };
18197             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
18198                 var current = _b[_i];
18199                 _loop_1(current);
18200             }
18201             if (depth !== undefined) {
18202                 depth--;
18203                 if (depth === 0) {
18204                     return;
18205                 }
18206             }
18207             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
18208                 var current = _d[_c];
18209                 var name = ts.combinePaths(path, current);
18210                 var absoluteName = ts.combinePaths(absolutePath, current);
18211                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
18212                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
18213                     visitDirectory(name, absoluteName, depth);
18214                 }
18215             }
18216         }
18217     }
18218     ts.matchFiles = matchFiles;
18219     /**
18220      * Computes the unique non-wildcard base paths amongst the provided include patterns.
18221      */
18222     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
18223         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
18224         var basePaths = [path];
18225         if (includes) {
18226             // Storage for literal base paths amongst the include patterns.
18227             var includeBasePaths = [];
18228             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
18229                 var include = includes_1[_i];
18230                 // We also need to check the relative paths by converting them to absolute and normalizing
18231                 // in case they escape the base path (e.g "..\somedirectory")
18232                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
18233                 // Append the literal and canonical candidate base paths.
18234                 includeBasePaths.push(getIncludeBasePath(absolute));
18235             }
18236             // Sort the offsets array using either the literal or canonical path representations.
18237             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
18238             var _loop_2 = function (includeBasePath) {
18239                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
18240                     basePaths.push(includeBasePath);
18241                 }
18242             };
18243             // Iterate over each include base path and include unique base paths that are not a
18244             // subpath of an existing base path
18245             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
18246                 var includeBasePath = includeBasePaths_1[_a];
18247                 _loop_2(includeBasePath);
18248             }
18249         }
18250         return basePaths;
18251     }
18252     function getIncludeBasePath(absolute) {
18253         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
18254         if (wildcardOffset < 0) {
18255             // No "*" or "?" in the path
18256             return !ts.hasExtension(absolute)
18257                 ? absolute
18258                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
18259         }
18260         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
18261     }
18262     function ensureScriptKind(fileName, scriptKind) {
18263         // Using scriptKind as a condition handles both:
18264         // - 'scriptKind' is unspecified and thus it is `undefined`
18265         // - 'scriptKind' is set and it is `Unknown` (0)
18266         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
18267         // to get the ScriptKind from the file name. If it cannot be resolved
18268         // from the file name then the default 'TS' script kind is returned.
18269         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
18270     }
18271     ts.ensureScriptKind = ensureScriptKind;
18272     function getScriptKindFromFileName(fileName) {
18273         var ext = fileName.substr(fileName.lastIndexOf("."));
18274         switch (ext.toLowerCase()) {
18275             case ".js" /* Js */:
18276                 return 1 /* JS */;
18277             case ".jsx" /* Jsx */:
18278                 return 2 /* JSX */;
18279             case ".ts" /* Ts */:
18280                 return 3 /* TS */;
18281             case ".tsx" /* Tsx */:
18282                 return 4 /* TSX */;
18283             case ".json" /* Json */:
18284                 return 6 /* JSON */;
18285             default:
18286                 return 0 /* Unknown */;
18287         }
18288     }
18289     ts.getScriptKindFromFileName = getScriptKindFromFileName;
18290     /**
18291      *  List of supported extensions in order of file resolution precedence.
18292      */
18293     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
18294     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
18295     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
18296     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
18297     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
18298     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
18299     var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
18300     var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
18301     function getSupportedExtensions(options, extraFileExtensions) {
18302         var needJsExtensions = options && options.allowJs;
18303         if (!extraFileExtensions || extraFileExtensions.length === 0) {
18304             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
18305         }
18306         var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
18307         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
18308     }
18309     ts.getSupportedExtensions = getSupportedExtensions;
18310     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
18311         if (!options || !options.resolveJsonModule) {
18312             return supportedExtensions;
18313         }
18314         if (supportedExtensions === allSupportedExtensions) {
18315             return allSupportedExtensionsWithJson;
18316         }
18317         if (supportedExtensions === ts.supportedTSExtensions) {
18318             return ts.supportedTSExtensionsWithJson;
18319         }
18320         return __spreadArrays(supportedExtensions, [".json" /* Json */]);
18321     }
18322     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
18323     function isJSLike(scriptKind) {
18324         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
18325     }
18326     function hasJSFileExtension(fileName) {
18327         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18328     }
18329     ts.hasJSFileExtension = hasJSFileExtension;
18330     function hasTSFileExtension(fileName) {
18331         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18332     }
18333     ts.hasTSFileExtension = hasTSFileExtension;
18334     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
18335         if (!fileName) {
18336             return false;
18337         }
18338         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
18339         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
18340             var extension = _a[_i];
18341             if (ts.fileExtensionIs(fileName, extension)) {
18342                 return true;
18343             }
18344         }
18345         return false;
18346     }
18347     ts.isSupportedSourceFileName = isSupportedSourceFileName;
18348     /**
18349      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
18350      * aligned to the offset of the highest priority extension in the
18351      * allSupportedExtensions array.
18352      */
18353     var ExtensionPriority;
18354     (function (ExtensionPriority) {
18355         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
18356         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
18357         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
18358         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
18359     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
18360     function getExtensionPriority(path, supportedExtensions) {
18361         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
18362             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
18363                 return adjustExtensionPriority(i, supportedExtensions);
18364             }
18365         }
18366         // If its not in the list of supported extensions, this is likely a
18367         // TypeScript file with a non-ts extension
18368         return 0 /* Highest */;
18369     }
18370     ts.getExtensionPriority = getExtensionPriority;
18371     /**
18372      * Adjusts an extension priority to be the highest priority within the same range.
18373      */
18374     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
18375         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18376             return 0 /* TypeScriptFiles */;
18377         }
18378         else if (extensionPriority < supportedExtensions.length) {
18379             return 2 /* DeclarationAndJavaScriptFiles */;
18380         }
18381         else {
18382             return supportedExtensions.length;
18383         }
18384     }
18385     ts.adjustExtensionPriority = adjustExtensionPriority;
18386     /**
18387      * Gets the next lowest extension priority for a given priority.
18388      */
18389     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
18390         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18391             return 2 /* DeclarationAndJavaScriptFiles */;
18392         }
18393         else {
18394             return supportedExtensions.length;
18395         }
18396     }
18397     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
18398     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
18399     function removeFileExtension(path) {
18400         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
18401             var ext = extensionsToRemove_1[_i];
18402             var extensionless = tryRemoveExtension(path, ext);
18403             if (extensionless !== undefined) {
18404                 return extensionless;
18405             }
18406         }
18407         return path;
18408     }
18409     ts.removeFileExtension = removeFileExtension;
18410     function tryRemoveExtension(path, extension) {
18411         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
18412     }
18413     ts.tryRemoveExtension = tryRemoveExtension;
18414     function removeExtension(path, extension) {
18415         return path.substring(0, path.length - extension.length);
18416     }
18417     ts.removeExtension = removeExtension;
18418     function changeExtension(path, newExtension) {
18419         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
18420     }
18421     ts.changeExtension = changeExtension;
18422     function tryParsePattern(pattern) {
18423         // This should be verified outside of here and a proper error thrown.
18424         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
18425         var indexOfStar = pattern.indexOf("*");
18426         return indexOfStar === -1 ? undefined : {
18427             prefix: pattern.substr(0, indexOfStar),
18428             suffix: pattern.substr(indexOfStar + 1)
18429         };
18430     }
18431     ts.tryParsePattern = tryParsePattern;
18432     function positionIsSynthesized(pos) {
18433         // This is a fast way of testing the following conditions:
18434         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
18435         return !(pos >= 0);
18436     }
18437     ts.positionIsSynthesized = positionIsSynthesized;
18438     /** True if an extension is one of the supported TypeScript extensions. */
18439     function extensionIsTS(ext) {
18440         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
18441     }
18442     ts.extensionIsTS = extensionIsTS;
18443     function resolutionExtensionIsTSOrJson(ext) {
18444         return extensionIsTS(ext) || ext === ".json" /* Json */;
18445     }
18446     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
18447     /**
18448      * Gets the extension from a path.
18449      * Path must have a valid extension.
18450      */
18451     function extensionFromPath(path) {
18452         var ext = tryGetExtensionFromPath(path);
18453         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
18454     }
18455     ts.extensionFromPath = extensionFromPath;
18456     function isAnySupportedFileExtension(path) {
18457         return tryGetExtensionFromPath(path) !== undefined;
18458     }
18459     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
18460     function tryGetExtensionFromPath(path) {
18461         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
18462     }
18463     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
18464     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
18465         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
18466     }
18467     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
18468     ts.emptyFileSystemEntries = {
18469         files: ts.emptyArray,
18470         directories: ts.emptyArray
18471     };
18472     /**
18473      * patternStrings contains both pattern strings (containing "*") and regular strings.
18474      * Return an exact match if possible, or a pattern match, or undefined.
18475      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
18476      */
18477     function matchPatternOrExact(patternStrings, candidate) {
18478         var patterns = [];
18479         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
18480             var patternString = patternStrings_1[_i];
18481             if (!hasZeroOrOneAsteriskCharacter(patternString))
18482                 continue;
18483             var pattern = tryParsePattern(patternString);
18484             if (pattern) {
18485                 patterns.push(pattern);
18486             }
18487             else if (patternString === candidate) {
18488                 // pattern was matched as is - no need to search further
18489                 return patternString;
18490             }
18491         }
18492         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
18493     }
18494     ts.matchPatternOrExact = matchPatternOrExact;
18495     function sliceAfter(arr, value) {
18496         var index = arr.indexOf(value);
18497         ts.Debug.assert(index !== -1);
18498         return arr.slice(index);
18499     }
18500     ts.sliceAfter = sliceAfter;
18501     function addRelatedInfo(diagnostic) {
18502         var _a;
18503         var relatedInformation = [];
18504         for (var _i = 1; _i < arguments.length; _i++) {
18505             relatedInformation[_i - 1] = arguments[_i];
18506         }
18507         if (!relatedInformation.length) {
18508             return diagnostic;
18509         }
18510         if (!diagnostic.relatedInformation) {
18511             diagnostic.relatedInformation = [];
18512         }
18513         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
18514         return diagnostic;
18515     }
18516     ts.addRelatedInfo = addRelatedInfo;
18517     function minAndMax(arr, getValue) {
18518         ts.Debug.assert(arr.length !== 0);
18519         var min = getValue(arr[0]);
18520         var max = min;
18521         for (var i = 1; i < arr.length; i++) {
18522             var value = getValue(arr[i]);
18523             if (value < min) {
18524                 min = value;
18525             }
18526             else if (value > max) {
18527                 max = value;
18528             }
18529         }
18530         return { min: min, max: max };
18531     }
18532     ts.minAndMax = minAndMax;
18533     var NodeSet = /** @class */ (function () {
18534         function NodeSet() {
18535             this.map = ts.createMap();
18536         }
18537         NodeSet.prototype.add = function (node) {
18538             this.map.set(String(ts.getNodeId(node)), node);
18539         };
18540         NodeSet.prototype.tryAdd = function (node) {
18541             if (this.has(node))
18542                 return false;
18543             this.add(node);
18544             return true;
18545         };
18546         NodeSet.prototype.has = function (node) {
18547             return this.map.has(String(ts.getNodeId(node)));
18548         };
18549         NodeSet.prototype.forEach = function (cb) {
18550             this.map.forEach(cb);
18551         };
18552         NodeSet.prototype.some = function (pred) {
18553             return forEachEntry(this.map, pred) || false;
18554         };
18555         return NodeSet;
18556     }());
18557     ts.NodeSet = NodeSet;
18558     var NodeMap = /** @class */ (function () {
18559         function NodeMap() {
18560             this.map = ts.createMap();
18561         }
18562         NodeMap.prototype.get = function (node) {
18563             var res = this.map.get(String(ts.getNodeId(node)));
18564             return res && res.value;
18565         };
18566         NodeMap.prototype.getOrUpdate = function (node, setValue) {
18567             var res = this.get(node);
18568             if (res)
18569                 return res;
18570             var value = setValue();
18571             this.set(node, value);
18572             return value;
18573         };
18574         NodeMap.prototype.set = function (node, value) {
18575             this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
18576         };
18577         NodeMap.prototype.has = function (node) {
18578             return this.map.has(String(ts.getNodeId(node)));
18579         };
18580         NodeMap.prototype.forEach = function (cb) {
18581             this.map.forEach(function (_a) {
18582                 var node = _a.node, value = _a.value;
18583                 return cb(value, node);
18584             });
18585         };
18586         return NodeMap;
18587     }());
18588     ts.NodeMap = NodeMap;
18589     function rangeOfNode(node) {
18590         return { pos: getTokenPosOfNode(node), end: node.end };
18591     }
18592     ts.rangeOfNode = rangeOfNode;
18593     function rangeOfTypeParameters(typeParameters) {
18594         // Include the `<>`
18595         return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
18596     }
18597     ts.rangeOfTypeParameters = rangeOfTypeParameters;
18598     function skipTypeChecking(sourceFile, options, host) {
18599         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
18600         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
18601         // '/// <reference no-default-lib="true"/>' directive.
18602         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
18603             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
18604             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
18605     }
18606     ts.skipTypeChecking = skipTypeChecking;
18607     function isJsonEqual(a, b) {
18608         // eslint-disable-next-line no-null/no-null
18609         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
18610     }
18611     ts.isJsonEqual = isJsonEqual;
18612     function getOrUpdate(map, key, getDefault) {
18613         var got = map.get(key);
18614         if (got === undefined) {
18615             var value = getDefault();
18616             map.set(key, value);
18617             return value;
18618         }
18619         else {
18620             return got;
18621         }
18622     }
18623     ts.getOrUpdate = getOrUpdate;
18624     /**
18625      * Converts a bigint literal string, e.g. `0x1234n`,
18626      * to its decimal string representation, e.g. `4660`.
18627      */
18628     function parsePseudoBigInt(stringValue) {
18629         var log2Base;
18630         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
18631             case 98 /* b */:
18632             case 66 /* B */: // 0b or 0B
18633                 log2Base = 1;
18634                 break;
18635             case 111 /* o */:
18636             case 79 /* O */: // 0o or 0O
18637                 log2Base = 3;
18638                 break;
18639             case 120 /* x */:
18640             case 88 /* X */: // 0x or 0X
18641                 log2Base = 4;
18642                 break;
18643             default: // already in decimal; omit trailing "n"
18644                 var nIndex = stringValue.length - 1;
18645                 // Skip leading 0s
18646                 var nonZeroStart = 0;
18647                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
18648                     nonZeroStart++;
18649                 }
18650                 return stringValue.slice(nonZeroStart, nIndex) || "0";
18651         }
18652         // Omit leading "0b", "0o", or "0x", and trailing "n"
18653         var startIndex = 2, endIndex = stringValue.length - 1;
18654         var bitsNeeded = (endIndex - startIndex) * log2Base;
18655         // Stores the value specified by the string as a LE array of 16-bit integers
18656         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
18657         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
18658         // Add the digits, one at a time
18659         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
18660             var segment = bitOffset >>> 4;
18661             var digitChar = stringValue.charCodeAt(i);
18662             // Find character range: 0-9 < A-F < a-f
18663             var digit = digitChar <= 57 /* _9 */
18664                 ? digitChar - 48 /* _0 */
18665                 : 10 + digitChar -
18666                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
18667             var shiftedDigit = digit << (bitOffset & 15);
18668             segments[segment] |= shiftedDigit;
18669             var residual = shiftedDigit >>> 16;
18670             if (residual)
18671                 segments[segment + 1] |= residual; // overflows segment
18672         }
18673         // Repeatedly divide segments by 10 and add remainder to base10Value
18674         var base10Value = "";
18675         var firstNonzeroSegment = segments.length - 1;
18676         var segmentsRemaining = true;
18677         while (segmentsRemaining) {
18678             var mod10 = 0;
18679             segmentsRemaining = false;
18680             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
18681                 var newSegment = mod10 << 16 | segments[segment];
18682                 var segmentValue = (newSegment / 10) | 0;
18683                 segments[segment] = segmentValue;
18684                 mod10 = newSegment - segmentValue * 10;
18685                 if (segmentValue && !segmentsRemaining) {
18686                     firstNonzeroSegment = segment;
18687                     segmentsRemaining = true;
18688                 }
18689             }
18690             base10Value = mod10 + base10Value;
18691         }
18692         return base10Value;
18693     }
18694     ts.parsePseudoBigInt = parsePseudoBigInt;
18695     function pseudoBigIntToString(_a) {
18696         var negative = _a.negative, base10Value = _a.base10Value;
18697         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
18698     }
18699     ts.pseudoBigIntToString = pseudoBigIntToString;
18700     function isValidTypeOnlyAliasUseSite(useSite) {
18701         return !!(useSite.flags & 8388608 /* Ambient */)
18702             || isPartOfTypeQuery(useSite)
18703             || isIdentifierInNonEmittingHeritageClause(useSite)
18704             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
18705             || !isExpressionNode(useSite);
18706     }
18707     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
18708     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
18709         return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */;
18710     }
18711     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
18712     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
18713         while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) {
18714             node = node.parent;
18715         }
18716         if (node.kind !== 154 /* ComputedPropertyName */) {
18717             return false;
18718         }
18719         if (hasModifier(node.parent, 128 /* Abstract */)) {
18720             return true;
18721         }
18722         var containerKind = node.parent.parent.kind;
18723         return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */;
18724     }
18725     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
18726     function isIdentifierInNonEmittingHeritageClause(node) {
18727         if (node.kind !== 75 /* Identifier */)
18728             return false;
18729         var heritageClause = findAncestor(node.parent, function (parent) {
18730             switch (parent.kind) {
18731                 case 279 /* HeritageClause */:
18732                     return true;
18733                 case 194 /* PropertyAccessExpression */:
18734                 case 216 /* ExpressionWithTypeArguments */:
18735                     return false;
18736                 default:
18737                     return "quit";
18738             }
18739         });
18740         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */;
18741     }
18742     function isIdentifierTypeReference(node) {
18743         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
18744     }
18745     ts.isIdentifierTypeReference = isIdentifierTypeReference;
18746     function arrayIsHomogeneous(array, comparer) {
18747         if (comparer === void 0) { comparer = ts.equateValues; }
18748         if (array.length < 2)
18749             return true;
18750         var first = array[0];
18751         for (var i = 1, length_1 = array.length; i < length_1; i++) {
18752             var target = array[i];
18753             if (!comparer(first, target))
18754                 return false;
18755         }
18756         return true;
18757     }
18758     ts.arrayIsHomogeneous = arrayIsHomogeneous;
18759 })(ts || (ts = {}));
18760 var ts;
18761 (function (ts) {
18762     var SignatureFlags;
18763     (function (SignatureFlags) {
18764         SignatureFlags[SignatureFlags["None"] = 0] = "None";
18765         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
18766         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
18767         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
18768         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
18769         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
18770     })(SignatureFlags || (SignatureFlags = {}));
18771     var NodeConstructor;
18772     var TokenConstructor;
18773     var IdentifierConstructor;
18774     var PrivateIdentifierConstructor;
18775     var SourceFileConstructor;
18776     function createNode(kind, pos, end) {
18777         if (kind === 290 /* SourceFile */) {
18778             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
18779         }
18780         else if (kind === 75 /* Identifier */) {
18781             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
18782         }
18783         else if (kind === 76 /* PrivateIdentifier */) {
18784             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, pos, end);
18785         }
18786         else if (!ts.isNodeKind(kind)) {
18787             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
18788         }
18789         else {
18790             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
18791         }
18792     }
18793     ts.createNode = createNode;
18794     function visitNode(cbNode, node) {
18795         return node && cbNode(node);
18796     }
18797     function visitNodes(cbNode, cbNodes, nodes) {
18798         if (nodes) {
18799             if (cbNodes) {
18800                 return cbNodes(nodes);
18801             }
18802             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
18803                 var node = nodes_1[_i];
18804                 var result = cbNode(node);
18805                 if (result) {
18806                     return result;
18807                 }
18808             }
18809         }
18810     }
18811     /*@internal*/
18812     function isJSDocLikeText(text, start) {
18813         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
18814             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
18815             text.charCodeAt(start + 3) !== 47 /* slash */;
18816     }
18817     ts.isJSDocLikeText = isJSDocLikeText;
18818     /**
18819      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
18820      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
18821      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
18822      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
18823      *
18824      * @param node a given node to visit its children
18825      * @param cbNode a callback to be invoked for all child nodes
18826      * @param cbNodes a callback to be invoked for embedded array
18827      *
18828      * @remarks `forEachChild` must visit the children of a node in the order
18829      * that they appear in the source code. The language service depends on this property to locate nodes by position.
18830      */
18831     function forEachChild(node, cbNode, cbNodes) {
18832         if (!node || node.kind <= 152 /* LastToken */) {
18833             return;
18834         }
18835         switch (node.kind) {
18836             case 153 /* QualifiedName */:
18837                 return visitNode(cbNode, node.left) ||
18838                     visitNode(cbNode, node.right);
18839             case 155 /* TypeParameter */:
18840                 return visitNode(cbNode, node.name) ||
18841                     visitNode(cbNode, node.constraint) ||
18842                     visitNode(cbNode, node.default) ||
18843                     visitNode(cbNode, node.expression);
18844             case 282 /* ShorthandPropertyAssignment */:
18845                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18846                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18847                     visitNode(cbNode, node.name) ||
18848                     visitNode(cbNode, node.questionToken) ||
18849                     visitNode(cbNode, node.exclamationToken) ||
18850                     visitNode(cbNode, node.equalsToken) ||
18851                     visitNode(cbNode, node.objectAssignmentInitializer);
18852             case 283 /* SpreadAssignment */:
18853                 return visitNode(cbNode, node.expression);
18854             case 156 /* Parameter */:
18855                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18856                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18857                     visitNode(cbNode, node.dotDotDotToken) ||
18858                     visitNode(cbNode, node.name) ||
18859                     visitNode(cbNode, node.questionToken) ||
18860                     visitNode(cbNode, node.type) ||
18861                     visitNode(cbNode, node.initializer);
18862             case 159 /* PropertyDeclaration */:
18863                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18864                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18865                     visitNode(cbNode, node.name) ||
18866                     visitNode(cbNode, node.questionToken) ||
18867                     visitNode(cbNode, node.exclamationToken) ||
18868                     visitNode(cbNode, node.type) ||
18869                     visitNode(cbNode, node.initializer);
18870             case 158 /* PropertySignature */:
18871                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18872                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18873                     visitNode(cbNode, node.name) ||
18874                     visitNode(cbNode, node.questionToken) ||
18875                     visitNode(cbNode, node.type) ||
18876                     visitNode(cbNode, node.initializer);
18877             case 281 /* PropertyAssignment */:
18878                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18879                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18880                     visitNode(cbNode, node.name) ||
18881                     visitNode(cbNode, node.questionToken) ||
18882                     visitNode(cbNode, node.initializer);
18883             case 242 /* VariableDeclaration */:
18884                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18885                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18886                     visitNode(cbNode, node.name) ||
18887                     visitNode(cbNode, node.exclamationToken) ||
18888                     visitNode(cbNode, node.type) ||
18889                     visitNode(cbNode, node.initializer);
18890             case 191 /* BindingElement */:
18891                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18892                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18893                     visitNode(cbNode, node.dotDotDotToken) ||
18894                     visitNode(cbNode, node.propertyName) ||
18895                     visitNode(cbNode, node.name) ||
18896                     visitNode(cbNode, node.initializer);
18897             case 170 /* FunctionType */:
18898             case 171 /* ConstructorType */:
18899             case 165 /* CallSignature */:
18900             case 166 /* ConstructSignature */:
18901             case 167 /* IndexSignature */:
18902                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18903                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18904                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18905                     visitNodes(cbNode, cbNodes, node.parameters) ||
18906                     visitNode(cbNode, node.type);
18907             case 161 /* MethodDeclaration */:
18908             case 160 /* MethodSignature */:
18909             case 162 /* Constructor */:
18910             case 163 /* GetAccessor */:
18911             case 164 /* SetAccessor */:
18912             case 201 /* FunctionExpression */:
18913             case 244 /* FunctionDeclaration */:
18914             case 202 /* ArrowFunction */:
18915                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18916                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18917                     visitNode(cbNode, node.asteriskToken) ||
18918                     visitNode(cbNode, node.name) ||
18919                     visitNode(cbNode, node.questionToken) ||
18920                     visitNode(cbNode, node.exclamationToken) ||
18921                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18922                     visitNodes(cbNode, cbNodes, node.parameters) ||
18923                     visitNode(cbNode, node.type) ||
18924                     visitNode(cbNode, node.equalsGreaterThanToken) ||
18925                     visitNode(cbNode, node.body);
18926             case 169 /* TypeReference */:
18927                 return visitNode(cbNode, node.typeName) ||
18928                     visitNodes(cbNode, cbNodes, node.typeArguments);
18929             case 168 /* TypePredicate */:
18930                 return visitNode(cbNode, node.assertsModifier) ||
18931                     visitNode(cbNode, node.parameterName) ||
18932                     visitNode(cbNode, node.type);
18933             case 172 /* TypeQuery */:
18934                 return visitNode(cbNode, node.exprName);
18935             case 173 /* TypeLiteral */:
18936                 return visitNodes(cbNode, cbNodes, node.members);
18937             case 174 /* ArrayType */:
18938                 return visitNode(cbNode, node.elementType);
18939             case 175 /* TupleType */:
18940                 return visitNodes(cbNode, cbNodes, node.elementTypes);
18941             case 178 /* UnionType */:
18942             case 179 /* IntersectionType */:
18943                 return visitNodes(cbNode, cbNodes, node.types);
18944             case 180 /* ConditionalType */:
18945                 return visitNode(cbNode, node.checkType) ||
18946                     visitNode(cbNode, node.extendsType) ||
18947                     visitNode(cbNode, node.trueType) ||
18948                     visitNode(cbNode, node.falseType);
18949             case 181 /* InferType */:
18950                 return visitNode(cbNode, node.typeParameter);
18951             case 188 /* ImportType */:
18952                 return visitNode(cbNode, node.argument) ||
18953                     visitNode(cbNode, node.qualifier) ||
18954                     visitNodes(cbNode, cbNodes, node.typeArguments);
18955             case 182 /* ParenthesizedType */:
18956             case 184 /* TypeOperator */:
18957                 return visitNode(cbNode, node.type);
18958             case 185 /* IndexedAccessType */:
18959                 return visitNode(cbNode, node.objectType) ||
18960                     visitNode(cbNode, node.indexType);
18961             case 186 /* MappedType */:
18962                 return visitNode(cbNode, node.readonlyToken) ||
18963                     visitNode(cbNode, node.typeParameter) ||
18964                     visitNode(cbNode, node.questionToken) ||
18965                     visitNode(cbNode, node.type);
18966             case 187 /* LiteralType */:
18967                 return visitNode(cbNode, node.literal);
18968             case 189 /* ObjectBindingPattern */:
18969             case 190 /* ArrayBindingPattern */:
18970                 return visitNodes(cbNode, cbNodes, node.elements);
18971             case 192 /* ArrayLiteralExpression */:
18972                 return visitNodes(cbNode, cbNodes, node.elements);
18973             case 193 /* ObjectLiteralExpression */:
18974                 return visitNodes(cbNode, cbNodes, node.properties);
18975             case 194 /* PropertyAccessExpression */:
18976                 return visitNode(cbNode, node.expression) ||
18977                     visitNode(cbNode, node.questionDotToken) ||
18978                     visitNode(cbNode, node.name);
18979             case 195 /* ElementAccessExpression */:
18980                 return visitNode(cbNode, node.expression) ||
18981                     visitNode(cbNode, node.questionDotToken) ||
18982                     visitNode(cbNode, node.argumentExpression);
18983             case 196 /* CallExpression */:
18984             case 197 /* NewExpression */:
18985                 return visitNode(cbNode, node.expression) ||
18986                     visitNode(cbNode, node.questionDotToken) ||
18987                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18988                     visitNodes(cbNode, cbNodes, node.arguments);
18989             case 198 /* TaggedTemplateExpression */:
18990                 return visitNode(cbNode, node.tag) ||
18991                     visitNode(cbNode, node.questionDotToken) ||
18992                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18993                     visitNode(cbNode, node.template);
18994             case 199 /* TypeAssertionExpression */:
18995                 return visitNode(cbNode, node.type) ||
18996                     visitNode(cbNode, node.expression);
18997             case 200 /* ParenthesizedExpression */:
18998                 return visitNode(cbNode, node.expression);
18999             case 203 /* DeleteExpression */:
19000                 return visitNode(cbNode, node.expression);
19001             case 204 /* TypeOfExpression */:
19002                 return visitNode(cbNode, node.expression);
19003             case 205 /* VoidExpression */:
19004                 return visitNode(cbNode, node.expression);
19005             case 207 /* PrefixUnaryExpression */:
19006                 return visitNode(cbNode, node.operand);
19007             case 212 /* YieldExpression */:
19008                 return visitNode(cbNode, node.asteriskToken) ||
19009                     visitNode(cbNode, node.expression);
19010             case 206 /* AwaitExpression */:
19011                 return visitNode(cbNode, node.expression);
19012             case 208 /* PostfixUnaryExpression */:
19013                 return visitNode(cbNode, node.operand);
19014             case 209 /* BinaryExpression */:
19015                 return visitNode(cbNode, node.left) ||
19016                     visitNode(cbNode, node.operatorToken) ||
19017                     visitNode(cbNode, node.right);
19018             case 217 /* AsExpression */:
19019                 return visitNode(cbNode, node.expression) ||
19020                     visitNode(cbNode, node.type);
19021             case 218 /* NonNullExpression */:
19022                 return visitNode(cbNode, node.expression);
19023             case 219 /* MetaProperty */:
19024                 return visitNode(cbNode, node.name);
19025             case 210 /* ConditionalExpression */:
19026                 return visitNode(cbNode, node.condition) ||
19027                     visitNode(cbNode, node.questionToken) ||
19028                     visitNode(cbNode, node.whenTrue) ||
19029                     visitNode(cbNode, node.colonToken) ||
19030                     visitNode(cbNode, node.whenFalse);
19031             case 213 /* SpreadElement */:
19032                 return visitNode(cbNode, node.expression);
19033             case 223 /* Block */:
19034             case 250 /* ModuleBlock */:
19035                 return visitNodes(cbNode, cbNodes, node.statements);
19036             case 290 /* SourceFile */:
19037                 return visitNodes(cbNode, cbNodes, node.statements) ||
19038                     visitNode(cbNode, node.endOfFileToken);
19039             case 225 /* VariableStatement */:
19040                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19041                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19042                     visitNode(cbNode, node.declarationList);
19043             case 243 /* VariableDeclarationList */:
19044                 return visitNodes(cbNode, cbNodes, node.declarations);
19045             case 226 /* ExpressionStatement */:
19046                 return visitNode(cbNode, node.expression);
19047             case 227 /* IfStatement */:
19048                 return visitNode(cbNode, node.expression) ||
19049                     visitNode(cbNode, node.thenStatement) ||
19050                     visitNode(cbNode, node.elseStatement);
19051             case 228 /* DoStatement */:
19052                 return visitNode(cbNode, node.statement) ||
19053                     visitNode(cbNode, node.expression);
19054             case 229 /* WhileStatement */:
19055                 return visitNode(cbNode, node.expression) ||
19056                     visitNode(cbNode, node.statement);
19057             case 230 /* ForStatement */:
19058                 return visitNode(cbNode, node.initializer) ||
19059                     visitNode(cbNode, node.condition) ||
19060                     visitNode(cbNode, node.incrementor) ||
19061                     visitNode(cbNode, node.statement);
19062             case 231 /* ForInStatement */:
19063                 return visitNode(cbNode, node.initializer) ||
19064                     visitNode(cbNode, node.expression) ||
19065                     visitNode(cbNode, node.statement);
19066             case 232 /* ForOfStatement */:
19067                 return visitNode(cbNode, node.awaitModifier) ||
19068                     visitNode(cbNode, node.initializer) ||
19069                     visitNode(cbNode, node.expression) ||
19070                     visitNode(cbNode, node.statement);
19071             case 233 /* ContinueStatement */:
19072             case 234 /* BreakStatement */:
19073                 return visitNode(cbNode, node.label);
19074             case 235 /* ReturnStatement */:
19075                 return visitNode(cbNode, node.expression);
19076             case 236 /* WithStatement */:
19077                 return visitNode(cbNode, node.expression) ||
19078                     visitNode(cbNode, node.statement);
19079             case 237 /* SwitchStatement */:
19080                 return visitNode(cbNode, node.expression) ||
19081                     visitNode(cbNode, node.caseBlock);
19082             case 251 /* CaseBlock */:
19083                 return visitNodes(cbNode, cbNodes, node.clauses);
19084             case 277 /* CaseClause */:
19085                 return visitNode(cbNode, node.expression) ||
19086                     visitNodes(cbNode, cbNodes, node.statements);
19087             case 278 /* DefaultClause */:
19088                 return visitNodes(cbNode, cbNodes, node.statements);
19089             case 238 /* LabeledStatement */:
19090                 return visitNode(cbNode, node.label) ||
19091                     visitNode(cbNode, node.statement);
19092             case 239 /* ThrowStatement */:
19093                 return visitNode(cbNode, node.expression);
19094             case 240 /* TryStatement */:
19095                 return visitNode(cbNode, node.tryBlock) ||
19096                     visitNode(cbNode, node.catchClause) ||
19097                     visitNode(cbNode, node.finallyBlock);
19098             case 280 /* CatchClause */:
19099                 return visitNode(cbNode, node.variableDeclaration) ||
19100                     visitNode(cbNode, node.block);
19101             case 157 /* Decorator */:
19102                 return visitNode(cbNode, node.expression);
19103             case 245 /* ClassDeclaration */:
19104             case 214 /* ClassExpression */:
19105                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19106                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19107                     visitNode(cbNode, node.name) ||
19108                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19109                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19110                     visitNodes(cbNode, cbNodes, node.members);
19111             case 246 /* InterfaceDeclaration */:
19112                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19113                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19114                     visitNode(cbNode, node.name) ||
19115                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19116                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19117                     visitNodes(cbNode, cbNodes, node.members);
19118             case 247 /* TypeAliasDeclaration */:
19119                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19120                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19121                     visitNode(cbNode, node.name) ||
19122                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19123                     visitNode(cbNode, node.type);
19124             case 248 /* EnumDeclaration */:
19125                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19126                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19127                     visitNode(cbNode, node.name) ||
19128                     visitNodes(cbNode, cbNodes, node.members);
19129             case 284 /* EnumMember */:
19130                 return visitNode(cbNode, node.name) ||
19131                     visitNode(cbNode, node.initializer);
19132             case 249 /* ModuleDeclaration */:
19133                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19134                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19135                     visitNode(cbNode, node.name) ||
19136                     visitNode(cbNode, node.body);
19137             case 253 /* ImportEqualsDeclaration */:
19138                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19139                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19140                     visitNode(cbNode, node.name) ||
19141                     visitNode(cbNode, node.moduleReference);
19142             case 254 /* ImportDeclaration */:
19143                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19144                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19145                     visitNode(cbNode, node.importClause) ||
19146                     visitNode(cbNode, node.moduleSpecifier);
19147             case 255 /* ImportClause */:
19148                 return visitNode(cbNode, node.name) ||
19149                     visitNode(cbNode, node.namedBindings);
19150             case 252 /* NamespaceExportDeclaration */:
19151                 return visitNode(cbNode, node.name);
19152             case 256 /* NamespaceImport */:
19153                 return visitNode(cbNode, node.name);
19154             case 262 /* NamespaceExport */:
19155                 return visitNode(cbNode, node.name);
19156             case 257 /* NamedImports */:
19157             case 261 /* NamedExports */:
19158                 return visitNodes(cbNode, cbNodes, node.elements);
19159             case 260 /* ExportDeclaration */:
19160                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19161                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19162                     visitNode(cbNode, node.exportClause) ||
19163                     visitNode(cbNode, node.moduleSpecifier);
19164             case 258 /* ImportSpecifier */:
19165             case 263 /* ExportSpecifier */:
19166                 return visitNode(cbNode, node.propertyName) ||
19167                     visitNode(cbNode, node.name);
19168             case 259 /* ExportAssignment */:
19169                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19170                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19171                     visitNode(cbNode, node.expression);
19172             case 211 /* TemplateExpression */:
19173                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
19174             case 221 /* TemplateSpan */:
19175                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
19176             case 154 /* ComputedPropertyName */:
19177                 return visitNode(cbNode, node.expression);
19178             case 279 /* HeritageClause */:
19179                 return visitNodes(cbNode, cbNodes, node.types);
19180             case 216 /* ExpressionWithTypeArguments */:
19181                 return visitNode(cbNode, node.expression) ||
19182                     visitNodes(cbNode, cbNodes, node.typeArguments);
19183             case 265 /* ExternalModuleReference */:
19184                 return visitNode(cbNode, node.expression);
19185             case 264 /* MissingDeclaration */:
19186                 return visitNodes(cbNode, cbNodes, node.decorators);
19187             case 327 /* CommaListExpression */:
19188                 return visitNodes(cbNode, cbNodes, node.elements);
19189             case 266 /* JsxElement */:
19190                 return visitNode(cbNode, node.openingElement) ||
19191                     visitNodes(cbNode, cbNodes, node.children) ||
19192                     visitNode(cbNode, node.closingElement);
19193             case 270 /* JsxFragment */:
19194                 return visitNode(cbNode, node.openingFragment) ||
19195                     visitNodes(cbNode, cbNodes, node.children) ||
19196                     visitNode(cbNode, node.closingFragment);
19197             case 267 /* JsxSelfClosingElement */:
19198             case 268 /* JsxOpeningElement */:
19199                 return visitNode(cbNode, node.tagName) ||
19200                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19201                     visitNode(cbNode, node.attributes);
19202             case 274 /* JsxAttributes */:
19203                 return visitNodes(cbNode, cbNodes, node.properties);
19204             case 273 /* JsxAttribute */:
19205                 return visitNode(cbNode, node.name) ||
19206                     visitNode(cbNode, node.initializer);
19207             case 275 /* JsxSpreadAttribute */:
19208                 return visitNode(cbNode, node.expression);
19209             case 276 /* JsxExpression */:
19210                 return visitNode(cbNode, node.dotDotDotToken) ||
19211                     visitNode(cbNode, node.expression);
19212             case 269 /* JsxClosingElement */:
19213                 return visitNode(cbNode, node.tagName);
19214             case 176 /* OptionalType */:
19215             case 177 /* RestType */:
19216             case 294 /* JSDocTypeExpression */:
19217             case 298 /* JSDocNonNullableType */:
19218             case 297 /* JSDocNullableType */:
19219             case 299 /* JSDocOptionalType */:
19220             case 301 /* JSDocVariadicType */:
19221                 return visitNode(cbNode, node.type);
19222             case 300 /* JSDocFunctionType */:
19223                 return visitNodes(cbNode, cbNodes, node.parameters) ||
19224                     visitNode(cbNode, node.type);
19225             case 303 /* JSDocComment */:
19226                 return visitNodes(cbNode, cbNodes, node.tags);
19227             case 317 /* JSDocParameterTag */:
19228             case 323 /* JSDocPropertyTag */:
19229                 return visitNode(cbNode, node.tagName) ||
19230                     (node.isNameFirst
19231                         ? visitNode(cbNode, node.name) ||
19232                             visitNode(cbNode, node.typeExpression)
19233                         : visitNode(cbNode, node.typeExpression) ||
19234                             visitNode(cbNode, node.name));
19235             case 309 /* JSDocAuthorTag */:
19236                 return visitNode(cbNode, node.tagName);
19237             case 308 /* JSDocImplementsTag */:
19238                 return visitNode(cbNode, node.tagName) ||
19239                     visitNode(cbNode, node.class);
19240             case 307 /* JSDocAugmentsTag */:
19241                 return visitNode(cbNode, node.tagName) ||
19242                     visitNode(cbNode, node.class);
19243             case 321 /* JSDocTemplateTag */:
19244                 return visitNode(cbNode, node.tagName) ||
19245                     visitNode(cbNode, node.constraint) ||
19246                     visitNodes(cbNode, cbNodes, node.typeParameters);
19247             case 322 /* JSDocTypedefTag */:
19248                 return visitNode(cbNode, node.tagName) ||
19249                     (node.typeExpression &&
19250                         node.typeExpression.kind === 294 /* JSDocTypeExpression */
19251                         ? visitNode(cbNode, node.typeExpression) ||
19252                             visitNode(cbNode, node.fullName)
19253                         : visitNode(cbNode, node.fullName) ||
19254                             visitNode(cbNode, node.typeExpression));
19255             case 315 /* JSDocCallbackTag */:
19256                 return visitNode(cbNode, node.tagName) ||
19257                     visitNode(cbNode, node.fullName) ||
19258                     visitNode(cbNode, node.typeExpression);
19259             case 318 /* JSDocReturnTag */:
19260             case 320 /* JSDocTypeTag */:
19261             case 319 /* JSDocThisTag */:
19262             case 316 /* JSDocEnumTag */:
19263                 return visitNode(cbNode, node.tagName) ||
19264                     visitNode(cbNode, node.typeExpression);
19265             case 305 /* JSDocSignature */:
19266                 return ts.forEach(node.typeParameters, cbNode) ||
19267                     ts.forEach(node.parameters, cbNode) ||
19268                     visitNode(cbNode, node.type);
19269             case 304 /* JSDocTypeLiteral */:
19270                 return ts.forEach(node.jsDocPropertyTags, cbNode);
19271             case 306 /* JSDocTag */:
19272             case 310 /* JSDocClassTag */:
19273             case 311 /* JSDocPublicTag */:
19274             case 312 /* JSDocPrivateTag */:
19275             case 313 /* JSDocProtectedTag */:
19276             case 314 /* JSDocReadonlyTag */:
19277                 return visitNode(cbNode, node.tagName);
19278             case 326 /* PartiallyEmittedExpression */:
19279                 return visitNode(cbNode, node.expression);
19280         }
19281     }
19282     ts.forEachChild = forEachChild;
19283     /** @internal */
19284     /**
19285      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
19286      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
19287      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
19288      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
19289      *
19290      * @param node a given node to visit its children
19291      * @param cbNode a callback to be invoked for all child nodes
19292      * @param cbNodes a callback to be invoked for embedded array
19293      *
19294      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
19295      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
19296      */
19297     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
19298         var stack = [rootNode];
19299         while (stack.length) {
19300             var parent = stack.pop();
19301             var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
19302             if (res) {
19303                 return res;
19304             }
19305         }
19306         return;
19307         function gatherPossibleChildren(node) {
19308             var children = [];
19309             forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
19310             return children;
19311             function addWorkItem(n) {
19312                 children.unshift(n);
19313             }
19314         }
19315         function visitAllPossibleChildren(parent, children) {
19316             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19317                 var child = children_1[_i];
19318                 if (ts.isArray(child)) {
19319                     if (cbNodes) {
19320                         var res = cbNodes(child, parent);
19321                         if (res) {
19322                             if (res === "skip")
19323                                 continue;
19324                             return res;
19325                         }
19326                     }
19327                     for (var i = child.length - 1; i >= 0; i--) {
19328                         var realChild = child[i];
19329                         var res = cbNode(realChild, parent);
19330                         if (res) {
19331                             if (res === "skip")
19332                                 continue;
19333                             return res;
19334                         }
19335                         stack.push(realChild);
19336                     }
19337                 }
19338                 else {
19339                     stack.push(child);
19340                     var res = cbNode(child, parent);
19341                     if (res) {
19342                         if (res === "skip")
19343                             continue;
19344                         return res;
19345                     }
19346                 }
19347             }
19348         }
19349     }
19350     ts.forEachChildRecursively = forEachChildRecursively;
19351     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
19352         if (setParentNodes === void 0) { setParentNodes = false; }
19353         ts.performance.mark("beforeParse");
19354         var result;
19355         ts.perfLogger.logStartParseSourceFile(fileName);
19356         if (languageVersion === 100 /* JSON */) {
19357             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
19358         }
19359         else {
19360             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
19361         }
19362         ts.perfLogger.logStopParseSourceFile();
19363         ts.performance.mark("afterParse");
19364         ts.performance.measure("Parse", "beforeParse", "afterParse");
19365         return result;
19366     }
19367     ts.createSourceFile = createSourceFile;
19368     function parseIsolatedEntityName(text, languageVersion) {
19369         return Parser.parseIsolatedEntityName(text, languageVersion);
19370     }
19371     ts.parseIsolatedEntityName = parseIsolatedEntityName;
19372     /**
19373      * Parse json text into SyntaxTree and return node and parse errors if any
19374      * @param fileName
19375      * @param sourceText
19376      */
19377     function parseJsonText(fileName, sourceText) {
19378         return Parser.parseJsonText(fileName, sourceText);
19379     }
19380     ts.parseJsonText = parseJsonText;
19381     // See also `isExternalOrCommonJsModule` in utilities.ts
19382     function isExternalModule(file) {
19383         return file.externalModuleIndicator !== undefined;
19384     }
19385     ts.isExternalModule = isExternalModule;
19386     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
19387     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
19388     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
19389     // this file as possible.
19390     //
19391     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
19392     // from this SourceFile that are being held onto may change as a result (including
19393     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
19394     // be used once 'update' is called on it.
19395     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
19396         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
19397         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
19398         // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import.
19399         // We will manually port the flag to the new source file.
19400         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
19401         return newSourceFile;
19402     }
19403     ts.updateSourceFile = updateSourceFile;
19404     /* @internal */
19405     function parseIsolatedJSDocComment(content, start, length) {
19406         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
19407         if (result && result.jsDoc) {
19408             // because the jsDocComment was parsed out of the source file, it might
19409             // not be covered by the fixupParentReferences.
19410             Parser.fixupParentReferences(result.jsDoc);
19411         }
19412         return result;
19413     }
19414     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
19415     /* @internal */
19416     // Exposed only for testing.
19417     function parseJSDocTypeExpressionForTests(content, start, length) {
19418         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
19419     }
19420     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
19421     // Implement the parser as a singleton module.  We do this for perf reasons because creating
19422     // parser instances can actually be expensive enough to impact us on projects with many source
19423     // files.
19424     var Parser;
19425     (function (Parser) {
19426         // Share a single scanner across all calls to parse a source file.  This helps speed things
19427         // up by avoiding the cost of creating/compiling scanners over and over again.
19428         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
19429         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
19430         // capture constructors in 'initializeState' to avoid null checks
19431         var NodeConstructor;
19432         var TokenConstructor;
19433         var IdentifierConstructor;
19434         var PrivateIdentifierConstructor;
19435         var SourceFileConstructor;
19436         var sourceFile;
19437         var parseDiagnostics;
19438         var syntaxCursor;
19439         var currentToken;
19440         var sourceText;
19441         var nodeCount;
19442         var identifiers;
19443         var privateIdentifiers;
19444         var identifierCount;
19445         var parsingContext;
19446         var notParenthesizedArrow;
19447         // Flags that dictate what parsing context we're in.  For example:
19448         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
19449         // that some tokens that would be considered identifiers may be considered keywords.
19450         //
19451         // When adding more parser context flags, consider which is the more common case that the
19452         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
19453         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
19454         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
19455         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
19456         // all nodes would need extra state on them to store this info.
19457         //
19458         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
19459         // grammar specification.
19460         //
19461         // An important thing about these context concepts.  By default they are effectively inherited
19462         // while parsing through every grammar production.  i.e. if you don't change them, then when
19463         // you parse a sub-production, it will have the same context values as the parent production.
19464         // This is great most of the time.  After all, consider all the 'expression' grammar productions
19465         // and how nearly all of them pass along the 'in' and 'yield' context values:
19466         //
19467         // EqualityExpression[In, Yield] :
19468         //      RelationalExpression[?In, ?Yield]
19469         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
19470         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
19471         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
19472         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
19473         //
19474         // Where you have to be careful is then understanding what the points are in the grammar
19475         // where the values are *not* passed along.  For example:
19476         //
19477         // SingleNameBinding[Yield,GeneratorParameter]
19478         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
19479         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
19480         //
19481         // Here this is saying that if the GeneratorParameter context flag is set, that we should
19482         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
19483         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
19484         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
19485         // should leave the 'yield' context flag alone.
19486         //
19487         // Getting this all correct is tricky and requires careful reading of the grammar to
19488         // understand when these values should be changed versus when they should be inherited.
19489         //
19490         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
19491         // parsing.  These context flags are naturally stored and restored through normal recursive
19492         // descent parsing and unwinding.
19493         var contextFlags;
19494         // Whether or not we've had a parse error since creating the last AST node.  If we have
19495         // encountered an error, it will be stored on the next AST node we create.  Parse errors
19496         // can be broken down into three categories:
19497         //
19498         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
19499         //    character that was completely not understood.
19500         //
19501         // 2) A token was expected, but was not present.  This type of error is commonly produced
19502         //    by the 'parseExpected' function.
19503         //
19504         // 3) A token was present that no parsing function was able to consume.  This type of error
19505         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
19506         //    decides to skip the token.
19507         //
19508         // In all of these cases, we want to mark the next node as having had an error before it.
19509         // With this mark, we can know in incremental settings if this node can be reused, or if
19510         // we have to reparse it.  If we don't keep this information around, we may just reuse the
19511         // node.  in that event we would then not produce the same errors as we did before, causing
19512         // significant confusion problems.
19513         //
19514         // Note: it is necessary that this value be saved/restored during speculative/lookahead
19515         // parsing.  During lookahead parsing, we will often create a node.  That node will have
19516         // this value attached, and then this value will be set back to 'false'.  If we decide to
19517         // rewind, we must get back to the same value we had prior to the lookahead.
19518         //
19519         // Note: any errors at the end of the file that do not precede a regular node, should get
19520         // attached to the EOF token.
19521         var parseErrorBeforeNextFinishedNode = false;
19522         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
19523             if (setParentNodes === void 0) { setParentNodes = false; }
19524             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
19525             if (scriptKind === 6 /* JSON */) {
19526                 var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
19527                 ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
19528                 result_2.referencedFiles = ts.emptyArray;
19529                 result_2.typeReferenceDirectives = ts.emptyArray;
19530                 result_2.libReferenceDirectives = ts.emptyArray;
19531                 result_2.amdDependencies = ts.emptyArray;
19532                 result_2.hasNoDefaultLib = false;
19533                 result_2.pragmas = ts.emptyMap;
19534                 return result_2;
19535             }
19536             initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
19537             var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
19538             clearState();
19539             return result;
19540         }
19541         Parser.parseSourceFile = parseSourceFile;
19542         function parseIsolatedEntityName(content, languageVersion) {
19543             // Choice of `isDeclarationFile` should be arbitrary
19544             initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
19545             // Prime the scanner.
19546             nextToken();
19547             var entityName = parseEntityName(/*allowReservedWords*/ true);
19548             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
19549             clearState();
19550             return isInvalid ? entityName : undefined;
19551         }
19552         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
19553         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
19554             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
19555             initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
19556             // Set source file so that errors will be reported with this file name
19557             sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
19558             sourceFile.flags = contextFlags;
19559             // Prime the scanner.
19560             nextToken();
19561             var pos = getNodePos();
19562             if (token() === 1 /* EndOfFileToken */) {
19563                 sourceFile.statements = createNodeArray([], pos, pos);
19564                 sourceFile.endOfFileToken = parseTokenNode();
19565             }
19566             else {
19567                 var statement = createNode(226 /* ExpressionStatement */);
19568                 switch (token()) {
19569                     case 22 /* OpenBracketToken */:
19570                         statement.expression = parseArrayLiteralExpression();
19571                         break;
19572                     case 106 /* TrueKeyword */:
19573                     case 91 /* FalseKeyword */:
19574                     case 100 /* NullKeyword */:
19575                         statement.expression = parseTokenNode();
19576                         break;
19577                     case 40 /* MinusToken */:
19578                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
19579                             statement.expression = parsePrefixUnaryExpression();
19580                         }
19581                         else {
19582                             statement.expression = parseObjectLiteralExpression();
19583                         }
19584                         break;
19585                     case 8 /* NumericLiteral */:
19586                     case 10 /* StringLiteral */:
19587                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
19588                             statement.expression = parseLiteralNode();
19589                             break;
19590                         }
19591                     // falls through
19592                     default:
19593                         statement.expression = parseObjectLiteralExpression();
19594                         break;
19595                 }
19596                 finishNode(statement);
19597                 sourceFile.statements = createNodeArray([statement], pos);
19598                 sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
19599             }
19600             if (setParentNodes) {
19601                 fixupParentReferences(sourceFile);
19602             }
19603             sourceFile.nodeCount = nodeCount;
19604             sourceFile.identifierCount = identifierCount;
19605             sourceFile.identifiers = identifiers;
19606             sourceFile.parseDiagnostics = parseDiagnostics;
19607             var result = sourceFile;
19608             clearState();
19609             return result;
19610         }
19611         Parser.parseJsonText = parseJsonText;
19612         function getLanguageVariant(scriptKind) {
19613             // .tsx and .jsx files are treated as jsx language variant.
19614             return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
19615         }
19616         function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
19617             NodeConstructor = ts.objectAllocator.getNodeConstructor();
19618             TokenConstructor = ts.objectAllocator.getTokenConstructor();
19619             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
19620             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
19621             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
19622             sourceText = _sourceText;
19623             syntaxCursor = _syntaxCursor;
19624             parseDiagnostics = [];
19625             parsingContext = 0;
19626             identifiers = ts.createMap();
19627             privateIdentifiers = ts.createMap();
19628             identifierCount = 0;
19629             nodeCount = 0;
19630             switch (scriptKind) {
19631                 case 1 /* JS */:
19632                 case 2 /* JSX */:
19633                     contextFlags = 131072 /* JavaScriptFile */;
19634                     break;
19635                 case 6 /* JSON */:
19636                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
19637                     break;
19638                 default:
19639                     contextFlags = 0 /* None */;
19640                     break;
19641             }
19642             parseErrorBeforeNextFinishedNode = false;
19643             // Initialize and prime the scanner before parsing the source elements.
19644             scanner.setText(sourceText);
19645             scanner.setOnError(scanError);
19646             scanner.setScriptTarget(languageVersion);
19647             scanner.setLanguageVariant(getLanguageVariant(scriptKind));
19648         }
19649         function clearState() {
19650             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
19651             scanner.clearCommentDirectives();
19652             scanner.setText("");
19653             scanner.setOnError(undefined);
19654             // Clear any data.  We don't want to accidentally hold onto it for too long.
19655             parseDiagnostics = undefined;
19656             sourceFile = undefined;
19657             identifiers = undefined;
19658             syntaxCursor = undefined;
19659             sourceText = undefined;
19660             notParenthesizedArrow = undefined;
19661         }
19662         function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
19663             var isDeclarationFile = isDeclarationFileName(fileName);
19664             if (isDeclarationFile) {
19665                 contextFlags |= 8388608 /* Ambient */;
19666             }
19667             sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
19668             sourceFile.flags = contextFlags;
19669             // Prime the scanner.
19670             nextToken();
19671             // A member of ReadonlyArray<T> isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future
19672             processCommentPragmas(sourceFile, sourceText);
19673             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
19674             sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
19675             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
19676             sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
19677             setExternalModuleIndicator(sourceFile);
19678             sourceFile.commentDirectives = scanner.getCommentDirectives();
19679             sourceFile.nodeCount = nodeCount;
19680             sourceFile.identifierCount = identifierCount;
19681             sourceFile.identifiers = identifiers;
19682             sourceFile.parseDiagnostics = parseDiagnostics;
19683             if (setParentNodes) {
19684                 fixupParentReferences(sourceFile);
19685             }
19686             return sourceFile;
19687             function reportPragmaDiagnostic(pos, end, diagnostic) {
19688                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
19689             }
19690         }
19691         function addJSDocComment(node) {
19692             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
19693             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
19694             if (jsDoc.length)
19695                 node.jsDoc = jsDoc;
19696             return node;
19697         }
19698         function fixupParentReferences(rootNode) {
19699             // normally parent references are set during binding. However, for clients that only need
19700             // a syntax tree, and no semantic features, then the binding process is an unnecessary
19701             // overhead.  This functions allows us to set all the parents, without all the expense of
19702             // binding.
19703             forEachChildRecursively(rootNode, bindParentToChild);
19704             function bindParentToChild(child, parent) {
19705                 child.parent = parent;
19706                 if (ts.hasJSDocNodes(child)) {
19707                     for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19708                         var doc = _a[_i];
19709                         bindParentToChild(doc, child);
19710                         forEachChildRecursively(doc, bindParentToChild);
19711                     }
19712                 }
19713             }
19714         }
19715         Parser.fixupParentReferences = fixupParentReferences;
19716         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
19717             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
19718             // this is quite rare comparing to other nodes and createNode should be as fast as possible
19719             var sourceFile = new SourceFileConstructor(290 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
19720             nodeCount++;
19721             sourceFile.text = sourceText;
19722             sourceFile.bindDiagnostics = [];
19723             sourceFile.bindSuggestionDiagnostics = undefined;
19724             sourceFile.languageVersion = languageVersion;
19725             sourceFile.fileName = ts.normalizePath(fileName);
19726             sourceFile.languageVariant = getLanguageVariant(scriptKind);
19727             sourceFile.isDeclarationFile = isDeclarationFile;
19728             sourceFile.scriptKind = scriptKind;
19729             return sourceFile;
19730         }
19731         function setContextFlag(val, flag) {
19732             if (val) {
19733                 contextFlags |= flag;
19734             }
19735             else {
19736                 contextFlags &= ~flag;
19737             }
19738         }
19739         function setDisallowInContext(val) {
19740             setContextFlag(val, 4096 /* DisallowInContext */);
19741         }
19742         function setYieldContext(val) {
19743             setContextFlag(val, 8192 /* YieldContext */);
19744         }
19745         function setDecoratorContext(val) {
19746             setContextFlag(val, 16384 /* DecoratorContext */);
19747         }
19748         function setAwaitContext(val) {
19749             setContextFlag(val, 32768 /* AwaitContext */);
19750         }
19751         function doOutsideOfContext(context, func) {
19752             // contextFlagsToClear will contain only the context flags that are
19753             // currently set that we need to temporarily clear
19754             // We don't just blindly reset to the previous flags to ensure
19755             // that we do not mutate cached flags for the incremental
19756             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19757             // HasAggregatedChildData).
19758             var contextFlagsToClear = context & contextFlags;
19759             if (contextFlagsToClear) {
19760                 // clear the requested context flags
19761                 setContextFlag(/*val*/ false, contextFlagsToClear);
19762                 var result = func();
19763                 // restore the context flags we just cleared
19764                 setContextFlag(/*val*/ true, contextFlagsToClear);
19765                 return result;
19766             }
19767             // no need to do anything special as we are not in any of the requested contexts
19768             return func();
19769         }
19770         function doInsideOfContext(context, func) {
19771             // contextFlagsToSet will contain only the context flags that
19772             // are not currently set that we need to temporarily enable.
19773             // We don't just blindly reset to the previous flags to ensure
19774             // that we do not mutate cached flags for the incremental
19775             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19776             // HasAggregatedChildData).
19777             var contextFlagsToSet = context & ~contextFlags;
19778             if (contextFlagsToSet) {
19779                 // set the requested context flags
19780                 setContextFlag(/*val*/ true, contextFlagsToSet);
19781                 var result = func();
19782                 // reset the context flags we just set
19783                 setContextFlag(/*val*/ false, contextFlagsToSet);
19784                 return result;
19785             }
19786             // no need to do anything special as we are already in all of the requested contexts
19787             return func();
19788         }
19789         function allowInAnd(func) {
19790             return doOutsideOfContext(4096 /* DisallowInContext */, func);
19791         }
19792         function disallowInAnd(func) {
19793             return doInsideOfContext(4096 /* DisallowInContext */, func);
19794         }
19795         function doInYieldContext(func) {
19796             return doInsideOfContext(8192 /* YieldContext */, func);
19797         }
19798         function doInDecoratorContext(func) {
19799             return doInsideOfContext(16384 /* DecoratorContext */, func);
19800         }
19801         function doInAwaitContext(func) {
19802             return doInsideOfContext(32768 /* AwaitContext */, func);
19803         }
19804         function doOutsideOfAwaitContext(func) {
19805             return doOutsideOfContext(32768 /* AwaitContext */, func);
19806         }
19807         function doInYieldAndAwaitContext(func) {
19808             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19809         }
19810         function doOutsideOfYieldAndAwaitContext(func) {
19811             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19812         }
19813         function inContext(flags) {
19814             return (contextFlags & flags) !== 0;
19815         }
19816         function inYieldContext() {
19817             return inContext(8192 /* YieldContext */);
19818         }
19819         function inDisallowInContext() {
19820             return inContext(4096 /* DisallowInContext */);
19821         }
19822         function inDecoratorContext() {
19823             return inContext(16384 /* DecoratorContext */);
19824         }
19825         function inAwaitContext() {
19826             return inContext(32768 /* AwaitContext */);
19827         }
19828         function parseErrorAtCurrentToken(message, arg0) {
19829             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
19830         }
19831         function parseErrorAtPosition(start, length, message, arg0) {
19832             // Don't report another error if it would just be at the same position as the last error.
19833             var lastError = ts.lastOrUndefined(parseDiagnostics);
19834             if (!lastError || start !== lastError.start) {
19835                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
19836             }
19837             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
19838             // node we finish so that it can't be reused incrementally.
19839             parseErrorBeforeNextFinishedNode = true;
19840         }
19841         function parseErrorAt(start, end, message, arg0) {
19842             parseErrorAtPosition(start, end - start, message, arg0);
19843         }
19844         function parseErrorAtRange(range, message, arg0) {
19845             parseErrorAt(range.pos, range.end, message, arg0);
19846         }
19847         function scanError(message, length) {
19848             parseErrorAtPosition(scanner.getTextPos(), length, message);
19849         }
19850         function getNodePos() {
19851             return scanner.getStartPos();
19852         }
19853         // Use this function to access the current token instead of reading the currentToken
19854         // variable. Since function results aren't narrowed in control flow analysis, this ensures
19855         // that the type checker doesn't make wrong assumptions about the type of the current
19856         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
19857         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
19858         // there is no performance penalty.
19859         function token() {
19860             return currentToken;
19861         }
19862         function nextTokenWithoutCheck() {
19863             return currentToken = scanner.scan();
19864         }
19865         function nextToken() {
19866             // if the keyword had an escape
19867             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
19868                 // issue a parse error for the escape
19869                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
19870             }
19871             return nextTokenWithoutCheck();
19872         }
19873         function nextTokenJSDoc() {
19874             return currentToken = scanner.scanJsDocToken();
19875         }
19876         function reScanGreaterToken() {
19877             return currentToken = scanner.reScanGreaterToken();
19878         }
19879         function reScanSlashToken() {
19880             return currentToken = scanner.reScanSlashToken();
19881         }
19882         function reScanTemplateToken(isTaggedTemplate) {
19883             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
19884         }
19885         function reScanTemplateHeadOrNoSubstitutionTemplate() {
19886             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
19887         }
19888         function reScanLessThanToken() {
19889             return currentToken = scanner.reScanLessThanToken();
19890         }
19891         function scanJsxIdentifier() {
19892             return currentToken = scanner.scanJsxIdentifier();
19893         }
19894         function scanJsxText() {
19895             return currentToken = scanner.scanJsxToken();
19896         }
19897         function scanJsxAttributeValue() {
19898             return currentToken = scanner.scanJsxAttributeValue();
19899         }
19900         function speculationHelper(callback, isLookAhead) {
19901             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
19902             // caller asked us to always reset our state).
19903             var saveToken = currentToken;
19904             var saveParseDiagnosticsLength = parseDiagnostics.length;
19905             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
19906             // Note: it is not actually necessary to save/restore the context flags here.  That's
19907             // because the saving/restoring of these flags happens naturally through the recursive
19908             // descent nature of our parser.  However, we still store this here just so we can
19909             // assert that invariant holds.
19910             var saveContextFlags = contextFlags;
19911             // If we're only looking ahead, then tell the scanner to only lookahead as well.
19912             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
19913             // same.
19914             var result = isLookAhead
19915                 ? scanner.lookAhead(callback)
19916                 : scanner.tryScan(callback);
19917             ts.Debug.assert(saveContextFlags === contextFlags);
19918             // If our callback returned something 'falsy' or we're just looking ahead,
19919             // then unconditionally restore us to where we were.
19920             if (!result || isLookAhead) {
19921                 currentToken = saveToken;
19922                 parseDiagnostics.length = saveParseDiagnosticsLength;
19923                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
19924             }
19925             return result;
19926         }
19927         /** Invokes the provided callback then unconditionally restores the parser to the state it
19928          * was in immediately prior to invoking the callback.  The result of invoking the callback
19929          * is returned from this function.
19930          */
19931         function lookAhead(callback) {
19932             return speculationHelper(callback, /*isLookAhead*/ true);
19933         }
19934         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
19935          * the parser to the state it was in immediately prior to invoking the callback.  If the
19936          * callback returns something truthy, then the parser state is not rolled back.  The result
19937          * of invoking the callback is returned from this function.
19938          */
19939         function tryParse(callback) {
19940             return speculationHelper(callback, /*isLookAhead*/ false);
19941         }
19942         // Ignore strict mode flag because we will report an error in type checker instead.
19943         function isIdentifier() {
19944             if (token() === 75 /* Identifier */) {
19945                 return true;
19946             }
19947             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
19948             // considered a keyword and is not an identifier.
19949             if (token() === 121 /* YieldKeyword */ && inYieldContext()) {
19950                 return false;
19951             }
19952             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
19953             // considered a keyword and is not an identifier.
19954             if (token() === 127 /* AwaitKeyword */ && inAwaitContext()) {
19955                 return false;
19956             }
19957             return token() > 112 /* LastReservedWord */;
19958         }
19959         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
19960             if (shouldAdvance === void 0) { shouldAdvance = true; }
19961             if (token() === kind) {
19962                 if (shouldAdvance) {
19963                     nextToken();
19964                 }
19965                 return true;
19966             }
19967             // Report specific message if provided with one.  Otherwise, report generic fallback message.
19968             if (diagnosticMessage) {
19969                 parseErrorAtCurrentToken(diagnosticMessage);
19970             }
19971             else {
19972                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19973             }
19974             return false;
19975         }
19976         function parseExpectedJSDoc(kind) {
19977             if (token() === kind) {
19978                 nextTokenJSDoc();
19979                 return true;
19980             }
19981             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19982             return false;
19983         }
19984         function parseOptional(t) {
19985             if (token() === t) {
19986                 nextToken();
19987                 return true;
19988             }
19989             return false;
19990         }
19991         function parseOptionalToken(t) {
19992             if (token() === t) {
19993                 return parseTokenNode();
19994             }
19995             return undefined;
19996         }
19997         function parseOptionalTokenJSDoc(t) {
19998             if (token() === t) {
19999                 return parseTokenNodeJSDoc();
20000             }
20001             return undefined;
20002         }
20003         function parseExpectedToken(t, diagnosticMessage, arg0) {
20004             return parseOptionalToken(t) ||
20005                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
20006         }
20007         function parseExpectedTokenJSDoc(t) {
20008             return parseOptionalTokenJSDoc(t) ||
20009                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
20010         }
20011         function parseTokenNode() {
20012             var node = createNode(token());
20013             nextToken();
20014             return finishNode(node);
20015         }
20016         function parseTokenNodeJSDoc() {
20017             var node = createNode(token());
20018             nextTokenJSDoc();
20019             return finishNode(node);
20020         }
20021         function canParseSemicolon() {
20022             // If there's a real semicolon, then we can always parse it out.
20023             if (token() === 26 /* SemicolonToken */) {
20024                 return true;
20025             }
20026             // We can parse out an optional semicolon in ASI cases in the following cases.
20027             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
20028         }
20029         function parseSemicolon() {
20030             if (canParseSemicolon()) {
20031                 if (token() === 26 /* SemicolonToken */) {
20032                     // consume the semicolon if it was explicitly provided.
20033                     nextToken();
20034                 }
20035                 return true;
20036             }
20037             else {
20038                 return parseExpected(26 /* SemicolonToken */);
20039             }
20040         }
20041         function createNode(kind, pos) {
20042             nodeCount++;
20043             var p = pos >= 0 ? pos : scanner.getStartPos();
20044             return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
20045                 kind === 75 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
20046                     kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierConstructor(kind, p, p) :
20047                         new TokenConstructor(kind, p, p);
20048         }
20049         function createNodeWithJSDoc(kind, pos) {
20050             var node = createNode(kind, pos);
20051             if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */ && (kind !== 226 /* ExpressionStatement */ || token() !== 20 /* OpenParenToken */)) {
20052                 addJSDocComment(node);
20053             }
20054             return node;
20055         }
20056         function createNodeArray(elements, pos, end) {
20057             // Since the element list of a node array is typically created by starting with an empty array and
20058             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20059             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20060             var length = elements.length;
20061             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20062             array.pos = pos;
20063             array.end = end === undefined ? scanner.getStartPos() : end;
20064             return array;
20065         }
20066         function finishNode(node, end) {
20067             node.end = end === undefined ? scanner.getStartPos() : end;
20068             if (contextFlags) {
20069                 node.flags |= contextFlags;
20070             }
20071             // Keep track on the node if we encountered an error while parsing it.  If we did, then
20072             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
20073             // flag so that we don't mark any subsequent nodes.
20074             if (parseErrorBeforeNextFinishedNode) {
20075                 parseErrorBeforeNextFinishedNode = false;
20076                 node.flags |= 65536 /* ThisNodeHasError */;
20077             }
20078             return node;
20079         }
20080         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
20081             if (reportAtCurrentPosition) {
20082                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
20083             }
20084             else if (diagnosticMessage) {
20085                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
20086             }
20087             var result = createNode(kind);
20088             if (kind === 75 /* Identifier */) {
20089                 result.escapedText = "";
20090             }
20091             else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
20092                 result.text = "";
20093             }
20094             return finishNode(result);
20095         }
20096         function internIdentifier(text) {
20097             var identifier = identifiers.get(text);
20098             if (identifier === undefined) {
20099                 identifiers.set(text, identifier = text);
20100             }
20101             return identifier;
20102         }
20103         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
20104         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
20105         // each identifier in order to reduce memory consumption.
20106         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
20107             identifierCount++;
20108             if (isIdentifier) {
20109                 var node = createNode(75 /* Identifier */);
20110                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
20111                 if (token() !== 75 /* Identifier */) {
20112                     node.originalKeywordKind = token();
20113                 }
20114                 node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
20115                 nextTokenWithoutCheck();
20116                 return finishNode(node);
20117             }
20118             if (token() === 76 /* PrivateIdentifier */) {
20119                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
20120                 return createIdentifier(/*isIdentifier*/ true);
20121             }
20122             // Only for end of file because the error gets reported incorrectly on embedded script tags.
20123             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
20124             var isReservedWord = scanner.isReservedWord();
20125             var msgArg = scanner.getTokenText();
20126             var defaultMessage = isReservedWord ?
20127                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
20128                 ts.Diagnostics.Identifier_expected;
20129             return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
20130         }
20131         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
20132             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
20133         }
20134         function parseIdentifierName(diagnosticMessage) {
20135             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
20136         }
20137         function isLiteralPropertyName() {
20138             return ts.tokenIsIdentifierOrKeyword(token()) ||
20139                 token() === 10 /* StringLiteral */ ||
20140                 token() === 8 /* NumericLiteral */;
20141         }
20142         function parsePropertyNameWorker(allowComputedPropertyNames) {
20143             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
20144                 var node = parseLiteralNode();
20145                 node.text = internIdentifier(node.text);
20146                 return node;
20147             }
20148             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
20149                 return parseComputedPropertyName();
20150             }
20151             if (token() === 76 /* PrivateIdentifier */) {
20152                 return parsePrivateIdentifier();
20153             }
20154             return parseIdentifierName();
20155         }
20156         function parsePropertyName() {
20157             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
20158         }
20159         function parseComputedPropertyName() {
20160             // PropertyName [Yield]:
20161             //      LiteralPropertyName
20162             //      ComputedPropertyName[?Yield]
20163             var node = createNode(154 /* ComputedPropertyName */);
20164             parseExpected(22 /* OpenBracketToken */);
20165             // We parse any expression (including a comma expression). But the grammar
20166             // says that only an assignment expression is allowed, so the grammar checker
20167             // will error if it sees a comma expression.
20168             node.expression = allowInAnd(parseExpression);
20169             parseExpected(23 /* CloseBracketToken */);
20170             return finishNode(node);
20171         }
20172         function internPrivateIdentifier(text) {
20173             var privateIdentifier = privateIdentifiers.get(text);
20174             if (privateIdentifier === undefined) {
20175                 privateIdentifiers.set(text, privateIdentifier = text);
20176             }
20177             return privateIdentifier;
20178         }
20179         function parsePrivateIdentifier() {
20180             var node = createNode(76 /* PrivateIdentifier */);
20181             node.escapedText = ts.escapeLeadingUnderscores(internPrivateIdentifier(scanner.getTokenText()));
20182             nextToken();
20183             return finishNode(node);
20184         }
20185         function parseContextualModifier(t) {
20186             return token() === t && tryParse(nextTokenCanFollowModifier);
20187         }
20188         function nextTokenIsOnSameLineAndCanFollowModifier() {
20189             nextToken();
20190             if (scanner.hasPrecedingLineBreak()) {
20191                 return false;
20192             }
20193             return canFollowModifier();
20194         }
20195         function nextTokenCanFollowModifier() {
20196             switch (token()) {
20197                 case 81 /* ConstKeyword */:
20198                     // 'const' is only a modifier if followed by 'enum'.
20199                     return nextToken() === 88 /* EnumKeyword */;
20200                 case 89 /* ExportKeyword */:
20201                     nextToken();
20202                     if (token() === 84 /* DefaultKeyword */) {
20203                         return lookAhead(nextTokenCanFollowDefaultKeyword);
20204                     }
20205                     if (token() === 145 /* TypeKeyword */) {
20206                         return lookAhead(nextTokenCanFollowExportModifier);
20207                     }
20208                     return canFollowExportModifier();
20209                 case 84 /* DefaultKeyword */:
20210                     return nextTokenCanFollowDefaultKeyword();
20211                 case 120 /* StaticKeyword */:
20212                 case 131 /* GetKeyword */:
20213                 case 142 /* SetKeyword */:
20214                     nextToken();
20215                     return canFollowModifier();
20216                 default:
20217                     return nextTokenIsOnSameLineAndCanFollowModifier();
20218             }
20219         }
20220         function canFollowExportModifier() {
20221             return token() !== 41 /* AsteriskToken */
20222                 && token() !== 123 /* AsKeyword */
20223                 && token() !== 18 /* OpenBraceToken */
20224                 && canFollowModifier();
20225         }
20226         function nextTokenCanFollowExportModifier() {
20227             nextToken();
20228             return canFollowExportModifier();
20229         }
20230         function parseAnyContextualModifier() {
20231             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
20232         }
20233         function canFollowModifier() {
20234             return token() === 22 /* OpenBracketToken */
20235                 || token() === 18 /* OpenBraceToken */
20236                 || token() === 41 /* AsteriskToken */
20237                 || token() === 25 /* DotDotDotToken */
20238                 || isLiteralPropertyName();
20239         }
20240         function nextTokenCanFollowDefaultKeyword() {
20241             nextToken();
20242             return token() === 80 /* ClassKeyword */ || token() === 94 /* FunctionKeyword */ ||
20243                 token() === 114 /* InterfaceKeyword */ ||
20244                 (token() === 122 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
20245                 (token() === 126 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
20246         }
20247         // True if positioned at the start of a list element
20248         function isListElement(parsingContext, inErrorRecovery) {
20249             var node = currentNode(parsingContext);
20250             if (node) {
20251                 return true;
20252             }
20253             switch (parsingContext) {
20254                 case 0 /* SourceElements */:
20255                 case 1 /* BlockStatements */:
20256                 case 3 /* SwitchClauseStatements */:
20257                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
20258                     // The problem is that ';' can show up in far too many contexts, and if we see one
20259                     // and assume it's a statement, then we may bail out inappropriately from whatever
20260                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
20261                     // we really don't want to assume the class is over and we're on a statement in the
20262                     // outer module.  We just want to consume and move on.
20263                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
20264                 case 2 /* SwitchClauses */:
20265                     return token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20266                 case 4 /* TypeMembers */:
20267                     return lookAhead(isTypeMemberStart);
20268                 case 5 /* ClassMembers */:
20269                     // We allow semicolons as class elements (as specified by ES6) as long as we're
20270                     // not in error recovery.  If we're in error recovery, we don't want an errant
20271                     // semicolon to be treated as a class member (since they're almost always used
20272                     // for statements.
20273                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
20274                 case 6 /* EnumMembers */:
20275                     // Include open bracket computed properties. This technically also lets in indexers,
20276                     // which would be a candidate for improved error reporting.
20277                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
20278                 case 12 /* ObjectLiteralMembers */:
20279                     switch (token()) {
20280                         case 22 /* OpenBracketToken */:
20281                         case 41 /* AsteriskToken */:
20282                         case 25 /* DotDotDotToken */:
20283                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
20284                             return true;
20285                         default:
20286                             return isLiteralPropertyName();
20287                     }
20288                 case 18 /* RestProperties */:
20289                     return isLiteralPropertyName();
20290                 case 9 /* ObjectBindingElements */:
20291                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
20292                 case 7 /* HeritageClauseElement */:
20293                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
20294                     // That way we won't consume the body of a class in its heritage clause.
20295                     if (token() === 18 /* OpenBraceToken */) {
20296                         return lookAhead(isValidHeritageClauseObjectLiteral);
20297                     }
20298                     if (!inErrorRecovery) {
20299                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
20300                     }
20301                     else {
20302                         // If we're in error recovery we tighten up what we're willing to match.
20303                         // That way we don't treat something like "this" as a valid heritage clause
20304                         // element during recovery.
20305                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
20306                     }
20307                 case 8 /* VariableDeclarations */:
20308                     return isIdentifierOrPrivateIdentifierOrPattern();
20309                 case 10 /* ArrayBindingElements */:
20310                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPrivateIdentifierOrPattern();
20311                 case 19 /* TypeParameters */:
20312                     return isIdentifier();
20313                 case 15 /* ArrayLiteralMembers */:
20314                     switch (token()) {
20315                         case 27 /* CommaToken */:
20316                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
20317                             return true;
20318                     }
20319                 // falls through
20320                 case 11 /* ArgumentExpressions */:
20321                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
20322                 case 16 /* Parameters */:
20323                     return isStartOfParameter(/*isJSDocParameter*/ false);
20324                 case 17 /* JSDocParameters */:
20325                     return isStartOfParameter(/*isJSDocParameter*/ true);
20326                 case 20 /* TypeArguments */:
20327                 case 21 /* TupleElementTypes */:
20328                     return token() === 27 /* CommaToken */ || isStartOfType();
20329                 case 22 /* HeritageClauses */:
20330                     return isHeritageClause();
20331                 case 23 /* ImportOrExportSpecifiers */:
20332                     return ts.tokenIsIdentifierOrKeyword(token());
20333                 case 13 /* JsxAttributes */:
20334                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
20335                 case 14 /* JsxChildren */:
20336                     return true;
20337             }
20338             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
20339         }
20340         function isValidHeritageClauseObjectLiteral() {
20341             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
20342             if (nextToken() === 19 /* CloseBraceToken */) {
20343                 // if we see "extends {}" then only treat the {} as what we're extending (and not
20344                 // the class body) if we have:
20345                 //
20346                 //      extends {} {
20347                 //      extends {},
20348                 //      extends {} extends
20349                 //      extends {} implements
20350                 var next = nextToken();
20351                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 90 /* ExtendsKeyword */ || next === 113 /* ImplementsKeyword */;
20352             }
20353             return true;
20354         }
20355         function nextTokenIsIdentifier() {
20356             nextToken();
20357             return isIdentifier();
20358         }
20359         function nextTokenIsIdentifierOrKeyword() {
20360             nextToken();
20361             return ts.tokenIsIdentifierOrKeyword(token());
20362         }
20363         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
20364             nextToken();
20365             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
20366         }
20367         function isHeritageClauseExtendsOrImplementsKeyword() {
20368             if (token() === 113 /* ImplementsKeyword */ ||
20369                 token() === 90 /* ExtendsKeyword */) {
20370                 return lookAhead(nextTokenIsStartOfExpression);
20371             }
20372             return false;
20373         }
20374         function nextTokenIsStartOfExpression() {
20375             nextToken();
20376             return isStartOfExpression();
20377         }
20378         function nextTokenIsStartOfType() {
20379             nextToken();
20380             return isStartOfType();
20381         }
20382         // True if positioned at a list terminator
20383         function isListTerminator(kind) {
20384             if (token() === 1 /* EndOfFileToken */) {
20385                 // Being at the end of the file ends all lists.
20386                 return true;
20387             }
20388             switch (kind) {
20389                 case 1 /* BlockStatements */:
20390                 case 2 /* SwitchClauses */:
20391                 case 4 /* TypeMembers */:
20392                 case 5 /* ClassMembers */:
20393                 case 6 /* EnumMembers */:
20394                 case 12 /* ObjectLiteralMembers */:
20395                 case 9 /* ObjectBindingElements */:
20396                 case 23 /* ImportOrExportSpecifiers */:
20397                     return token() === 19 /* CloseBraceToken */;
20398                 case 3 /* SwitchClauseStatements */:
20399                     return token() === 19 /* CloseBraceToken */ || token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20400                 case 7 /* HeritageClauseElement */:
20401                     return token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20402                 case 8 /* VariableDeclarations */:
20403                     return isVariableDeclaratorListTerminator();
20404                 case 19 /* TypeParameters */:
20405                     // Tokens other than '>' are here for better error recovery
20406                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20407                 case 11 /* ArgumentExpressions */:
20408                     // Tokens other than ')' are here for better error recovery
20409                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
20410                 case 15 /* ArrayLiteralMembers */:
20411                 case 21 /* TupleElementTypes */:
20412                 case 10 /* ArrayBindingElements */:
20413                     return token() === 23 /* CloseBracketToken */;
20414                 case 17 /* JSDocParameters */:
20415                 case 16 /* Parameters */:
20416                 case 18 /* RestProperties */:
20417                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
20418                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
20419                 case 20 /* TypeArguments */:
20420                     // All other tokens should cause the type-argument to terminate except comma token
20421                     return token() !== 27 /* CommaToken */;
20422                 case 22 /* HeritageClauses */:
20423                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
20424                 case 13 /* JsxAttributes */:
20425                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
20426                 case 14 /* JsxChildren */:
20427                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
20428                 default:
20429                     return false;
20430             }
20431         }
20432         function isVariableDeclaratorListTerminator() {
20433             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
20434             // with parsing the list of variable declarators.
20435             if (canParseSemicolon()) {
20436                 return true;
20437             }
20438             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
20439             // are done if we see an 'in' keyword in front of us. Same with for-of
20440             if (isInOrOfKeyword(token())) {
20441                 return true;
20442             }
20443             // ERROR RECOVERY TWEAK:
20444             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
20445             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
20446             // another variable declaration.
20447             if (token() === 38 /* EqualsGreaterThanToken */) {
20448                 return true;
20449             }
20450             // Keep trying to parse out variable declarators.
20451             return false;
20452         }
20453         // True if positioned at element or terminator of the current list or any enclosing list
20454         function isInSomeParsingContext() {
20455             for (var kind = 0; kind < 24 /* Count */; kind++) {
20456                 if (parsingContext & (1 << kind)) {
20457                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
20458                         return true;
20459                     }
20460                 }
20461             }
20462             return false;
20463         }
20464         // Parses a list of elements
20465         function parseList(kind, parseElement) {
20466             var saveParsingContext = parsingContext;
20467             parsingContext |= 1 << kind;
20468             var list = [];
20469             var listPos = getNodePos();
20470             while (!isListTerminator(kind)) {
20471                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20472                     var element = parseListElement(kind, parseElement);
20473                     list.push(element);
20474                     continue;
20475                 }
20476                 if (abortParsingListOrMoveToNextToken(kind)) {
20477                     break;
20478                 }
20479             }
20480             parsingContext = saveParsingContext;
20481             return createNodeArray(list, listPos);
20482         }
20483         function parseListElement(parsingContext, parseElement) {
20484             var node = currentNode(parsingContext);
20485             if (node) {
20486                 return consumeNode(node);
20487             }
20488             return parseElement();
20489         }
20490         function currentNode(parsingContext) {
20491             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
20492             //
20493             // If there is an outstanding parse error that we've encountered, but not attached to
20494             // some node, then we cannot get a node from the old source tree.  This is because we
20495             // want to mark the next node we encounter as being unusable.
20496             //
20497             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
20498             // on it (or its leftmost child) as having the error.  For now though, being conservative
20499             // is nice and likely won't ever affect perf.
20500             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
20501                 return undefined;
20502             }
20503             var node = syntaxCursor.currentNode(scanner.getStartPos());
20504             // Can't reuse a missing node.
20505             // Can't reuse a node that intersected the change range.
20506             // Can't reuse a node that contains a parse error.  This is necessary so that we
20507             // produce the same set of errors again.
20508             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
20509                 return undefined;
20510             }
20511             // We can only reuse a node if it was parsed under the same strict mode that we're
20512             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
20513             // the user added 'using strict' at the top of the file, then we can't use that node
20514             // again as the presence of strict mode may cause us to parse the tokens in the file
20515             // differently.
20516             //
20517             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
20518             // are unaffected by strict mode.  It's just the parser will decide what to do with it
20519             // differently depending on what mode it is in.
20520             //
20521             // This also applies to all our other context flags as well.
20522             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
20523             if (nodeContextFlags !== contextFlags) {
20524                 return undefined;
20525             }
20526             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
20527             // in the current list parsing context that we're currently at.
20528             if (!canReuseNode(node, parsingContext)) {
20529                 return undefined;
20530             }
20531             if (node.jsDocCache) {
20532                 // jsDocCache may include tags from parent nodes, which might have been modified.
20533                 node.jsDocCache = undefined;
20534             }
20535             return node;
20536         }
20537         function consumeNode(node) {
20538             // Move the scanner so it is after the node we just consumed.
20539             scanner.setTextPos(node.end);
20540             nextToken();
20541             return node;
20542         }
20543         function isReusableParsingContext(parsingContext) {
20544             switch (parsingContext) {
20545                 case 5 /* ClassMembers */:
20546                 case 2 /* SwitchClauses */:
20547                 case 0 /* SourceElements */:
20548                 case 1 /* BlockStatements */:
20549                 case 3 /* SwitchClauseStatements */:
20550                 case 6 /* EnumMembers */:
20551                 case 4 /* TypeMembers */:
20552                 case 8 /* VariableDeclarations */:
20553                 case 17 /* JSDocParameters */:
20554                 case 16 /* Parameters */:
20555                     return true;
20556             }
20557             return false;
20558         }
20559         function canReuseNode(node, parsingContext) {
20560             switch (parsingContext) {
20561                 case 5 /* ClassMembers */:
20562                     return isReusableClassMember(node);
20563                 case 2 /* SwitchClauses */:
20564                     return isReusableSwitchClause(node);
20565                 case 0 /* SourceElements */:
20566                 case 1 /* BlockStatements */:
20567                 case 3 /* SwitchClauseStatements */:
20568                     return isReusableStatement(node);
20569                 case 6 /* EnumMembers */:
20570                     return isReusableEnumMember(node);
20571                 case 4 /* TypeMembers */:
20572                     return isReusableTypeMember(node);
20573                 case 8 /* VariableDeclarations */:
20574                     return isReusableVariableDeclaration(node);
20575                 case 17 /* JSDocParameters */:
20576                 case 16 /* Parameters */:
20577                     return isReusableParameter(node);
20578                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
20579                 // you can do so safely.  Danger areas involve nodes that may involve speculative
20580                 // parsing.  If speculative parsing is involved with the node, then the range the
20581                 // parser reached while looking ahead might be in the edited range (see the example
20582                 // in canReuseVariableDeclaratorNode for a good case of this).
20583                 // case ParsingContext.HeritageClauses:
20584                 // This would probably be safe to reuse.  There is no speculative parsing with
20585                 // heritage clauses.
20586                 // case ParsingContext.TypeParameters:
20587                 // This would probably be safe to reuse.  There is no speculative parsing with
20588                 // type parameters.  Note that that's because type *parameters* only occur in
20589                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
20590                 // *expression* contexts.
20591                 // case ParsingContext.TupleElementTypes:
20592                 // This would probably be safe to reuse.  There is no speculative parsing with
20593                 // tuple types.
20594                 // Technically, type argument list types are probably safe to reuse.  While
20595                 // speculative parsing is involved with them (since type argument lists are only
20596                 // produced from speculative parsing a < as a type argument list), we only have
20597                 // the types because speculative parsing succeeded.  Thus, the lookahead never
20598                 // went past the end of the list and rewound.
20599                 // case ParsingContext.TypeArguments:
20600                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
20601                 // need a large amount of lookahead, and we should not reuse them as they may
20602                 // have actually intersected the edit.
20603                 // case ParsingContext.ArgumentExpressions:
20604                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
20605                 // cases.  i.e. a property assignment may end with an expression, and thus might
20606                 // have lookahead far beyond it's old node.
20607                 // case ParsingContext.ObjectLiteralMembers:
20608                 // This is probably not safe to reuse.  There can be speculative parsing with
20609                 // type names in a heritage clause.  There can be generic names in the type
20610                 // name list, and there can be left hand side expressions (which can have type
20611                 // arguments.)
20612                 // case ParsingContext.HeritageClauseElement:
20613                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
20614                 // on any given element. Same for children.
20615                 // case ParsingContext.JsxAttributes:
20616                 // case ParsingContext.JsxChildren:
20617             }
20618             return false;
20619         }
20620         function isReusableClassMember(node) {
20621             if (node) {
20622                 switch (node.kind) {
20623                     case 162 /* Constructor */:
20624                     case 167 /* IndexSignature */:
20625                     case 163 /* GetAccessor */:
20626                     case 164 /* SetAccessor */:
20627                     case 159 /* PropertyDeclaration */:
20628                     case 222 /* SemicolonClassElement */:
20629                         return true;
20630                     case 161 /* MethodDeclaration */:
20631                         // Method declarations are not necessarily reusable.  An object-literal
20632                         // may have a method calls "constructor(...)" and we must reparse that
20633                         // into an actual .ConstructorDeclaration.
20634                         var methodDeclaration = node;
20635                         var nameIsConstructor = methodDeclaration.name.kind === 75 /* Identifier */ &&
20636                             methodDeclaration.name.originalKeywordKind === 129 /* ConstructorKeyword */;
20637                         return !nameIsConstructor;
20638                 }
20639             }
20640             return false;
20641         }
20642         function isReusableSwitchClause(node) {
20643             if (node) {
20644                 switch (node.kind) {
20645                     case 277 /* CaseClause */:
20646                     case 278 /* DefaultClause */:
20647                         return true;
20648                 }
20649             }
20650             return false;
20651         }
20652         function isReusableStatement(node) {
20653             if (node) {
20654                 switch (node.kind) {
20655                     case 244 /* FunctionDeclaration */:
20656                     case 225 /* VariableStatement */:
20657                     case 223 /* Block */:
20658                     case 227 /* IfStatement */:
20659                     case 226 /* ExpressionStatement */:
20660                     case 239 /* ThrowStatement */:
20661                     case 235 /* ReturnStatement */:
20662                     case 237 /* SwitchStatement */:
20663                     case 234 /* BreakStatement */:
20664                     case 233 /* ContinueStatement */:
20665                     case 231 /* ForInStatement */:
20666                     case 232 /* ForOfStatement */:
20667                     case 230 /* ForStatement */:
20668                     case 229 /* WhileStatement */:
20669                     case 236 /* WithStatement */:
20670                     case 224 /* EmptyStatement */:
20671                     case 240 /* TryStatement */:
20672                     case 238 /* LabeledStatement */:
20673                     case 228 /* DoStatement */:
20674                     case 241 /* DebuggerStatement */:
20675                     case 254 /* ImportDeclaration */:
20676                     case 253 /* ImportEqualsDeclaration */:
20677                     case 260 /* ExportDeclaration */:
20678                     case 259 /* ExportAssignment */:
20679                     case 249 /* ModuleDeclaration */:
20680                     case 245 /* ClassDeclaration */:
20681                     case 246 /* InterfaceDeclaration */:
20682                     case 248 /* EnumDeclaration */:
20683                     case 247 /* TypeAliasDeclaration */:
20684                         return true;
20685                 }
20686             }
20687             return false;
20688         }
20689         function isReusableEnumMember(node) {
20690             return node.kind === 284 /* EnumMember */;
20691         }
20692         function isReusableTypeMember(node) {
20693             if (node) {
20694                 switch (node.kind) {
20695                     case 166 /* ConstructSignature */:
20696                     case 160 /* MethodSignature */:
20697                     case 167 /* IndexSignature */:
20698                     case 158 /* PropertySignature */:
20699                     case 165 /* CallSignature */:
20700                         return true;
20701                 }
20702             }
20703             return false;
20704         }
20705         function isReusableVariableDeclaration(node) {
20706             if (node.kind !== 242 /* VariableDeclaration */) {
20707                 return false;
20708             }
20709             // Very subtle incremental parsing bug.  Consider the following code:
20710             //
20711             //      let v = new List < A, B
20712             //
20713             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
20714             // on one side and "B" on the other. If you then change that to:
20715             //
20716             //      let v = new List < A, B >()
20717             //
20718             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
20719             // start reparsing at "B" and we completely fail to handle this properly.
20720             //
20721             // In order to prevent this, we do not allow a variable declarator to be reused if it
20722             // has an initializer.
20723             var variableDeclarator = node;
20724             return variableDeclarator.initializer === undefined;
20725         }
20726         function isReusableParameter(node) {
20727             if (node.kind !== 156 /* Parameter */) {
20728                 return false;
20729             }
20730             // See the comment in isReusableVariableDeclaration for why we do this.
20731             var parameter = node;
20732             return parameter.initializer === undefined;
20733         }
20734         // Returns true if we should abort parsing.
20735         function abortParsingListOrMoveToNextToken(kind) {
20736             parseErrorAtCurrentToken(parsingContextErrors(kind));
20737             if (isInSomeParsingContext()) {
20738                 return true;
20739             }
20740             nextToken();
20741             return false;
20742         }
20743         function parsingContextErrors(context) {
20744             switch (context) {
20745                 case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
20746                 case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
20747                 case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
20748                 case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
20749                 case 18 /* RestProperties */: // fallthrough
20750                 case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
20751                 case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
20752                 case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
20753                 case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
20754                 case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
20755                 case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
20756                 case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
20757                 case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
20758                 case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
20759                 case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
20760                 case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
20761                 case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
20762                 case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
20763                 case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
20764                 case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
20765                 case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
20766                 case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
20767                 case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
20768                 case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
20769                 default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
20770             }
20771         }
20772         // Parses a comma-delimited list of elements
20773         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
20774             var saveParsingContext = parsingContext;
20775             parsingContext |= 1 << kind;
20776             var list = [];
20777             var listPos = getNodePos();
20778             var commaStart = -1; // Meaning the previous token was not a comma
20779             while (true) {
20780                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20781                     var startPos = scanner.getStartPos();
20782                     list.push(parseListElement(kind, parseElement));
20783                     commaStart = scanner.getTokenPos();
20784                     if (parseOptional(27 /* CommaToken */)) {
20785                         // No need to check for a zero length node since we know we parsed a comma
20786                         continue;
20787                     }
20788                     commaStart = -1; // Back to the state where the last token was not a comma
20789                     if (isListTerminator(kind)) {
20790                         break;
20791                     }
20792                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
20793                     // out a comma so we give a good error message.
20794                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
20795                     // If the token was a semicolon, and the caller allows that, then skip it and
20796                     // continue.  This ensures we get back on track and don't result in tons of
20797                     // parse errors.  For example, this can happen when people do things like use
20798                     // a semicolon to delimit object literal members.   Note: we'll have already
20799                     // reported an error when we called parseExpected above.
20800                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
20801                         nextToken();
20802                     }
20803                     if (startPos === scanner.getStartPos()) {
20804                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
20805                         // Consume a token to advance the parser in some way and avoid an infinite loop
20806                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
20807                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
20808                         nextToken();
20809                     }
20810                     continue;
20811                 }
20812                 if (isListTerminator(kind)) {
20813                     break;
20814                 }
20815                 if (abortParsingListOrMoveToNextToken(kind)) {
20816                     break;
20817                 }
20818             }
20819             parsingContext = saveParsingContext;
20820             var result = createNodeArray(list, listPos);
20821             // Recording the trailing comma is deliberately done after the previous
20822             // loop, and not just if we see a list terminator. This is because the list
20823             // may have ended incorrectly, but it is still important to know if there
20824             // was a trailing comma.
20825             // Check if the last token was a comma.
20826             if (commaStart >= 0) {
20827                 // Always preserve a trailing comma by marking it on the NodeArray
20828                 result.hasTrailingComma = true;
20829             }
20830             return result;
20831         }
20832         function getExpectedCommaDiagnostic(kind) {
20833             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
20834         }
20835         function createMissingList() {
20836             var list = createNodeArray([], getNodePos());
20837             list.isMissingList = true;
20838             return list;
20839         }
20840         function isMissingList(arr) {
20841             return !!arr.isMissingList;
20842         }
20843         function parseBracketedList(kind, parseElement, open, close) {
20844             if (parseExpected(open)) {
20845                 var result = parseDelimitedList(kind, parseElement);
20846                 parseExpected(close);
20847                 return result;
20848             }
20849             return createMissingList();
20850         }
20851         function parseEntityName(allowReservedWords, diagnosticMessage) {
20852             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
20853             var dotPos = scanner.getStartPos();
20854             while (parseOptional(24 /* DotToken */)) {
20855                 if (token() === 29 /* LessThanToken */) {
20856                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
20857                     entity.jsdocDotPos = dotPos;
20858                     break;
20859                 }
20860                 dotPos = scanner.getStartPos();
20861                 entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false));
20862             }
20863             return entity;
20864         }
20865         function createQualifiedName(entity, name) {
20866             var node = createNode(153 /* QualifiedName */, entity.pos);
20867             node.left = entity;
20868             node.right = name;
20869             return finishNode(node);
20870         }
20871         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
20872             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
20873             // However, often we'll encounter this in error situations when the identifier or keyword
20874             // is actually starting another valid construct.
20875             //
20876             // So, we check for the following specific case:
20877             //
20878             //      name.
20879             //      identifierOrKeyword identifierNameOrKeyword
20880             //
20881             // Note: the newlines are important here.  For example, if that above code
20882             // were rewritten into:
20883             //
20884             //      name.identifierOrKeyword
20885             //      identifierNameOrKeyword
20886             //
20887             // Then we would consider it valid.  That's because ASI would take effect and
20888             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
20889             // In the first case though, ASI will not take effect because there is not a
20890             // line terminator after the identifier or keyword.
20891             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
20892                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
20893                 if (matchesPattern) {
20894                     // Report that we need an identifier.  However, report it right after the dot,
20895                     // and not on the next token.  This is because the next token might actually
20896                     // be an identifier and the error would be quite confusing.
20897                     return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20898                 }
20899             }
20900             if (token() === 76 /* PrivateIdentifier */) {
20901                 var node = parsePrivateIdentifier();
20902                 return allowPrivateIdentifiers ? node : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20903             }
20904             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
20905         }
20906         function parseTemplateExpression(isTaggedTemplate) {
20907             var template = createNode(211 /* TemplateExpression */);
20908             template.head = parseTemplateHead(isTaggedTemplate);
20909             ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20910             var list = [];
20911             var listPos = getNodePos();
20912             do {
20913                 list.push(parseTemplateSpan(isTaggedTemplate));
20914             } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
20915             template.templateSpans = createNodeArray(list, listPos);
20916             return finishNode(template);
20917         }
20918         function parseTemplateSpan(isTaggedTemplate) {
20919             var span = createNode(221 /* TemplateSpan */);
20920             span.expression = allowInAnd(parseExpression);
20921             var literal;
20922             if (token() === 19 /* CloseBraceToken */) {
20923                 reScanTemplateToken(isTaggedTemplate);
20924                 literal = parseTemplateMiddleOrTemplateTail();
20925             }
20926             else {
20927                 literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
20928             }
20929             span.literal = literal;
20930             return finishNode(span);
20931         }
20932         function parseLiteralNode() {
20933             return parseLiteralLikeNode(token());
20934         }
20935         function parseTemplateHead(isTaggedTemplate) {
20936             if (isTaggedTemplate) {
20937                 reScanTemplateHeadOrNoSubstitutionTemplate();
20938             }
20939             var fragment = parseLiteralLikeNode(token());
20940             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20941             return fragment;
20942         }
20943         function parseTemplateMiddleOrTemplateTail() {
20944             var fragment = parseLiteralLikeNode(token());
20945             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
20946             return fragment;
20947         }
20948         function parseLiteralLikeNode(kind) {
20949             var node = createNode(kind);
20950             node.text = scanner.getTokenValue();
20951             switch (kind) {
20952                 case 14 /* NoSubstitutionTemplateLiteral */:
20953                 case 15 /* TemplateHead */:
20954                 case 16 /* TemplateMiddle */:
20955                 case 17 /* TemplateTail */:
20956                     var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
20957                     var tokenText = scanner.getTokenText();
20958                     node.rawText = tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
20959                     break;
20960             }
20961             if (scanner.hasExtendedUnicodeEscape()) {
20962                 node.hasExtendedUnicodeEscape = true;
20963             }
20964             if (scanner.isUnterminated()) {
20965                 node.isUnterminated = true;
20966             }
20967             // Octal literals are not allowed in strict mode or ES5
20968             // Note that theoretically the following condition would hold true literals like 009,
20969             // which is not octal.But because of how the scanner separates the tokens, we would
20970             // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
20971             // We also do not need to check for negatives because any prefix operator would be part of a
20972             // parent unary expression.
20973             if (node.kind === 8 /* NumericLiteral */) {
20974                 node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
20975             }
20976             if (ts.isTemplateLiteralKind(node.kind)) {
20977                 node.templateFlags = scanner.getTokenFlags() & 2048 /* ContainsInvalidEscape */;
20978             }
20979             nextToken();
20980             finishNode(node);
20981             return node;
20982         }
20983         // TYPES
20984         function parseTypeReference() {
20985             var node = createNode(169 /* TypeReference */);
20986             node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
20987             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
20988                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
20989             }
20990             return finishNode(node);
20991         }
20992         // If true, we should abort parsing an error function.
20993         function typeHasArrowFunctionBlockingParseError(node) {
20994             switch (node.kind) {
20995                 case 169 /* TypeReference */:
20996                     return ts.nodeIsMissing(node.typeName);
20997                 case 170 /* FunctionType */:
20998                 case 171 /* ConstructorType */: {
20999                     var _a = node, parameters = _a.parameters, type = _a.type;
21000                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
21001                 }
21002                 case 182 /* ParenthesizedType */:
21003                     return typeHasArrowFunctionBlockingParseError(node.type);
21004                 default:
21005                     return false;
21006             }
21007         }
21008         function parseThisTypePredicate(lhs) {
21009             nextToken();
21010             var node = createNode(168 /* TypePredicate */, lhs.pos);
21011             node.parameterName = lhs;
21012             node.type = parseType();
21013             return finishNode(node);
21014         }
21015         function parseThisTypeNode() {
21016             var node = createNode(183 /* ThisType */);
21017             nextToken();
21018             return finishNode(node);
21019         }
21020         function parseJSDocAllType(postFixEquals) {
21021             var result = createNode(295 /* JSDocAllType */);
21022             if (postFixEquals) {
21023                 return createPostfixType(299 /* JSDocOptionalType */, result);
21024             }
21025             else {
21026                 nextToken();
21027             }
21028             return finishNode(result);
21029         }
21030         function parseJSDocNonNullableType() {
21031             var result = createNode(298 /* JSDocNonNullableType */);
21032             nextToken();
21033             result.type = parseNonArrayType();
21034             return finishNode(result);
21035         }
21036         function parseJSDocUnknownOrNullableType() {
21037             var pos = scanner.getStartPos();
21038             // skip the ?
21039             nextToken();
21040             // Need to lookahead to decide if this is a nullable or unknown type.
21041             // Here are cases where we'll pick the unknown type:
21042             //
21043             //      Foo(?,
21044             //      { a: ? }
21045             //      Foo(?)
21046             //      Foo<?>
21047             //      Foo(?=
21048             //      (?|
21049             if (token() === 27 /* CommaToken */ ||
21050                 token() === 19 /* CloseBraceToken */ ||
21051                 token() === 21 /* CloseParenToken */ ||
21052                 token() === 31 /* GreaterThanToken */ ||
21053                 token() === 62 /* EqualsToken */ ||
21054                 token() === 51 /* BarToken */) {
21055                 var result = createNode(296 /* JSDocUnknownType */, pos);
21056                 return finishNode(result);
21057             }
21058             else {
21059                 var result = createNode(297 /* JSDocNullableType */, pos);
21060                 result.type = parseType();
21061                 return finishNode(result);
21062             }
21063         }
21064         function parseJSDocFunctionType() {
21065             if (lookAhead(nextTokenIsOpenParen)) {
21066                 var result = createNodeWithJSDoc(300 /* JSDocFunctionType */);
21067                 nextToken();
21068                 fillSignature(58 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
21069                 return finishNode(result);
21070             }
21071             var node = createNode(169 /* TypeReference */);
21072             node.typeName = parseIdentifierName();
21073             return finishNode(node);
21074         }
21075         function parseJSDocParameter() {
21076             var parameter = createNode(156 /* Parameter */);
21077             if (token() === 104 /* ThisKeyword */ || token() === 99 /* NewKeyword */) {
21078                 parameter.name = parseIdentifierName();
21079                 parseExpected(58 /* ColonToken */);
21080             }
21081             parameter.type = parseJSDocType();
21082             return finishNode(parameter);
21083         }
21084         function parseJSDocType() {
21085             scanner.setInJSDocType(true);
21086             var moduleSpecifier = parseOptionalToken(135 /* ModuleKeyword */);
21087             if (moduleSpecifier) {
21088                 var moduleTag = createNode(302 /* JSDocNamepathType */, moduleSpecifier.pos);
21089                 terminate: while (true) {
21090                     switch (token()) {
21091                         case 19 /* CloseBraceToken */:
21092                         case 1 /* EndOfFileToken */:
21093                         case 27 /* CommaToken */:
21094                         case 5 /* WhitespaceTrivia */:
21095                             break terminate;
21096                         default:
21097                             nextTokenJSDoc();
21098                     }
21099                 }
21100                 scanner.setInJSDocType(false);
21101                 return finishNode(moduleTag);
21102             }
21103             var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
21104             var type = parseTypeOrTypePredicate();
21105             scanner.setInJSDocType(false);
21106             if (dotdotdot) {
21107                 var variadic = createNode(301 /* JSDocVariadicType */, dotdotdot.pos);
21108                 variadic.type = type;
21109                 type = finishNode(variadic);
21110             }
21111             if (token() === 62 /* EqualsToken */) {
21112                 return createPostfixType(299 /* JSDocOptionalType */, type);
21113             }
21114             return type;
21115         }
21116         function parseTypeQuery() {
21117             var node = createNode(172 /* TypeQuery */);
21118             parseExpected(108 /* TypeOfKeyword */);
21119             node.exprName = parseEntityName(/*allowReservedWords*/ true);
21120             return finishNode(node);
21121         }
21122         function parseTypeParameter() {
21123             var node = createNode(155 /* TypeParameter */);
21124             node.name = parseIdentifier();
21125             if (parseOptional(90 /* ExtendsKeyword */)) {
21126                 // It's not uncommon for people to write improper constraints to a generic.  If the
21127                 // user writes a constraint that is an expression and not an actual type, then parse
21128                 // it out as an expression (so we can recover well), but report that a type is needed
21129                 // instead.
21130                 if (isStartOfType() || !isStartOfExpression()) {
21131                     node.constraint = parseType();
21132                 }
21133                 else {
21134                     // It was not a type, and it looked like an expression.  Parse out an expression
21135                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
21136                     // and not parseExpression here.  If the user has:
21137                     //
21138                     //      <T extends "">
21139                     //
21140                     // We do *not* want to consume the `>` as we're consuming the expression for "".
21141                     node.expression = parseUnaryExpressionOrHigher();
21142                 }
21143             }
21144             if (parseOptional(62 /* EqualsToken */)) {
21145                 node.default = parseType();
21146             }
21147             return finishNode(node);
21148         }
21149         function parseTypeParameters() {
21150             if (token() === 29 /* LessThanToken */) {
21151                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21152             }
21153         }
21154         function parseParameterType() {
21155             if (parseOptional(58 /* ColonToken */)) {
21156                 return parseType();
21157             }
21158             return undefined;
21159         }
21160         function isStartOfParameter(isJSDocParameter) {
21161             return token() === 25 /* DotDotDotToken */ ||
21162                 isIdentifierOrPrivateIdentifierOrPattern() ||
21163                 ts.isModifierKind(token()) ||
21164                 token() === 59 /* AtToken */ ||
21165                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
21166         }
21167         function parseParameter() {
21168             var node = createNodeWithJSDoc(156 /* Parameter */);
21169             if (token() === 104 /* ThisKeyword */) {
21170                 node.name = createIdentifier(/*isIdentifier*/ true);
21171                 node.type = parseParameterType();
21172                 return finishNode(node);
21173             }
21174             node.decorators = parseDecorators();
21175             node.modifiers = parseModifiers();
21176             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
21177             // FormalParameter [Yield,Await]:
21178             //      BindingElement[?Yield,?Await]
21179             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
21180             if (ts.getFullWidth(node.name) === 0 && !node.modifiers && ts.isModifierKind(token())) {
21181                 // in cases like
21182                 // 'use strict'
21183                 // function foo(static)
21184                 // isParameter('static') === true, because of isModifier('static')
21185                 // however 'static' is not a legal identifier in a strict mode.
21186                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
21187                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
21188                 // to avoid this we'll advance cursor to the next token.
21189                 nextToken();
21190             }
21191             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21192             node.type = parseParameterType();
21193             node.initializer = parseInitializer();
21194             return finishNode(node);
21195         }
21196         /**
21197          * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
21198          * @returns If return type parsing succeeds
21199          */
21200         function fillSignature(returnToken, flags, signature) {
21201             if (!(flags & 32 /* JSDoc */)) {
21202                 signature.typeParameters = parseTypeParameters();
21203             }
21204             var parametersParsedSuccessfully = parseParameterList(signature, flags);
21205             if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
21206                 signature.type = parseTypeOrTypePredicate();
21207                 if (typeHasArrowFunctionBlockingParseError(signature.type))
21208                     return false;
21209             }
21210             return parametersParsedSuccessfully;
21211         }
21212         function shouldParseReturnType(returnToken, isType) {
21213             if (returnToken === 38 /* EqualsGreaterThanToken */) {
21214                 parseExpected(returnToken);
21215                 return true;
21216             }
21217             else if (parseOptional(58 /* ColonToken */)) {
21218                 return true;
21219             }
21220             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
21221                 // This is easy to get backward, especially in type contexts, so parse the type anyway
21222                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
21223                 nextToken();
21224                 return true;
21225             }
21226             return false;
21227         }
21228         // Returns true on success.
21229         function parseParameterList(signature, flags) {
21230             // FormalParameters [Yield,Await]: (modified)
21231             //      [empty]
21232             //      FormalParameterList[?Yield,Await]
21233             //
21234             // FormalParameter[Yield,Await]: (modified)
21235             //      BindingElement[?Yield,Await]
21236             //
21237             // BindingElement [Yield,Await]: (modified)
21238             //      SingleNameBinding[?Yield,?Await]
21239             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21240             //
21241             // SingleNameBinding [Yield,Await]:
21242             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21243             if (!parseExpected(20 /* OpenParenToken */)) {
21244                 signature.parameters = createMissingList();
21245                 return false;
21246             }
21247             var savedYieldContext = inYieldContext();
21248             var savedAwaitContext = inAwaitContext();
21249             setYieldContext(!!(flags & 1 /* Yield */));
21250             setAwaitContext(!!(flags & 2 /* Await */));
21251             signature.parameters = flags & 32 /* JSDoc */ ?
21252                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
21253                 parseDelimitedList(16 /* Parameters */, parseParameter);
21254             setYieldContext(savedYieldContext);
21255             setAwaitContext(savedAwaitContext);
21256             return parseExpected(21 /* CloseParenToken */);
21257         }
21258         function parseTypeMemberSemicolon() {
21259             // We allow type members to be separated by commas or (possibly ASI) semicolons.
21260             // First check if it was a comma.  If so, we're done with the member.
21261             if (parseOptional(27 /* CommaToken */)) {
21262                 return;
21263             }
21264             // Didn't have a comma.  We must have a (possible ASI) semicolon.
21265             parseSemicolon();
21266         }
21267         function parseSignatureMember(kind) {
21268             var node = createNodeWithJSDoc(kind);
21269             if (kind === 166 /* ConstructSignature */) {
21270                 parseExpected(99 /* NewKeyword */);
21271             }
21272             fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21273             parseTypeMemberSemicolon();
21274             return finishNode(node);
21275         }
21276         function isIndexSignature() {
21277             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
21278         }
21279         function isUnambiguouslyIndexSignature() {
21280             // The only allowed sequence is:
21281             //
21282             //   [id:
21283             //
21284             // However, for error recovery, we also check the following cases:
21285             //
21286             //   [...
21287             //   [id,
21288             //   [id?,
21289             //   [id?:
21290             //   [id?]
21291             //   [public id
21292             //   [private id
21293             //   [protected id
21294             //   []
21295             //
21296             nextToken();
21297             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
21298                 return true;
21299             }
21300             if (ts.isModifierKind(token())) {
21301                 nextToken();
21302                 if (isIdentifier()) {
21303                     return true;
21304                 }
21305             }
21306             else if (!isIdentifier()) {
21307                 return false;
21308             }
21309             else {
21310                 // Skip the identifier
21311                 nextToken();
21312             }
21313             // A colon signifies a well formed indexer
21314             // A comma should be a badly formed indexer because comma expressions are not allowed
21315             // in computed properties.
21316             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
21317                 return true;
21318             }
21319             // Question mark could be an indexer with an optional property,
21320             // or it could be a conditional expression in a computed property.
21321             if (token() !== 57 /* QuestionToken */) {
21322                 return false;
21323             }
21324             // If any of the following tokens are after the question mark, it cannot
21325             // be a conditional expression, so treat it as an indexer.
21326             nextToken();
21327             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
21328         }
21329         function parseIndexSignatureDeclaration(node) {
21330             node.kind = 167 /* IndexSignature */;
21331             node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21332             node.type = parseTypeAnnotation();
21333             parseTypeMemberSemicolon();
21334             return finishNode(node);
21335         }
21336         function parsePropertyOrMethodSignature(node) {
21337             node.name = parsePropertyName();
21338             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21339             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21340                 node.kind = 160 /* MethodSignature */;
21341                 // Method signatures don't exist in expression contexts.  So they have neither
21342                 // [Yield] nor [Await]
21343                 fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21344             }
21345             else {
21346                 node.kind = 158 /* PropertySignature */;
21347                 node.type = parseTypeAnnotation();
21348                 if (token() === 62 /* EqualsToken */) {
21349                     // Although type literal properties cannot not have initializers, we attempt
21350                     // to parse an initializer so we can report in the checker that an interface
21351                     // property or type literal property cannot have an initializer.
21352                     node.initializer = parseInitializer();
21353                 }
21354             }
21355             parseTypeMemberSemicolon();
21356             return finishNode(node);
21357         }
21358         function isTypeMemberStart() {
21359             // Return true if we have the start of a signature member
21360             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21361                 return true;
21362             }
21363             var idToken = false;
21364             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
21365             while (ts.isModifierKind(token())) {
21366                 idToken = true;
21367                 nextToken();
21368             }
21369             // Index signatures and computed property names are type members
21370             if (token() === 22 /* OpenBracketToken */) {
21371                 return true;
21372             }
21373             // Try to get the first property-like token following all modifiers
21374             if (isLiteralPropertyName()) {
21375                 idToken = true;
21376                 nextToken();
21377             }
21378             // If we were able to get any potential identifier, check that it is
21379             // the start of a member declaration
21380             if (idToken) {
21381                 return token() === 20 /* OpenParenToken */ ||
21382                     token() === 29 /* LessThanToken */ ||
21383                     token() === 57 /* QuestionToken */ ||
21384                     token() === 58 /* ColonToken */ ||
21385                     token() === 27 /* CommaToken */ ||
21386                     canParseSemicolon();
21387             }
21388             return false;
21389         }
21390         function parseTypeMember() {
21391             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21392                 return parseSignatureMember(165 /* CallSignature */);
21393             }
21394             if (token() === 99 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
21395                 return parseSignatureMember(166 /* ConstructSignature */);
21396             }
21397             var node = createNodeWithJSDoc(0 /* Unknown */);
21398             node.modifiers = parseModifiers();
21399             if (isIndexSignature()) {
21400                 return parseIndexSignatureDeclaration(node);
21401             }
21402             return parsePropertyOrMethodSignature(node);
21403         }
21404         function nextTokenIsOpenParenOrLessThan() {
21405             nextToken();
21406             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
21407         }
21408         function nextTokenIsDot() {
21409             return nextToken() === 24 /* DotToken */;
21410         }
21411         function nextTokenIsOpenParenOrLessThanOrDot() {
21412             switch (nextToken()) {
21413                 case 20 /* OpenParenToken */:
21414                 case 29 /* LessThanToken */:
21415                 case 24 /* DotToken */:
21416                     return true;
21417             }
21418             return false;
21419         }
21420         function parseTypeLiteral() {
21421             var node = createNode(173 /* TypeLiteral */);
21422             node.members = parseObjectTypeMembers();
21423             return finishNode(node);
21424         }
21425         function parseObjectTypeMembers() {
21426             var members;
21427             if (parseExpected(18 /* OpenBraceToken */)) {
21428                 members = parseList(4 /* TypeMembers */, parseTypeMember);
21429                 parseExpected(19 /* CloseBraceToken */);
21430             }
21431             else {
21432                 members = createMissingList();
21433             }
21434             return members;
21435         }
21436         function isStartOfMappedType() {
21437             nextToken();
21438             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21439                 return nextToken() === 138 /* ReadonlyKeyword */;
21440             }
21441             if (token() === 138 /* ReadonlyKeyword */) {
21442                 nextToken();
21443             }
21444             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 97 /* InKeyword */;
21445         }
21446         function parseMappedTypeParameter() {
21447             var node = createNode(155 /* TypeParameter */);
21448             node.name = parseIdentifier();
21449             parseExpected(97 /* InKeyword */);
21450             node.constraint = parseType();
21451             return finishNode(node);
21452         }
21453         function parseMappedType() {
21454             var node = createNode(186 /* MappedType */);
21455             parseExpected(18 /* OpenBraceToken */);
21456             if (token() === 138 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21457                 node.readonlyToken = parseTokenNode();
21458                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
21459                     parseExpectedToken(138 /* ReadonlyKeyword */);
21460                 }
21461             }
21462             parseExpected(22 /* OpenBracketToken */);
21463             node.typeParameter = parseMappedTypeParameter();
21464             parseExpected(23 /* CloseBracketToken */);
21465             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21466                 node.questionToken = parseTokenNode();
21467                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
21468                     parseExpectedToken(57 /* QuestionToken */);
21469                 }
21470             }
21471             node.type = parseTypeAnnotation();
21472             parseSemicolon();
21473             parseExpected(19 /* CloseBraceToken */);
21474             return finishNode(node);
21475         }
21476         function parseTupleElementType() {
21477             var pos = getNodePos();
21478             if (parseOptional(25 /* DotDotDotToken */)) {
21479                 var node = createNode(177 /* RestType */, pos);
21480                 node.type = parseType();
21481                 return finishNode(node);
21482             }
21483             var type = parseType();
21484             if (!(contextFlags & 4194304 /* JSDoc */) && type.kind === 297 /* JSDocNullableType */ && type.pos === type.type.pos) {
21485                 type.kind = 176 /* OptionalType */;
21486             }
21487             return type;
21488         }
21489         function parseTupleType() {
21490             var node = createNode(175 /* TupleType */);
21491             node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21492             return finishNode(node);
21493         }
21494         function parseParenthesizedType() {
21495             var node = createNode(182 /* ParenthesizedType */);
21496             parseExpected(20 /* OpenParenToken */);
21497             node.type = parseType();
21498             parseExpected(21 /* CloseParenToken */);
21499             return finishNode(node);
21500         }
21501         function parseFunctionOrConstructorType() {
21502             var pos = getNodePos();
21503             var kind = parseOptional(99 /* NewKeyword */) ? 171 /* ConstructorType */ : 170 /* FunctionType */;
21504             var node = createNodeWithJSDoc(kind, pos);
21505             fillSignature(38 /* EqualsGreaterThanToken */, 4 /* Type */, node);
21506             return finishNode(node);
21507         }
21508         function parseKeywordAndNoDot() {
21509             var node = parseTokenNode();
21510             return token() === 24 /* DotToken */ ? undefined : node;
21511         }
21512         function parseLiteralTypeNode(negative) {
21513             var node = createNode(187 /* LiteralType */);
21514             var unaryMinusExpression;
21515             if (negative) {
21516                 unaryMinusExpression = createNode(207 /* PrefixUnaryExpression */);
21517                 unaryMinusExpression.operator = 40 /* MinusToken */;
21518                 nextToken();
21519             }
21520             var expression = token() === 106 /* TrueKeyword */ || token() === 91 /* FalseKeyword */
21521                 ? parseTokenNode()
21522                 : parseLiteralLikeNode(token());
21523             if (negative) {
21524                 unaryMinusExpression.operand = expression;
21525                 finishNode(unaryMinusExpression);
21526                 expression = unaryMinusExpression;
21527             }
21528             node.literal = expression;
21529             return finishNode(node);
21530         }
21531         function isStartOfTypeOfImportType() {
21532             nextToken();
21533             return token() === 96 /* ImportKeyword */;
21534         }
21535         function parseImportType() {
21536             sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
21537             var node = createNode(188 /* ImportType */);
21538             if (parseOptional(108 /* TypeOfKeyword */)) {
21539                 node.isTypeOf = true;
21540             }
21541             parseExpected(96 /* ImportKeyword */);
21542             parseExpected(20 /* OpenParenToken */);
21543             node.argument = parseType();
21544             parseExpected(21 /* CloseParenToken */);
21545             if (parseOptional(24 /* DotToken */)) {
21546                 node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
21547             }
21548             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
21549                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21550             }
21551             return finishNode(node);
21552         }
21553         function nextTokenIsNumericOrBigIntLiteral() {
21554             nextToken();
21555             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
21556         }
21557         function parseNonArrayType() {
21558             switch (token()) {
21559                 case 125 /* AnyKeyword */:
21560                 case 148 /* UnknownKeyword */:
21561                 case 143 /* StringKeyword */:
21562                 case 140 /* NumberKeyword */:
21563                 case 151 /* BigIntKeyword */:
21564                 case 144 /* SymbolKeyword */:
21565                 case 128 /* BooleanKeyword */:
21566                 case 146 /* UndefinedKeyword */:
21567                 case 137 /* NeverKeyword */:
21568                 case 141 /* ObjectKeyword */:
21569                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
21570                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
21571                 case 41 /* AsteriskToken */:
21572                     return parseJSDocAllType(/*postfixEquals*/ false);
21573                 case 65 /* AsteriskEqualsToken */:
21574                     return parseJSDocAllType(/*postfixEquals*/ true);
21575                 case 60 /* QuestionQuestionToken */:
21576                     // If there is '??', consider that is prefix '?' in JSDoc type.
21577                     scanner.reScanQuestionToken();
21578                 // falls through
21579                 case 57 /* QuestionToken */:
21580                     return parseJSDocUnknownOrNullableType();
21581                 case 94 /* FunctionKeyword */:
21582                     return parseJSDocFunctionType();
21583                 case 53 /* ExclamationToken */:
21584                     return parseJSDocNonNullableType();
21585                 case 14 /* NoSubstitutionTemplateLiteral */:
21586                 case 10 /* StringLiteral */:
21587                 case 8 /* NumericLiteral */:
21588                 case 9 /* BigIntLiteral */:
21589                 case 106 /* TrueKeyword */:
21590                 case 91 /* FalseKeyword */:
21591                     return parseLiteralTypeNode();
21592                 case 40 /* MinusToken */:
21593                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
21594                 case 110 /* VoidKeyword */:
21595                 case 100 /* NullKeyword */:
21596                     return parseTokenNode();
21597                 case 104 /* ThisKeyword */: {
21598                     var thisKeyword = parseThisTypeNode();
21599                     if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21600                         return parseThisTypePredicate(thisKeyword);
21601                     }
21602                     else {
21603                         return thisKeyword;
21604                     }
21605                 }
21606                 case 108 /* TypeOfKeyword */:
21607                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
21608                 case 18 /* OpenBraceToken */:
21609                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
21610                 case 22 /* OpenBracketToken */:
21611                     return parseTupleType();
21612                 case 20 /* OpenParenToken */:
21613                     return parseParenthesizedType();
21614                 case 96 /* ImportKeyword */:
21615                     return parseImportType();
21616                 case 124 /* AssertsKeyword */:
21617                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
21618                 default:
21619                     return parseTypeReference();
21620             }
21621         }
21622         function isStartOfType(inStartOfParameter) {
21623             switch (token()) {
21624                 case 125 /* AnyKeyword */:
21625                 case 148 /* UnknownKeyword */:
21626                 case 143 /* StringKeyword */:
21627                 case 140 /* NumberKeyword */:
21628                 case 151 /* BigIntKeyword */:
21629                 case 128 /* BooleanKeyword */:
21630                 case 138 /* ReadonlyKeyword */:
21631                 case 144 /* SymbolKeyword */:
21632                 case 147 /* UniqueKeyword */:
21633                 case 110 /* VoidKeyword */:
21634                 case 146 /* UndefinedKeyword */:
21635                 case 100 /* NullKeyword */:
21636                 case 104 /* ThisKeyword */:
21637                 case 108 /* TypeOfKeyword */:
21638                 case 137 /* NeverKeyword */:
21639                 case 18 /* OpenBraceToken */:
21640                 case 22 /* OpenBracketToken */:
21641                 case 29 /* LessThanToken */:
21642                 case 51 /* BarToken */:
21643                 case 50 /* AmpersandToken */:
21644                 case 99 /* NewKeyword */:
21645                 case 10 /* StringLiteral */:
21646                 case 8 /* NumericLiteral */:
21647                 case 9 /* BigIntLiteral */:
21648                 case 106 /* TrueKeyword */:
21649                 case 91 /* FalseKeyword */:
21650                 case 141 /* ObjectKeyword */:
21651                 case 41 /* AsteriskToken */:
21652                 case 57 /* QuestionToken */:
21653                 case 53 /* ExclamationToken */:
21654                 case 25 /* DotDotDotToken */:
21655                 case 132 /* InferKeyword */:
21656                 case 96 /* ImportKeyword */:
21657                 case 124 /* AssertsKeyword */:
21658                     return true;
21659                 case 94 /* FunctionKeyword */:
21660                     return !inStartOfParameter;
21661                 case 40 /* MinusToken */:
21662                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
21663                 case 20 /* OpenParenToken */:
21664                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
21665                     // or something that starts a type. We don't want to consider things like '(1)' a type.
21666                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
21667                 default:
21668                     return isIdentifier();
21669             }
21670         }
21671         function isStartOfParenthesizedOrFunctionType() {
21672             nextToken();
21673             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
21674         }
21675         function parsePostfixTypeOrHigher() {
21676             var type = parseNonArrayType();
21677             while (!scanner.hasPrecedingLineBreak()) {
21678                 switch (token()) {
21679                     case 53 /* ExclamationToken */:
21680                         type = createPostfixType(298 /* JSDocNonNullableType */, type);
21681                         break;
21682                     case 57 /* QuestionToken */:
21683                         // If not in JSDoc and next token is start of a type we have a conditional type
21684                         if (!(contextFlags & 4194304 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
21685                             return type;
21686                         }
21687                         type = createPostfixType(297 /* JSDocNullableType */, type);
21688                         break;
21689                     case 22 /* OpenBracketToken */:
21690                         parseExpected(22 /* OpenBracketToken */);
21691                         if (isStartOfType()) {
21692                             var node = createNode(185 /* IndexedAccessType */, type.pos);
21693                             node.objectType = type;
21694                             node.indexType = parseType();
21695                             parseExpected(23 /* CloseBracketToken */);
21696                             type = finishNode(node);
21697                         }
21698                         else {
21699                             var node = createNode(174 /* ArrayType */, type.pos);
21700                             node.elementType = type;
21701                             parseExpected(23 /* CloseBracketToken */);
21702                             type = finishNode(node);
21703                         }
21704                         break;
21705                     default:
21706                         return type;
21707                 }
21708             }
21709             return type;
21710         }
21711         function createPostfixType(kind, type) {
21712             nextToken();
21713             var postfix = createNode(kind, type.pos);
21714             postfix.type = type;
21715             return finishNode(postfix);
21716         }
21717         function parseTypeOperator(operator) {
21718             var node = createNode(184 /* TypeOperator */);
21719             parseExpected(operator);
21720             node.operator = operator;
21721             node.type = parseTypeOperatorOrHigher();
21722             return finishNode(node);
21723         }
21724         function parseInferType() {
21725             var node = createNode(181 /* InferType */);
21726             parseExpected(132 /* InferKeyword */);
21727             var typeParameter = createNode(155 /* TypeParameter */);
21728             typeParameter.name = parseIdentifier();
21729             node.typeParameter = finishNode(typeParameter);
21730             return finishNode(node);
21731         }
21732         function parseTypeOperatorOrHigher() {
21733             var operator = token();
21734             switch (operator) {
21735                 case 134 /* KeyOfKeyword */:
21736                 case 147 /* UniqueKeyword */:
21737                 case 138 /* ReadonlyKeyword */:
21738                     return parseTypeOperator(operator);
21739                 case 132 /* InferKeyword */:
21740                     return parseInferType();
21741             }
21742             return parsePostfixTypeOrHigher();
21743         }
21744         function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
21745             var start = scanner.getStartPos();
21746             var hasLeadingOperator = parseOptional(operator);
21747             var type = parseConstituentType();
21748             if (token() === operator || hasLeadingOperator) {
21749                 var types = [type];
21750                 while (parseOptional(operator)) {
21751                     types.push(parseConstituentType());
21752                 }
21753                 var node = createNode(kind, start);
21754                 node.types = createNodeArray(types, start);
21755                 type = finishNode(node);
21756             }
21757             return type;
21758         }
21759         function parseIntersectionTypeOrHigher() {
21760             return parseUnionOrIntersectionType(179 /* IntersectionType */, parseTypeOperatorOrHigher, 50 /* AmpersandToken */);
21761         }
21762         function parseUnionTypeOrHigher() {
21763             return parseUnionOrIntersectionType(178 /* UnionType */, parseIntersectionTypeOrHigher, 51 /* BarToken */);
21764         }
21765         function isStartOfFunctionType() {
21766             if (token() === 29 /* LessThanToken */) {
21767                 return true;
21768             }
21769             return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
21770         }
21771         function skipParameterStart() {
21772             if (ts.isModifierKind(token())) {
21773                 // Skip modifiers
21774                 parseModifiers();
21775             }
21776             if (isIdentifier() || token() === 104 /* ThisKeyword */) {
21777                 nextToken();
21778                 return true;
21779             }
21780             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
21781                 // Return true if we can parse an array or object binding pattern with no errors
21782                 var previousErrorCount = parseDiagnostics.length;
21783                 parseIdentifierOrPattern();
21784                 return previousErrorCount === parseDiagnostics.length;
21785             }
21786             return false;
21787         }
21788         function isUnambiguouslyStartOfFunctionType() {
21789             nextToken();
21790             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
21791                 // ( )
21792                 // ( ...
21793                 return true;
21794             }
21795             if (skipParameterStart()) {
21796                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
21797                 // now see if we have something that indicates a parameter declaration
21798                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
21799                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
21800                     // ( xxx :
21801                     // ( xxx ,
21802                     // ( xxx ?
21803                     // ( xxx =
21804                     return true;
21805                 }
21806                 if (token() === 21 /* CloseParenToken */) {
21807                     nextToken();
21808                     if (token() === 38 /* EqualsGreaterThanToken */) {
21809                         // ( xxx ) =>
21810                         return true;
21811                     }
21812                 }
21813             }
21814             return false;
21815         }
21816         function parseTypeOrTypePredicate() {
21817             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
21818             var type = parseType();
21819             if (typePredicateVariable) {
21820                 var node = createNode(168 /* TypePredicate */, typePredicateVariable.pos);
21821                 node.assertsModifier = undefined;
21822                 node.parameterName = typePredicateVariable;
21823                 node.type = type;
21824                 return finishNode(node);
21825             }
21826             else {
21827                 return type;
21828             }
21829         }
21830         function parseTypePredicatePrefix() {
21831             var id = parseIdentifier();
21832             if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21833                 nextToken();
21834                 return id;
21835             }
21836         }
21837         function parseAssertsTypePredicate() {
21838             var node = createNode(168 /* TypePredicate */);
21839             node.assertsModifier = parseExpectedToken(124 /* AssertsKeyword */);
21840             node.parameterName = token() === 104 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
21841             node.type = parseOptional(133 /* IsKeyword */) ? parseType() : undefined;
21842             return finishNode(node);
21843         }
21844         function parseType() {
21845             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
21846             // apply to 'type' contexts.  So we disable these parameters here before moving on.
21847             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
21848         }
21849         function parseTypeWorker(noConditionalTypes) {
21850             if (isStartOfFunctionType() || token() === 99 /* NewKeyword */) {
21851                 return parseFunctionOrConstructorType();
21852             }
21853             var type = parseUnionTypeOrHigher();
21854             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(90 /* ExtendsKeyword */)) {
21855                 var node = createNode(180 /* ConditionalType */, type.pos);
21856                 node.checkType = type;
21857                 // The type following 'extends' is not permitted to be another conditional type
21858                 node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
21859                 parseExpected(57 /* QuestionToken */);
21860                 node.trueType = parseTypeWorker();
21861                 parseExpected(58 /* ColonToken */);
21862                 node.falseType = parseTypeWorker();
21863                 return finishNode(node);
21864             }
21865             return type;
21866         }
21867         function parseTypeAnnotation() {
21868             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
21869         }
21870         // EXPRESSIONS
21871         function isStartOfLeftHandSideExpression() {
21872             switch (token()) {
21873                 case 104 /* ThisKeyword */:
21874                 case 102 /* SuperKeyword */:
21875                 case 100 /* NullKeyword */:
21876                 case 106 /* TrueKeyword */:
21877                 case 91 /* FalseKeyword */:
21878                 case 8 /* NumericLiteral */:
21879                 case 9 /* BigIntLiteral */:
21880                 case 10 /* StringLiteral */:
21881                 case 14 /* NoSubstitutionTemplateLiteral */:
21882                 case 15 /* TemplateHead */:
21883                 case 20 /* OpenParenToken */:
21884                 case 22 /* OpenBracketToken */:
21885                 case 18 /* OpenBraceToken */:
21886                 case 94 /* FunctionKeyword */:
21887                 case 80 /* ClassKeyword */:
21888                 case 99 /* NewKeyword */:
21889                 case 43 /* SlashToken */:
21890                 case 67 /* SlashEqualsToken */:
21891                 case 75 /* Identifier */:
21892                     return true;
21893                 case 96 /* ImportKeyword */:
21894                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
21895                 default:
21896                     return isIdentifier();
21897             }
21898         }
21899         function isStartOfExpression() {
21900             if (isStartOfLeftHandSideExpression()) {
21901                 return true;
21902             }
21903             switch (token()) {
21904                 case 39 /* PlusToken */:
21905                 case 40 /* MinusToken */:
21906                 case 54 /* TildeToken */:
21907                 case 53 /* ExclamationToken */:
21908                 case 85 /* DeleteKeyword */:
21909                 case 108 /* TypeOfKeyword */:
21910                 case 110 /* VoidKeyword */:
21911                 case 45 /* PlusPlusToken */:
21912                 case 46 /* MinusMinusToken */:
21913                 case 29 /* LessThanToken */:
21914                 case 127 /* AwaitKeyword */:
21915                 case 121 /* YieldKeyword */:
21916                 case 76 /* PrivateIdentifier */:
21917                     // Yield/await always starts an expression.  Either it is an identifier (in which case
21918                     // it is definitely an expression).  Or it's a keyword (either because we're in
21919                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
21920                     return true;
21921                 default:
21922                     // Error tolerance.  If we see the start of some binary operator, we consider
21923                     // that the start of an expression.  That way we'll parse out a missing identifier,
21924                     // give a good message about an identifier being missing, and then consume the
21925                     // rest of the binary expression.
21926                     if (isBinaryOperator()) {
21927                         return true;
21928                     }
21929                     return isIdentifier();
21930             }
21931         }
21932         function isStartOfExpressionStatement() {
21933             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
21934             return token() !== 18 /* OpenBraceToken */ &&
21935                 token() !== 94 /* FunctionKeyword */ &&
21936                 token() !== 80 /* ClassKeyword */ &&
21937                 token() !== 59 /* AtToken */ &&
21938                 isStartOfExpression();
21939         }
21940         function parseExpression() {
21941             // Expression[in]:
21942             //      AssignmentExpression[in]
21943             //      Expression[in] , AssignmentExpression[in]
21944             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
21945             var saveDecoratorContext = inDecoratorContext();
21946             if (saveDecoratorContext) {
21947                 setDecoratorContext(/*val*/ false);
21948             }
21949             var expr = parseAssignmentExpressionOrHigher();
21950             var operatorToken;
21951             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
21952                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
21953             }
21954             if (saveDecoratorContext) {
21955                 setDecoratorContext(/*val*/ true);
21956             }
21957             return expr;
21958         }
21959         function parseInitializer() {
21960             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
21961         }
21962         function parseAssignmentExpressionOrHigher() {
21963             //  AssignmentExpression[in,yield]:
21964             //      1) ConditionalExpression[?in,?yield]
21965             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
21966             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
21967             //      4) ArrowFunctionExpression[?in,?yield]
21968             //      5) AsyncArrowFunctionExpression[in,yield,await]
21969             //      6) [+Yield] YieldExpression[?In]
21970             //
21971             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
21972             // (i.e. they're both BinaryExpressions with an assignment operator in it).
21973             // First, do the simple check if we have a YieldExpression (production '6').
21974             if (isYieldExpression()) {
21975                 return parseYieldExpression();
21976             }
21977             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
21978             // parameter list or is an async arrow function.
21979             // AsyncArrowFunctionExpression:
21980             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
21981             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
21982             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
21983             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
21984             //
21985             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
21986             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
21987             // with AssignmentExpression if we see one.
21988             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
21989             if (arrowExpression) {
21990                 return arrowExpression;
21991             }
21992             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
21993             // start with a LogicalOrExpression, while the assignment productions can only start with
21994             // LeftHandSideExpressions.
21995             //
21996             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
21997             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
21998             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
21999             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
22000             // and consumes anything.
22001             var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22002             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
22003             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
22004             // identifier and the current token is an arrow.
22005             if (expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22006                 return parseSimpleArrowFunctionExpression(expr);
22007             }
22008             // Now see if we might be in cases '2' or '3'.
22009             // If the expression was a LHS expression, and we have an assignment operator, then
22010             // we're in '2' or '3'. Consume the assignment and return.
22011             //
22012             // Note: we call reScanGreaterToken so that we get an appropriately merged token
22013             // for cases like `> > =` becoming `>>=`
22014             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
22015                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
22016             }
22017             // It wasn't an assignment or a lambda.  This is a conditional expression:
22018             return parseConditionalExpressionRest(expr);
22019         }
22020         function isYieldExpression() {
22021             if (token() === 121 /* YieldKeyword */) {
22022                 // If we have a 'yield' keyword, and this is a context where yield expressions are
22023                 // allowed, then definitely parse out a yield expression.
22024                 if (inYieldContext()) {
22025                     return true;
22026                 }
22027                 // We're in a context where 'yield expr' is not allowed.  However, if we can
22028                 // definitely tell that the user was trying to parse a 'yield expr' and not
22029                 // just a normal expr that start with a 'yield' identifier, then parse out
22030                 // a 'yield expr'.  We can then report an error later that they are only
22031                 // allowed in generator expressions.
22032                 //
22033                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
22034                 // invocation expression of something called 'yield'.  However, if we have
22035                 // 'yield foo' then that is not legal as a normal expression, so we can
22036                 // definitely recognize this as a yield expression.
22037                 //
22038                 // for now we just check if the next token is an identifier.  More heuristics
22039                 // can be added here later as necessary.  We just need to make sure that we
22040                 // don't accidentally consume something legal.
22041                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22042             }
22043             return false;
22044         }
22045         function nextTokenIsIdentifierOnSameLine() {
22046             nextToken();
22047             return !scanner.hasPrecedingLineBreak() && isIdentifier();
22048         }
22049         function parseYieldExpression() {
22050             var node = createNode(212 /* YieldExpression */);
22051             // YieldExpression[In] :
22052             //      yield
22053             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22054             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22055             nextToken();
22056             if (!scanner.hasPrecedingLineBreak() &&
22057                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
22058                 node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
22059                 node.expression = parseAssignmentExpressionOrHigher();
22060                 return finishNode(node);
22061             }
22062             else {
22063                 // if the next token is not on the same line as yield.  or we don't have an '*' or
22064                 // the start of an expression, then this is just a simple "yield" expression.
22065                 return finishNode(node);
22066             }
22067         }
22068         function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
22069             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
22070             var node;
22071             if (asyncModifier) {
22072                 node = createNode(202 /* ArrowFunction */, asyncModifier.pos);
22073                 node.modifiers = asyncModifier;
22074             }
22075             else {
22076                 node = createNode(202 /* ArrowFunction */, identifier.pos);
22077             }
22078             var parameter = createNode(156 /* Parameter */, identifier.pos);
22079             parameter.name = identifier;
22080             finishNode(parameter);
22081             node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
22082             node.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22083             node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
22084             return addJSDocComment(finishNode(node));
22085         }
22086         function tryParseParenthesizedArrowFunctionExpression() {
22087             var triState = isParenthesizedArrowFunctionExpression();
22088             if (triState === 0 /* False */) {
22089                 // It's definitely not a parenthesized arrow function expression.
22090                 return undefined;
22091             }
22092             // If we definitely have an arrow function, then we can just parse one, not requiring a
22093             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
22094             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
22095             // expression instead.
22096             var arrowFunction = triState === 1 /* True */
22097                 ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
22098                 : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
22099             if (!arrowFunction) {
22100                 // Didn't appear to actually be a parenthesized arrow function.  Just bail out.
22101                 return undefined;
22102             }
22103             var isAsync = hasModifierOfKind(arrowFunction, 126 /* AsyncKeyword */);
22104             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
22105             // have an opening brace, just in case we're in an error state.
22106             var lastToken = token();
22107             arrowFunction.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22108             arrowFunction.body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
22109                 ? parseArrowFunctionExpressionBody(isAsync)
22110                 : parseIdentifier();
22111             return finishNode(arrowFunction);
22112         }
22113         //  True        -> We definitely expect a parenthesized arrow function here.
22114         //  False       -> There *cannot* be a parenthesized arrow function here.
22115         //  Unknown     -> There *might* be a parenthesized arrow function here.
22116         //                 Speculatively look ahead to be sure, and rollback if not.
22117         function isParenthesizedArrowFunctionExpression() {
22118             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 126 /* AsyncKeyword */) {
22119                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
22120             }
22121             if (token() === 38 /* EqualsGreaterThanToken */) {
22122                 // ERROR RECOVERY TWEAK:
22123                 // If we see a standalone => try to parse it as an arrow function expression as that's
22124                 // likely what the user intended to write.
22125                 return 1 /* True */;
22126             }
22127             // Definitely not a parenthesized arrow function.
22128             return 0 /* False */;
22129         }
22130         function isParenthesizedArrowFunctionExpressionWorker() {
22131             if (token() === 126 /* AsyncKeyword */) {
22132                 nextToken();
22133                 if (scanner.hasPrecedingLineBreak()) {
22134                     return 0 /* False */;
22135                 }
22136                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
22137                     return 0 /* False */;
22138                 }
22139             }
22140             var first = token();
22141             var second = nextToken();
22142             if (first === 20 /* OpenParenToken */) {
22143                 if (second === 21 /* CloseParenToken */) {
22144                     // Simple cases: "() =>", "(): ", and "() {".
22145                     // This is an arrow function with no parameters.
22146                     // The last one is not actually an arrow function,
22147                     // but this is probably what the user intended.
22148                     var third = nextToken();
22149                     switch (third) {
22150                         case 38 /* EqualsGreaterThanToken */:
22151                         case 58 /* ColonToken */:
22152                         case 18 /* OpenBraceToken */:
22153                             return 1 /* True */;
22154                         default:
22155                             return 0 /* False */;
22156                     }
22157                 }
22158                 // If encounter "([" or "({", this could be the start of a binding pattern.
22159                 // Examples:
22160                 //      ([ x ]) => { }
22161                 //      ({ x }) => { }
22162                 //      ([ x ])
22163                 //      ({ x })
22164                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
22165                     return 2 /* Unknown */;
22166                 }
22167                 // Simple case: "(..."
22168                 // This is an arrow function with a rest parameter.
22169                 if (second === 25 /* DotDotDotToken */) {
22170                     return 1 /* True */;
22171                 }
22172                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
22173                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
22174                 // a good error message.
22175                 if (ts.isModifierKind(second) && second !== 126 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
22176                     return 1 /* True */;
22177                 }
22178                 // If we had "(" followed by something that's not an identifier,
22179                 // then this definitely doesn't look like a lambda.  "this" is not
22180                 // valid, but we want to parse it and then give a semantic error.
22181                 if (!isIdentifier() && second !== 104 /* ThisKeyword */) {
22182                     return 0 /* False */;
22183                 }
22184                 switch (nextToken()) {
22185                     case 58 /* ColonToken */:
22186                         // If we have something like "(a:", then we must have a
22187                         // type-annotated parameter in an arrow function expression.
22188                         return 1 /* True */;
22189                     case 57 /* QuestionToken */:
22190                         nextToken();
22191                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
22192                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
22193                             return 1 /* True */;
22194                         }
22195                         // Otherwise it is definitely not a lambda.
22196                         return 0 /* False */;
22197                     case 27 /* CommaToken */:
22198                     case 62 /* EqualsToken */:
22199                     case 21 /* CloseParenToken */:
22200                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
22201                         return 2 /* Unknown */;
22202                 }
22203                 // It is definitely not an arrow function
22204                 return 0 /* False */;
22205             }
22206             else {
22207                 ts.Debug.assert(first === 29 /* LessThanToken */);
22208                 // If we have "<" not followed by an identifier,
22209                 // then this definitely is not an arrow function.
22210                 if (!isIdentifier()) {
22211                     return 0 /* False */;
22212                 }
22213                 // JSX overrides
22214                 if (sourceFile.languageVariant === 1 /* JSX */) {
22215                     var isArrowFunctionInJsx = lookAhead(function () {
22216                         var third = nextToken();
22217                         if (third === 90 /* ExtendsKeyword */) {
22218                             var fourth = nextToken();
22219                             switch (fourth) {
22220                                 case 62 /* EqualsToken */:
22221                                 case 31 /* GreaterThanToken */:
22222                                     return false;
22223                                 default:
22224                                     return true;
22225                             }
22226                         }
22227                         else if (third === 27 /* CommaToken */) {
22228                             return true;
22229                         }
22230                         return false;
22231                     });
22232                     if (isArrowFunctionInJsx) {
22233                         return 1 /* True */;
22234                     }
22235                     return 0 /* False */;
22236                 }
22237                 // This *could* be a parenthesized arrow function.
22238                 return 2 /* Unknown */;
22239             }
22240         }
22241         function parsePossibleParenthesizedArrowFunctionExpressionHead() {
22242             var tokenPos = scanner.getTokenPos();
22243             if (notParenthesizedArrow && notParenthesizedArrow.has(tokenPos.toString())) {
22244                 return undefined;
22245             }
22246             var result = parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
22247             if (!result) {
22248                 (notParenthesizedArrow || (notParenthesizedArrow = ts.createMap())).set(tokenPos.toString(), true);
22249             }
22250             return result;
22251         }
22252         function tryParseAsyncSimpleArrowFunctionExpression() {
22253             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
22254             if (token() === 126 /* AsyncKeyword */) {
22255                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
22256                     var asyncModifier = parseModifiersForArrowFunction();
22257                     var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22258                     return parseSimpleArrowFunctionExpression(expr, asyncModifier);
22259                 }
22260             }
22261             return undefined;
22262         }
22263         function isUnParenthesizedAsyncArrowFunctionWorker() {
22264             // AsyncArrowFunctionExpression:
22265             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
22266             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
22267             if (token() === 126 /* AsyncKeyword */) {
22268                 nextToken();
22269                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
22270                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
22271                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
22272                     return 0 /* False */;
22273                 }
22274                 // Check for un-parenthesized AsyncArrowFunction
22275                 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22276                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22277                     return 1 /* True */;
22278                 }
22279             }
22280             return 0 /* False */;
22281         }
22282         function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
22283             var node = createNodeWithJSDoc(202 /* ArrowFunction */);
22284             node.modifiers = parseModifiersForArrowFunction();
22285             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
22286             // Arrow functions are never generators.
22287             //
22288             // If we're speculatively parsing a signature for a parenthesized arrow function, then
22289             // we have to have a complete parameter list.  Otherwise we might see something like
22290             // a => (b => c)
22291             // And think that "(b =>" was actually a parenthesized arrow function with a missing
22292             // close paren.
22293             if (!fillSignature(58 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
22294                 return undefined;
22295             }
22296             // Parsing a signature isn't enough.
22297             // Parenthesized arrow signatures often look like other valid expressions.
22298             // For instance:
22299             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
22300             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
22301             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
22302             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
22303             //
22304             // So we need just a bit of lookahead to ensure that it can only be a signature.
22305             var hasJSDocFunctionType = node.type && ts.isJSDocFunctionType(node.type);
22306             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
22307                 // Returning undefined here will cause our caller to rewind to where we started from.
22308                 return undefined;
22309             }
22310             return node;
22311         }
22312         function parseArrowFunctionExpressionBody(isAsync) {
22313             if (token() === 18 /* OpenBraceToken */) {
22314                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
22315             }
22316             if (token() !== 26 /* SemicolonToken */ &&
22317                 token() !== 94 /* FunctionKeyword */ &&
22318                 token() !== 80 /* ClassKeyword */ &&
22319                 isStartOfStatement() &&
22320                 !isStartOfExpressionStatement()) {
22321                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
22322                 //
22323                 // Here we try to recover from a potential error situation in the case where the
22324                 // user meant to supply a block. For example, if the user wrote:
22325                 //
22326                 //  a =>
22327                 //      let v = 0;
22328                 //  }
22329                 //
22330                 // they may be missing an open brace.  Check to see if that's the case so we can
22331                 // try to recover better.  If we don't do this, then the next close curly we see may end
22332                 // up preemptively closing the containing construct.
22333                 //
22334                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
22335                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
22336             }
22337             return isAsync
22338                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
22339                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
22340         }
22341         function parseConditionalExpressionRest(leftOperand) {
22342             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
22343             var questionToken = parseOptionalToken(57 /* QuestionToken */);
22344             if (!questionToken) {
22345                 return leftOperand;
22346             }
22347             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
22348             // we do not that for the 'whenFalse' part.
22349             var node = createNode(210 /* ConditionalExpression */, leftOperand.pos);
22350             node.condition = leftOperand;
22351             node.questionToken = questionToken;
22352             node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
22353             node.colonToken = parseExpectedToken(58 /* ColonToken */);
22354             node.whenFalse = ts.nodeIsPresent(node.colonToken)
22355                 ? parseAssignmentExpressionOrHigher()
22356                 : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
22357             return finishNode(node);
22358         }
22359         function parseBinaryExpressionOrHigher(precedence) {
22360             var leftOperand = parseUnaryExpressionOrHigher();
22361             return parseBinaryExpressionRest(precedence, leftOperand);
22362         }
22363         function isInOrOfKeyword(t) {
22364             return t === 97 /* InKeyword */ || t === 152 /* OfKeyword */;
22365         }
22366         function parseBinaryExpressionRest(precedence, leftOperand) {
22367             while (true) {
22368                 // We either have a binary operator here, or we're finished.  We call
22369                 // reScanGreaterToken so that we merge token sequences like > and = into >=
22370                 reScanGreaterToken();
22371                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
22372                 // Check the precedence to see if we should "take" this operator
22373                 // - For left associative operator (all operator but **), consume the operator,
22374                 //   recursively call the function below, and parse binaryExpression as a rightOperand
22375                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
22376                 //   For example:
22377                 //      a - b - c;
22378                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22379                 //      a * b - c
22380                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22381                 //      a - b * c;
22382                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
22383                 // - For right associative operator (**), consume the operator, recursively call the function
22384                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
22385                 //   the operator is strictly grater than the current precedence
22386                 //   For example:
22387                 //      a ** b ** c;
22388                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22389                 //      a - b ** c;
22390                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22391                 //      a ** b - c
22392                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
22393                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
22394                     newPrecedence >= precedence :
22395                     newPrecedence > precedence;
22396                 if (!consumeCurrentOperator) {
22397                     break;
22398                 }
22399                 if (token() === 97 /* InKeyword */ && inDisallowInContext()) {
22400                     break;
22401                 }
22402                 if (token() === 123 /* AsKeyword */) {
22403                     // Make sure we *do* perform ASI for constructs like this:
22404                     //    var x = foo
22405                     //    as (Bar)
22406                     // This should be parsed as an initialized variable, followed
22407                     // by a function call to 'as' with the argument 'Bar'
22408                     if (scanner.hasPrecedingLineBreak()) {
22409                         break;
22410                     }
22411                     else {
22412                         nextToken();
22413                         leftOperand = makeAsExpression(leftOperand, parseType());
22414                     }
22415                 }
22416                 else {
22417                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
22418                 }
22419             }
22420             return leftOperand;
22421         }
22422         function isBinaryOperator() {
22423             if (inDisallowInContext() && token() === 97 /* InKeyword */) {
22424                 return false;
22425             }
22426             return ts.getBinaryOperatorPrecedence(token()) > 0;
22427         }
22428         function makeBinaryExpression(left, operatorToken, right) {
22429             var node = createNode(209 /* BinaryExpression */, left.pos);
22430             node.left = left;
22431             node.operatorToken = operatorToken;
22432             node.right = right;
22433             return finishNode(node);
22434         }
22435         function makeAsExpression(left, right) {
22436             var node = createNode(217 /* AsExpression */, left.pos);
22437             node.expression = left;
22438             node.type = right;
22439             return finishNode(node);
22440         }
22441         function parsePrefixUnaryExpression() {
22442             var node = createNode(207 /* PrefixUnaryExpression */);
22443             node.operator = token();
22444             nextToken();
22445             node.operand = parseSimpleUnaryExpression();
22446             return finishNode(node);
22447         }
22448         function parseDeleteExpression() {
22449             var node = createNode(203 /* DeleteExpression */);
22450             nextToken();
22451             node.expression = parseSimpleUnaryExpression();
22452             return finishNode(node);
22453         }
22454         function parseTypeOfExpression() {
22455             var node = createNode(204 /* TypeOfExpression */);
22456             nextToken();
22457             node.expression = parseSimpleUnaryExpression();
22458             return finishNode(node);
22459         }
22460         function parseVoidExpression() {
22461             var node = createNode(205 /* VoidExpression */);
22462             nextToken();
22463             node.expression = parseSimpleUnaryExpression();
22464             return finishNode(node);
22465         }
22466         function isAwaitExpression() {
22467             if (token() === 127 /* AwaitKeyword */) {
22468                 if (inAwaitContext()) {
22469                     return true;
22470                 }
22471                 // here we are using similar heuristics as 'isYieldExpression'
22472                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22473             }
22474             return false;
22475         }
22476         function parseAwaitExpression() {
22477             var node = createNode(206 /* AwaitExpression */);
22478             nextToken();
22479             node.expression = parseSimpleUnaryExpression();
22480             return finishNode(node);
22481         }
22482         /**
22483          * Parse ES7 exponential expression and await expression
22484          *
22485          * ES7 ExponentiationExpression:
22486          *      1) UnaryExpression[?Yield]
22487          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
22488          *
22489          */
22490         function parseUnaryExpressionOrHigher() {
22491             /**
22492              * ES7 UpdateExpression:
22493              *      1) LeftHandSideExpression[?Yield]
22494              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
22495              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
22496              *      4) ++UnaryExpression[?Yield]
22497              *      5) --UnaryExpression[?Yield]
22498              */
22499             if (isUpdateExpression()) {
22500                 var updateExpression = parseUpdateExpression();
22501                 return token() === 42 /* AsteriskAsteriskToken */ ?
22502                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
22503                     updateExpression;
22504             }
22505             /**
22506              * ES7 UnaryExpression:
22507              *      1) UpdateExpression[?yield]
22508              *      2) delete UpdateExpression[?yield]
22509              *      3) void UpdateExpression[?yield]
22510              *      4) typeof UpdateExpression[?yield]
22511              *      5) + UpdateExpression[?yield]
22512              *      6) - UpdateExpression[?yield]
22513              *      7) ~ UpdateExpression[?yield]
22514              *      8) ! UpdateExpression[?yield]
22515              */
22516             var unaryOperator = token();
22517             var simpleUnaryExpression = parseSimpleUnaryExpression();
22518             if (token() === 42 /* AsteriskAsteriskToken */) {
22519                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
22520                 var end = simpleUnaryExpression.end;
22521                 if (simpleUnaryExpression.kind === 199 /* TypeAssertionExpression */) {
22522                     parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
22523                 }
22524                 else {
22525                     parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator));
22526                 }
22527             }
22528             return simpleUnaryExpression;
22529         }
22530         /**
22531          * Parse ES7 simple-unary expression or higher:
22532          *
22533          * ES7 UnaryExpression:
22534          *      1) UpdateExpression[?yield]
22535          *      2) delete UnaryExpression[?yield]
22536          *      3) void UnaryExpression[?yield]
22537          *      4) typeof UnaryExpression[?yield]
22538          *      5) + UnaryExpression[?yield]
22539          *      6) - UnaryExpression[?yield]
22540          *      7) ~ UnaryExpression[?yield]
22541          *      8) ! UnaryExpression[?yield]
22542          *      9) [+Await] await UnaryExpression[?yield]
22543          */
22544         function parseSimpleUnaryExpression() {
22545             switch (token()) {
22546                 case 39 /* PlusToken */:
22547                 case 40 /* MinusToken */:
22548                 case 54 /* TildeToken */:
22549                 case 53 /* ExclamationToken */:
22550                     return parsePrefixUnaryExpression();
22551                 case 85 /* DeleteKeyword */:
22552                     return parseDeleteExpression();
22553                 case 108 /* TypeOfKeyword */:
22554                     return parseTypeOfExpression();
22555                 case 110 /* VoidKeyword */:
22556                     return parseVoidExpression();
22557                 case 29 /* LessThanToken */:
22558                     // This is modified UnaryExpression grammar in TypeScript
22559                     //  UnaryExpression (modified):
22560                     //      < type > UnaryExpression
22561                     return parseTypeAssertion();
22562                 case 127 /* AwaitKeyword */:
22563                     if (isAwaitExpression()) {
22564                         return parseAwaitExpression();
22565                     }
22566                 // falls through
22567                 default:
22568                     return parseUpdateExpression();
22569             }
22570         }
22571         /**
22572          * Check if the current token can possibly be an ES7 increment expression.
22573          *
22574          * ES7 UpdateExpression:
22575          *      LeftHandSideExpression[?Yield]
22576          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
22577          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
22578          *      ++LeftHandSideExpression[?Yield]
22579          *      --LeftHandSideExpression[?Yield]
22580          */
22581         function isUpdateExpression() {
22582             // This function is called inside parseUnaryExpression to decide
22583             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
22584             switch (token()) {
22585                 case 39 /* PlusToken */:
22586                 case 40 /* MinusToken */:
22587                 case 54 /* TildeToken */:
22588                 case 53 /* ExclamationToken */:
22589                 case 85 /* DeleteKeyword */:
22590                 case 108 /* TypeOfKeyword */:
22591                 case 110 /* VoidKeyword */:
22592                 case 127 /* AwaitKeyword */:
22593                     return false;
22594                 case 29 /* LessThanToken */:
22595                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
22596                     if (sourceFile.languageVariant !== 1 /* JSX */) {
22597                         return false;
22598                     }
22599                 // We are in JSX context and the token is part of JSXElement.
22600                 // falls through
22601                 default:
22602                     return true;
22603             }
22604         }
22605         /**
22606          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
22607          *
22608          * ES7 UpdateExpression[yield]:
22609          *      1) LeftHandSideExpression[?yield]
22610          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
22611          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
22612          *      4) ++LeftHandSideExpression[?yield]
22613          *      5) --LeftHandSideExpression[?yield]
22614          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
22615          */
22616         function parseUpdateExpression() {
22617             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
22618                 var node = createNode(207 /* PrefixUnaryExpression */);
22619                 node.operator = token();
22620                 nextToken();
22621                 node.operand = parseLeftHandSideExpressionOrHigher();
22622                 return finishNode(node);
22623             }
22624             else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
22625                 // JSXElement is part of primaryExpression
22626                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
22627             }
22628             var expression = parseLeftHandSideExpressionOrHigher();
22629             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
22630             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
22631                 var node = createNode(208 /* PostfixUnaryExpression */, expression.pos);
22632                 node.operand = expression;
22633                 node.operator = token();
22634                 nextToken();
22635                 return finishNode(node);
22636             }
22637             return expression;
22638         }
22639         function parseLeftHandSideExpressionOrHigher() {
22640             // Original Ecma:
22641             // LeftHandSideExpression: See 11.2
22642             //      NewExpression
22643             //      CallExpression
22644             //
22645             // Our simplification:
22646             //
22647             // LeftHandSideExpression: See 11.2
22648             //      MemberExpression
22649             //      CallExpression
22650             //
22651             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
22652             // MemberExpression to make our lives easier.
22653             //
22654             // to best understand the below code, it's important to see how CallExpression expands
22655             // out into its own productions:
22656             //
22657             // CallExpression:
22658             //      MemberExpression Arguments
22659             //      CallExpression Arguments
22660             //      CallExpression[Expression]
22661             //      CallExpression.IdentifierName
22662             //      import (AssignmentExpression)
22663             //      super Arguments
22664             //      super.IdentifierName
22665             //
22666             // Because of the recursion in these calls, we need to bottom out first. There are three
22667             // bottom out states we can run into: 1) We see 'super' which must start either of
22668             // the last two CallExpression productions. 2) We see 'import' which must start import call.
22669             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
22670             // or starts the beginning of the first four CallExpression productions.
22671             var expression;
22672             if (token() === 96 /* ImportKeyword */) {
22673                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
22674                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
22675                     // For example:
22676                     //      var foo3 = require("subfolder
22677                     //      import * as foo1 from "module-from-node
22678                     // We want this import to be a statement rather than import call expression
22679                     sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
22680                     expression = parseTokenNode();
22681                 }
22682                 else if (lookAhead(nextTokenIsDot)) {
22683                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
22684                     var fullStart = scanner.getStartPos();
22685                     nextToken(); // advance past the 'import'
22686                     nextToken(); // advance past the dot
22687                     var node = createNode(219 /* MetaProperty */, fullStart);
22688                     node.keywordToken = 96 /* ImportKeyword */;
22689                     node.name = parseIdentifierName();
22690                     expression = finishNode(node);
22691                     sourceFile.flags |= 2097152 /* PossiblyContainsImportMeta */;
22692                 }
22693                 else {
22694                     expression = parseMemberExpressionOrHigher();
22695                 }
22696             }
22697             else {
22698                 expression = token() === 102 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
22699             }
22700             // Now, we *may* be complete.  However, we might have consumed the start of a
22701             // CallExpression or OptionalExpression.  As such, we need to consume the rest
22702             // of it here to be complete.
22703             return parseCallExpressionRest(expression);
22704         }
22705         function parseMemberExpressionOrHigher() {
22706             // Note: to make our lives simpler, we decompose the NewExpression productions and
22707             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
22708             // like so:
22709             //
22710             //   PrimaryExpression : See 11.1
22711             //      this
22712             //      Identifier
22713             //      Literal
22714             //      ArrayLiteral
22715             //      ObjectLiteral
22716             //      (Expression)
22717             //      FunctionExpression
22718             //      new MemberExpression Arguments?
22719             //
22720             //   MemberExpression : See 11.2
22721             //      PrimaryExpression
22722             //      MemberExpression[Expression]
22723             //      MemberExpression.IdentifierName
22724             //
22725             //   CallExpression : See 11.2
22726             //      MemberExpression
22727             //      CallExpression Arguments
22728             //      CallExpression[Expression]
22729             //      CallExpression.IdentifierName
22730             //
22731             // Technically this is ambiguous.  i.e. CallExpression defines:
22732             //
22733             //   CallExpression:
22734             //      CallExpression Arguments
22735             //
22736             // If you see: "new Foo()"
22737             //
22738             // Then that could be treated as a single ObjectCreationExpression, or it could be
22739             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
22740             // the original grammar) by making sure that if we see an ObjectCreationExpression
22741             // we always consume arguments if they are there. So we treat "new Foo()" as an
22742             // object creation only, and not at all as an invocation.  Another way to think
22743             // about this is that for every "new" that we see, we will consume an argument list if
22744             // it is there as part of the *associated* object creation node.  Any additional
22745             // argument lists we see, will become invocation expressions.
22746             //
22747             // Because there are no other places in the grammar now that refer to FunctionExpression
22748             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
22749             // production.
22750             //
22751             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
22752             // of the recursion immediately.  So we parse out a primary expression to start with.
22753             var expression = parsePrimaryExpression();
22754             return parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
22755         }
22756         function parseSuperExpression() {
22757             var expression = parseTokenNode();
22758             if (token() === 29 /* LessThanToken */) {
22759                 var startPos = getNodePos();
22760                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
22761                 if (typeArguments !== undefined) {
22762                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
22763                 }
22764             }
22765             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
22766                 return expression;
22767             }
22768             // If we have seen "super" it must be followed by '(' or '.'.
22769             // If it wasn't then just try to parse out a '.' and report an error.
22770             var node = createNode(194 /* PropertyAccessExpression */, expression.pos);
22771             node.expression = expression;
22772             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
22773             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
22774             node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
22775             return finishNode(node);
22776         }
22777         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
22778             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
22779             var result;
22780             if (opening.kind === 268 /* JsxOpeningElement */) {
22781                 var node = createNode(266 /* JsxElement */, opening.pos);
22782                 node.openingElement = opening;
22783                 node.children = parseJsxChildren(node.openingElement);
22784                 node.closingElement = parseJsxClosingElement(inExpressionContext);
22785                 if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
22786                     parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
22787                 }
22788                 result = finishNode(node);
22789             }
22790             else if (opening.kind === 271 /* JsxOpeningFragment */) {
22791                 var node = createNode(270 /* JsxFragment */, opening.pos);
22792                 node.openingFragment = opening;
22793                 node.children = parseJsxChildren(node.openingFragment);
22794                 node.closingFragment = parseJsxClosingFragment(inExpressionContext);
22795                 result = finishNode(node);
22796             }
22797             else {
22798                 ts.Debug.assert(opening.kind === 267 /* JsxSelfClosingElement */);
22799                 // Nothing else to do for self-closing elements
22800                 result = opening;
22801             }
22802             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
22803             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
22804             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
22805             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
22806             // does less damage and we can report a better error.
22807             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
22808             // of one sort or another.
22809             if (inExpressionContext && token() === 29 /* LessThanToken */) {
22810                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
22811                 if (invalidElement) {
22812                     parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
22813                     var badNode = createNode(209 /* BinaryExpression */, result.pos);
22814                     badNode.end = invalidElement.end;
22815                     badNode.left = result;
22816                     badNode.right = invalidElement;
22817                     badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
22818                     badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
22819                     return badNode;
22820                 }
22821             }
22822             return result;
22823         }
22824         function parseJsxText() {
22825             var node = createNode(11 /* JsxText */);
22826             node.text = scanner.getTokenValue();
22827             node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
22828             currentToken = scanner.scanJsxToken();
22829             return finishNode(node);
22830         }
22831         function parseJsxChild(openingTag, token) {
22832             switch (token) {
22833                 case 1 /* EndOfFileToken */:
22834                     // If we hit EOF, issue the error at the tag that lacks the closing element
22835                     // rather than at the end of the file (which is useless)
22836                     if (ts.isJsxOpeningFragment(openingTag)) {
22837                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
22838                     }
22839                     else {
22840                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
22841                         // or to cover only 'Foo' in < Foo >
22842                         var tag = openingTag.tagName;
22843                         var start = ts.skipTrivia(sourceText, tag.pos);
22844                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
22845                     }
22846                     return undefined;
22847                 case 30 /* LessThanSlashToken */:
22848                 case 7 /* ConflictMarkerTrivia */:
22849                     return undefined;
22850                 case 11 /* JsxText */:
22851                 case 12 /* JsxTextAllWhiteSpaces */:
22852                     return parseJsxText();
22853                 case 18 /* OpenBraceToken */:
22854                     return parseJsxExpression(/*inExpressionContext*/ false);
22855                 case 29 /* LessThanToken */:
22856                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
22857                 default:
22858                     return ts.Debug.assertNever(token);
22859             }
22860         }
22861         function parseJsxChildren(openingTag) {
22862             var list = [];
22863             var listPos = getNodePos();
22864             var saveParsingContext = parsingContext;
22865             parsingContext |= 1 << 14 /* JsxChildren */;
22866             while (true) {
22867                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
22868                 if (!child)
22869                     break;
22870                 list.push(child);
22871             }
22872             parsingContext = saveParsingContext;
22873             return createNodeArray(list, listPos);
22874         }
22875         function parseJsxAttributes() {
22876             var jsxAttributes = createNode(274 /* JsxAttributes */);
22877             jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
22878             return finishNode(jsxAttributes);
22879         }
22880         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
22881             var fullStart = scanner.getStartPos();
22882             parseExpected(29 /* LessThanToken */);
22883             if (token() === 31 /* GreaterThanToken */) {
22884                 // See below for explanation of scanJsxText
22885                 var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
22886                 scanJsxText();
22887                 return finishNode(node_1);
22888             }
22889             var tagName = parseJsxElementName();
22890             var typeArguments = tryParseTypeArguments();
22891             var attributes = parseJsxAttributes();
22892             var node;
22893             if (token() === 31 /* GreaterThanToken */) {
22894                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
22895                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
22896                 // scanning errors
22897                 node = createNode(268 /* JsxOpeningElement */, fullStart);
22898                 scanJsxText();
22899             }
22900             else {
22901                 parseExpected(43 /* SlashToken */);
22902                 if (inExpressionContext) {
22903                     parseExpected(31 /* GreaterThanToken */);
22904                 }
22905                 else {
22906                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22907                     scanJsxText();
22908                 }
22909                 node = createNode(267 /* JsxSelfClosingElement */, fullStart);
22910             }
22911             node.tagName = tagName;
22912             node.typeArguments = typeArguments;
22913             node.attributes = attributes;
22914             return finishNode(node);
22915         }
22916         function parseJsxElementName() {
22917             scanJsxIdentifier();
22918             // JsxElement can have name in the form of
22919             //      propertyAccessExpression
22920             //      primaryExpression in the form of an identifier and "this" keyword
22921             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
22922             // We only want to consider "this" as a primaryExpression
22923             var expression = token() === 104 /* ThisKeyword */ ?
22924                 parseTokenNode() : parseIdentifierName();
22925             while (parseOptional(24 /* DotToken */)) {
22926                 var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
22927                 propertyAccess.expression = expression;
22928                 propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
22929                 expression = finishNode(propertyAccess);
22930             }
22931             return expression;
22932         }
22933         function parseJsxExpression(inExpressionContext) {
22934             var node = createNode(276 /* JsxExpression */);
22935             if (!parseExpected(18 /* OpenBraceToken */)) {
22936                 return undefined;
22937             }
22938             if (token() !== 19 /* CloseBraceToken */) {
22939                 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
22940                 // Only an AssignmentExpression is valid here per the JSX spec,
22941                 // but we can unambiguously parse a comma sequence and provide
22942                 // a better error message in grammar checking.
22943                 node.expression = parseExpression();
22944             }
22945             if (inExpressionContext) {
22946                 parseExpected(19 /* CloseBraceToken */);
22947             }
22948             else {
22949                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
22950                     scanJsxText();
22951                 }
22952             }
22953             return finishNode(node);
22954         }
22955         function parseJsxAttribute() {
22956             if (token() === 18 /* OpenBraceToken */) {
22957                 return parseJsxSpreadAttribute();
22958             }
22959             scanJsxIdentifier();
22960             var node = createNode(273 /* JsxAttribute */);
22961             node.name = parseIdentifierName();
22962             if (token() === 62 /* EqualsToken */) {
22963                 switch (scanJsxAttributeValue()) {
22964                     case 10 /* StringLiteral */:
22965                         node.initializer = parseLiteralNode();
22966                         break;
22967                     default:
22968                         node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
22969                         break;
22970                 }
22971             }
22972             return finishNode(node);
22973         }
22974         function parseJsxSpreadAttribute() {
22975             var node = createNode(275 /* JsxSpreadAttribute */);
22976             parseExpected(18 /* OpenBraceToken */);
22977             parseExpected(25 /* DotDotDotToken */);
22978             node.expression = parseExpression();
22979             parseExpected(19 /* CloseBraceToken */);
22980             return finishNode(node);
22981         }
22982         function parseJsxClosingElement(inExpressionContext) {
22983             var node = createNode(269 /* JsxClosingElement */);
22984             parseExpected(30 /* LessThanSlashToken */);
22985             node.tagName = parseJsxElementName();
22986             if (inExpressionContext) {
22987                 parseExpected(31 /* GreaterThanToken */);
22988             }
22989             else {
22990                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22991                 scanJsxText();
22992             }
22993             return finishNode(node);
22994         }
22995         function parseJsxClosingFragment(inExpressionContext) {
22996             var node = createNode(272 /* JsxClosingFragment */);
22997             parseExpected(30 /* LessThanSlashToken */);
22998             if (ts.tokenIsIdentifierOrKeyword(token())) {
22999                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
23000             }
23001             if (inExpressionContext) {
23002                 parseExpected(31 /* GreaterThanToken */);
23003             }
23004             else {
23005                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
23006                 scanJsxText();
23007             }
23008             return finishNode(node);
23009         }
23010         function parseTypeAssertion() {
23011             var node = createNode(199 /* TypeAssertionExpression */);
23012             parseExpected(29 /* LessThanToken */);
23013             node.type = parseType();
23014             parseExpected(31 /* GreaterThanToken */);
23015             node.expression = parseSimpleUnaryExpression();
23016             return finishNode(node);
23017         }
23018         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
23019             nextToken();
23020             return ts.tokenIsIdentifierOrKeyword(token())
23021                 || token() === 22 /* OpenBracketToken */
23022                 || isTemplateStartOfTaggedTemplate();
23023         }
23024         function isStartOfOptionalPropertyOrElementAccessChain() {
23025             return token() === 28 /* QuestionDotToken */
23026                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
23027         }
23028         function tryReparseOptionalChain(node) {
23029             if (node.flags & 32 /* OptionalChain */) {
23030                 return true;
23031             }
23032             // check for an optional chain in a non-null expression
23033             if (ts.isNonNullExpression(node)) {
23034                 var expr = node.expression;
23035                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
23036                     expr = expr.expression;
23037                 }
23038                 if (expr.flags & 32 /* OptionalChain */) {
23039                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
23040                     while (ts.isNonNullExpression(node)) {
23041                         node.flags |= 32 /* OptionalChain */;
23042                         node = node.expression;
23043                     }
23044                     return true;
23045                 }
23046             }
23047             return false;
23048         }
23049         function parsePropertyAccessExpressionRest(expression, questionDotToken) {
23050             var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23051             propertyAccess.expression = expression;
23052             propertyAccess.questionDotToken = questionDotToken;
23053             propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
23054             if (questionDotToken || tryReparseOptionalChain(expression)) {
23055                 propertyAccess.flags |= 32 /* OptionalChain */;
23056                 if (ts.isPrivateIdentifier(propertyAccess.name)) {
23057                     parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
23058                 }
23059             }
23060             return finishNode(propertyAccess);
23061         }
23062         function parseElementAccessExpressionRest(expression, questionDotToken) {
23063             var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
23064             indexedAccess.expression = expression;
23065             indexedAccess.questionDotToken = questionDotToken;
23066             if (token() === 23 /* CloseBracketToken */) {
23067                 indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
23068             }
23069             else {
23070                 var argument = allowInAnd(parseExpression);
23071                 if (ts.isStringOrNumericLiteralLike(argument)) {
23072                     argument.text = internIdentifier(argument.text);
23073                 }
23074                 indexedAccess.argumentExpression = argument;
23075             }
23076             parseExpected(23 /* CloseBracketToken */);
23077             if (questionDotToken || tryReparseOptionalChain(expression)) {
23078                 indexedAccess.flags |= 32 /* OptionalChain */;
23079             }
23080             return finishNode(indexedAccess);
23081         }
23082         function parseMemberExpressionRest(expression, allowOptionalChain) {
23083             while (true) {
23084                 var questionDotToken = void 0;
23085                 var isPropertyAccess = false;
23086                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
23087                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
23088                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
23089                 }
23090                 else {
23091                     isPropertyAccess = parseOptional(24 /* DotToken */);
23092                 }
23093                 if (isPropertyAccess) {
23094                     expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
23095                     continue;
23096                 }
23097                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
23098                     nextToken();
23099                     var nonNullExpression = createNode(218 /* NonNullExpression */, expression.pos);
23100                     nonNullExpression.expression = expression;
23101                     expression = finishNode(nonNullExpression);
23102                     continue;
23103                 }
23104                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
23105                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
23106                     expression = parseElementAccessExpressionRest(expression, questionDotToken);
23107                     continue;
23108                 }
23109                 if (isTemplateStartOfTaggedTemplate()) {
23110                     expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
23111                     continue;
23112                 }
23113                 return expression;
23114             }
23115         }
23116         function isTemplateStartOfTaggedTemplate() {
23117             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
23118         }
23119         function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
23120             var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
23121             tagExpression.tag = tag;
23122             tagExpression.questionDotToken = questionDotToken;
23123             tagExpression.typeArguments = typeArguments;
23124             tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
23125                 ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode())
23126                 : parseTemplateExpression(/*isTaggedTemplate*/ true);
23127             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
23128                 tagExpression.flags |= 32 /* OptionalChain */;
23129             }
23130             return finishNode(tagExpression);
23131         }
23132         function parseCallExpressionRest(expression) {
23133             while (true) {
23134                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
23135                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
23136                 // handle 'foo<<T>()'
23137                 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
23138                     // See if this is the start of a generic invocation.  If so, consume it and
23139                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
23140                     // part of an arithmetic expression.  Break out so we consume it higher in the
23141                     // stack.
23142                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
23143                     if (typeArguments) {
23144                         if (isTemplateStartOfTaggedTemplate()) {
23145                             expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
23146                             continue;
23147                         }
23148                         var callExpr = createNode(196 /* CallExpression */, expression.pos);
23149                         callExpr.expression = expression;
23150                         callExpr.questionDotToken = questionDotToken;
23151                         callExpr.typeArguments = typeArguments;
23152                         callExpr.arguments = parseArgumentList();
23153                         if (questionDotToken || tryReparseOptionalChain(expression)) {
23154                             callExpr.flags |= 32 /* OptionalChain */;
23155                         }
23156                         expression = finishNode(callExpr);
23157                         continue;
23158                     }
23159                 }
23160                 else if (token() === 20 /* OpenParenToken */) {
23161                     var callExpr = createNode(196 /* CallExpression */, expression.pos);
23162                     callExpr.expression = expression;
23163                     callExpr.questionDotToken = questionDotToken;
23164                     callExpr.arguments = parseArgumentList();
23165                     if (questionDotToken || tryReparseOptionalChain(expression)) {
23166                         callExpr.flags |= 32 /* OptionalChain */;
23167                     }
23168                     expression = finishNode(callExpr);
23169                     continue;
23170                 }
23171                 if (questionDotToken) {
23172                     // We failed to parse anything, so report a missing identifier here.
23173                     var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23174                     propertyAccess.expression = expression;
23175                     propertyAccess.questionDotToken = questionDotToken;
23176                     propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
23177                     propertyAccess.flags |= 32 /* OptionalChain */;
23178                     expression = finishNode(propertyAccess);
23179                 }
23180                 break;
23181             }
23182             return expression;
23183         }
23184         function parseArgumentList() {
23185             parseExpected(20 /* OpenParenToken */);
23186             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
23187             parseExpected(21 /* CloseParenToken */);
23188             return result;
23189         }
23190         function parseTypeArgumentsInExpression() {
23191             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
23192                 return undefined;
23193             }
23194             nextToken();
23195             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
23196             if (!parseExpected(31 /* GreaterThanToken */)) {
23197                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
23198                 return undefined;
23199             }
23200             // If we have a '<', then only parse this as a argument list if the type arguments
23201             // are complete and we have an open paren.  if we don't, rewind and return nothing.
23202             return typeArguments && canFollowTypeArgumentsInExpression()
23203                 ? typeArguments
23204                 : undefined;
23205         }
23206         function canFollowTypeArgumentsInExpression() {
23207             switch (token()) {
23208                 case 20 /* OpenParenToken */: // foo<x>(
23209                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
23210                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
23211                 // these are the only tokens can legally follow a type argument
23212                 // list. So we definitely want to treat them as type arg lists.
23213                 // falls through
23214                 case 24 /* DotToken */: // foo<x>.
23215                 case 21 /* CloseParenToken */: // foo<x>)
23216                 case 23 /* CloseBracketToken */: // foo<x>]
23217                 case 58 /* ColonToken */: // foo<x>:
23218                 case 26 /* SemicolonToken */: // foo<x>;
23219                 case 57 /* QuestionToken */: // foo<x>?
23220                 case 34 /* EqualsEqualsToken */: // foo<x> ==
23221                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
23222                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
23223                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
23224                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
23225                 case 56 /* BarBarToken */: // foo<x> ||
23226                 case 60 /* QuestionQuestionToken */: // foo<x> ??
23227                 case 52 /* CaretToken */: // foo<x> ^
23228                 case 50 /* AmpersandToken */: // foo<x> &
23229                 case 51 /* BarToken */: // foo<x> |
23230                 case 19 /* CloseBraceToken */: // foo<x> }
23231                 case 1 /* EndOfFileToken */: // foo<x>
23232                     // these cases can't legally follow a type arg list.  However, they're not legal
23233                     // expressions either.  The user is probably in the middle of a generic type. So
23234                     // treat it as such.
23235                     return true;
23236                 case 27 /* CommaToken */: // foo<x>,
23237                 case 18 /* OpenBraceToken */: // foo<x> {
23238                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
23239                 // as an invocation expression.  Instead, we want to parse out the expression
23240                 // in isolation from the type arguments.
23241                 // falls through
23242                 default:
23243                     // Anything else treat as an expression.
23244                     return false;
23245             }
23246         }
23247         function parsePrimaryExpression() {
23248             switch (token()) {
23249                 case 8 /* NumericLiteral */:
23250                 case 9 /* BigIntLiteral */:
23251                 case 10 /* StringLiteral */:
23252                 case 14 /* NoSubstitutionTemplateLiteral */:
23253                     return parseLiteralNode();
23254                 case 104 /* ThisKeyword */:
23255                 case 102 /* SuperKeyword */:
23256                 case 100 /* NullKeyword */:
23257                 case 106 /* TrueKeyword */:
23258                 case 91 /* FalseKeyword */:
23259                     return parseTokenNode();
23260                 case 20 /* OpenParenToken */:
23261                     return parseParenthesizedExpression();
23262                 case 22 /* OpenBracketToken */:
23263                     return parseArrayLiteralExpression();
23264                 case 18 /* OpenBraceToken */:
23265                     return parseObjectLiteralExpression();
23266                 case 126 /* AsyncKeyword */:
23267                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
23268                     // If we encounter `async [no LineTerminator here] function` then this is an async
23269                     // function; otherwise, its an identifier.
23270                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
23271                         break;
23272                     }
23273                     return parseFunctionExpression();
23274                 case 80 /* ClassKeyword */:
23275                     return parseClassExpression();
23276                 case 94 /* FunctionKeyword */:
23277                     return parseFunctionExpression();
23278                 case 99 /* NewKeyword */:
23279                     return parseNewExpressionOrNewDotTarget();
23280                 case 43 /* SlashToken */:
23281                 case 67 /* SlashEqualsToken */:
23282                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
23283                         return parseLiteralNode();
23284                     }
23285                     break;
23286                 case 15 /* TemplateHead */:
23287                     return parseTemplateExpression(/* isTaggedTemplate */ false);
23288             }
23289             return parseIdentifier(ts.Diagnostics.Expression_expected);
23290         }
23291         function parseParenthesizedExpression() {
23292             var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
23293             parseExpected(20 /* OpenParenToken */);
23294             node.expression = allowInAnd(parseExpression);
23295             parseExpected(21 /* CloseParenToken */);
23296             return finishNode(node);
23297         }
23298         function parseSpreadElement() {
23299             var node = createNode(213 /* SpreadElement */);
23300             parseExpected(25 /* DotDotDotToken */);
23301             node.expression = parseAssignmentExpressionOrHigher();
23302             return finishNode(node);
23303         }
23304         function parseArgumentOrArrayLiteralElement() {
23305             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
23306                 token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
23307                     parseAssignmentExpressionOrHigher();
23308         }
23309         function parseArgumentExpression() {
23310             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
23311         }
23312         function parseArrayLiteralExpression() {
23313             var node = createNode(192 /* ArrayLiteralExpression */);
23314             parseExpected(22 /* OpenBracketToken */);
23315             if (scanner.hasPrecedingLineBreak()) {
23316                 node.multiLine = true;
23317             }
23318             node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
23319             parseExpected(23 /* CloseBracketToken */);
23320             return finishNode(node);
23321         }
23322         function parseObjectLiteralElement() {
23323             var node = createNodeWithJSDoc(0 /* Unknown */);
23324             if (parseOptionalToken(25 /* DotDotDotToken */)) {
23325                 node.kind = 283 /* SpreadAssignment */;
23326                 node.expression = parseAssignmentExpressionOrHigher();
23327                 return finishNode(node);
23328             }
23329             node.decorators = parseDecorators();
23330             node.modifiers = parseModifiers();
23331             if (parseContextualModifier(131 /* GetKeyword */)) {
23332                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
23333             }
23334             if (parseContextualModifier(142 /* SetKeyword */)) {
23335                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
23336             }
23337             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23338             var tokenIsIdentifier = isIdentifier();
23339             node.name = parsePropertyName();
23340             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
23341             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
23342             node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
23343             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
23344                 return parseMethodDeclaration(node, asteriskToken);
23345             }
23346             // check if it is short-hand property assignment or normal property assignment
23347             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
23348             // CoverInitializedName[Yield] :
23349             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
23350             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
23351             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
23352             if (isShorthandPropertyAssignment) {
23353                 node.kind = 282 /* ShorthandPropertyAssignment */;
23354                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
23355                 if (equalsToken) {
23356                     node.equalsToken = equalsToken;
23357                     node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
23358                 }
23359             }
23360             else {
23361                 node.kind = 281 /* PropertyAssignment */;
23362                 parseExpected(58 /* ColonToken */);
23363                 node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
23364             }
23365             return finishNode(node);
23366         }
23367         function parseObjectLiteralExpression() {
23368             var node = createNode(193 /* ObjectLiteralExpression */);
23369             var openBracePosition = scanner.getTokenPos();
23370             parseExpected(18 /* OpenBraceToken */);
23371             if (scanner.hasPrecedingLineBreak()) {
23372                 node.multiLine = true;
23373             }
23374             node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
23375             if (!parseExpected(19 /* CloseBraceToken */)) {
23376                 var lastError = ts.lastOrUndefined(parseDiagnostics);
23377                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23378                     ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23379                 }
23380             }
23381             return finishNode(node);
23382         }
23383         function parseFunctionExpression() {
23384             // GeneratorExpression:
23385             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
23386             //
23387             // FunctionExpression:
23388             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
23389             var saveDecoratorContext = inDecoratorContext();
23390             if (saveDecoratorContext) {
23391                 setDecoratorContext(/*val*/ false);
23392             }
23393             var node = createNodeWithJSDoc(201 /* FunctionExpression */);
23394             node.modifiers = parseModifiers();
23395             parseExpected(94 /* FunctionKeyword */);
23396             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23397             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
23398             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
23399             node.name =
23400                 isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
23401                     isGenerator ? doInYieldContext(parseOptionalIdentifier) :
23402                         isAsync ? doInAwaitContext(parseOptionalIdentifier) :
23403                             parseOptionalIdentifier();
23404             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
23405             node.body = parseFunctionBlock(isGenerator | isAsync);
23406             if (saveDecoratorContext) {
23407                 setDecoratorContext(/*val*/ true);
23408             }
23409             return finishNode(node);
23410         }
23411         function parseOptionalIdentifier() {
23412             return isIdentifier() ? parseIdentifier() : undefined;
23413         }
23414         function parseNewExpressionOrNewDotTarget() {
23415             var fullStart = scanner.getStartPos();
23416             parseExpected(99 /* NewKeyword */);
23417             if (parseOptional(24 /* DotToken */)) {
23418                 var node_2 = createNode(219 /* MetaProperty */, fullStart);
23419                 node_2.keywordToken = 99 /* NewKeyword */;
23420                 node_2.name = parseIdentifierName();
23421                 return finishNode(node_2);
23422             }
23423             var expression = parsePrimaryExpression();
23424             var typeArguments;
23425             while (true) {
23426                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
23427                 typeArguments = tryParse(parseTypeArgumentsInExpression);
23428                 if (isTemplateStartOfTaggedTemplate()) {
23429                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
23430                     expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
23431                     typeArguments = undefined;
23432                 }
23433                 break;
23434             }
23435             var node = createNode(197 /* NewExpression */, fullStart);
23436             node.expression = expression;
23437             node.typeArguments = typeArguments;
23438             if (token() === 20 /* OpenParenToken */) {
23439                 node.arguments = parseArgumentList();
23440             }
23441             else if (node.typeArguments) {
23442                 parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
23443             }
23444             return finishNode(node);
23445         }
23446         // STATEMENTS
23447         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
23448             var node = createNode(223 /* Block */);
23449             var openBracePosition = scanner.getTokenPos();
23450             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
23451                 if (scanner.hasPrecedingLineBreak()) {
23452                     node.multiLine = true;
23453                 }
23454                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
23455                 if (!parseExpected(19 /* CloseBraceToken */)) {
23456                     var lastError = ts.lastOrUndefined(parseDiagnostics);
23457                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23458                         ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23459                     }
23460                 }
23461             }
23462             else {
23463                 node.statements = createMissingList();
23464             }
23465             return finishNode(node);
23466         }
23467         function parseFunctionBlock(flags, diagnosticMessage) {
23468             var savedYieldContext = inYieldContext();
23469             setYieldContext(!!(flags & 1 /* Yield */));
23470             var savedAwaitContext = inAwaitContext();
23471             setAwaitContext(!!(flags & 2 /* Await */));
23472             // We may be in a [Decorator] context when parsing a function expression or
23473             // arrow function. The body of the function is not in [Decorator] context.
23474             var saveDecoratorContext = inDecoratorContext();
23475             if (saveDecoratorContext) {
23476                 setDecoratorContext(/*val*/ false);
23477             }
23478             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
23479             if (saveDecoratorContext) {
23480                 setDecoratorContext(/*val*/ true);
23481             }
23482             setYieldContext(savedYieldContext);
23483             setAwaitContext(savedAwaitContext);
23484             return block;
23485         }
23486         function parseEmptyStatement() {
23487             var node = createNode(224 /* EmptyStatement */);
23488             parseExpected(26 /* SemicolonToken */);
23489             return finishNode(node);
23490         }
23491         function parseIfStatement() {
23492             var node = createNode(227 /* IfStatement */);
23493             parseExpected(95 /* IfKeyword */);
23494             parseExpected(20 /* OpenParenToken */);
23495             node.expression = allowInAnd(parseExpression);
23496             parseExpected(21 /* CloseParenToken */);
23497             node.thenStatement = parseStatement();
23498             node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
23499             return finishNode(node);
23500         }
23501         function parseDoStatement() {
23502             var node = createNode(228 /* DoStatement */);
23503             parseExpected(86 /* DoKeyword */);
23504             node.statement = parseStatement();
23505             parseExpected(111 /* WhileKeyword */);
23506             parseExpected(20 /* OpenParenToken */);
23507             node.expression = allowInAnd(parseExpression);
23508             parseExpected(21 /* CloseParenToken */);
23509             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
23510             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
23511             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
23512             //  do;while(0)x will have a semicolon inserted before x.
23513             parseOptional(26 /* SemicolonToken */);
23514             return finishNode(node);
23515         }
23516         function parseWhileStatement() {
23517             var node = createNode(229 /* WhileStatement */);
23518             parseExpected(111 /* WhileKeyword */);
23519             parseExpected(20 /* OpenParenToken */);
23520             node.expression = allowInAnd(parseExpression);
23521             parseExpected(21 /* CloseParenToken */);
23522             node.statement = parseStatement();
23523             return finishNode(node);
23524         }
23525         function parseForOrForInOrForOfStatement() {
23526             var pos = getNodePos();
23527             parseExpected(93 /* ForKeyword */);
23528             var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
23529             parseExpected(20 /* OpenParenToken */);
23530             var initializer;
23531             if (token() !== 26 /* SemicolonToken */) {
23532                 if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
23533                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
23534                 }
23535                 else {
23536                     initializer = disallowInAnd(parseExpression);
23537                 }
23538             }
23539             var forOrForInOrForOfStatement;
23540             if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
23541                 var forOfStatement = createNode(232 /* ForOfStatement */, pos);
23542                 forOfStatement.awaitModifier = awaitToken;
23543                 forOfStatement.initializer = initializer;
23544                 forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
23545                 parseExpected(21 /* CloseParenToken */);
23546                 forOrForInOrForOfStatement = forOfStatement;
23547             }
23548             else if (parseOptional(97 /* InKeyword */)) {
23549                 var forInStatement = createNode(231 /* ForInStatement */, pos);
23550                 forInStatement.initializer = initializer;
23551                 forInStatement.expression = allowInAnd(parseExpression);
23552                 parseExpected(21 /* CloseParenToken */);
23553                 forOrForInOrForOfStatement = forInStatement;
23554             }
23555             else {
23556                 var forStatement = createNode(230 /* ForStatement */, pos);
23557                 forStatement.initializer = initializer;
23558                 parseExpected(26 /* SemicolonToken */);
23559                 if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
23560                     forStatement.condition = allowInAnd(parseExpression);
23561                 }
23562                 parseExpected(26 /* SemicolonToken */);
23563                 if (token() !== 21 /* CloseParenToken */) {
23564                     forStatement.incrementor = allowInAnd(parseExpression);
23565                 }
23566                 parseExpected(21 /* CloseParenToken */);
23567                 forOrForInOrForOfStatement = forStatement;
23568             }
23569             forOrForInOrForOfStatement.statement = parseStatement();
23570             return finishNode(forOrForInOrForOfStatement);
23571         }
23572         function parseBreakOrContinueStatement(kind) {
23573             var node = createNode(kind);
23574             parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
23575             if (!canParseSemicolon()) {
23576                 node.label = parseIdentifier();
23577             }
23578             parseSemicolon();
23579             return finishNode(node);
23580         }
23581         function parseReturnStatement() {
23582             var node = createNode(235 /* ReturnStatement */);
23583             parseExpected(101 /* ReturnKeyword */);
23584             if (!canParseSemicolon()) {
23585                 node.expression = allowInAnd(parseExpression);
23586             }
23587             parseSemicolon();
23588             return finishNode(node);
23589         }
23590         function parseWithStatement() {
23591             var node = createNode(236 /* WithStatement */);
23592             parseExpected(112 /* WithKeyword */);
23593             parseExpected(20 /* OpenParenToken */);
23594             node.expression = allowInAnd(parseExpression);
23595             parseExpected(21 /* CloseParenToken */);
23596             node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
23597             return finishNode(node);
23598         }
23599         function parseCaseClause() {
23600             var node = createNode(277 /* CaseClause */);
23601             parseExpected(78 /* CaseKeyword */);
23602             node.expression = allowInAnd(parseExpression);
23603             parseExpected(58 /* ColonToken */);
23604             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23605             return finishNode(node);
23606         }
23607         function parseDefaultClause() {
23608             var node = createNode(278 /* DefaultClause */);
23609             parseExpected(84 /* DefaultKeyword */);
23610             parseExpected(58 /* ColonToken */);
23611             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23612             return finishNode(node);
23613         }
23614         function parseCaseOrDefaultClause() {
23615             return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
23616         }
23617         function parseSwitchStatement() {
23618             var node = createNode(237 /* SwitchStatement */);
23619             parseExpected(103 /* SwitchKeyword */);
23620             parseExpected(20 /* OpenParenToken */);
23621             node.expression = allowInAnd(parseExpression);
23622             parseExpected(21 /* CloseParenToken */);
23623             var caseBlock = createNode(251 /* CaseBlock */);
23624             parseExpected(18 /* OpenBraceToken */);
23625             caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
23626             parseExpected(19 /* CloseBraceToken */);
23627             node.caseBlock = finishNode(caseBlock);
23628             return finishNode(node);
23629         }
23630         function parseThrowStatement() {
23631             // ThrowStatement[Yield] :
23632             //      throw [no LineTerminator here]Expression[In, ?Yield];
23633             // Because of automatic semicolon insertion, we need to report error if this
23634             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
23635             // directly as that might consume an expression on the following line.
23636             // We just return 'undefined' in that case.  The actual error will be reported in the
23637             // grammar walker.
23638             var node = createNode(239 /* ThrowStatement */);
23639             parseExpected(105 /* ThrowKeyword */);
23640             node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
23641             parseSemicolon();
23642             return finishNode(node);
23643         }
23644         // TODO: Review for error recovery
23645         function parseTryStatement() {
23646             var node = createNode(240 /* TryStatement */);
23647             parseExpected(107 /* TryKeyword */);
23648             node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23649             node.catchClause = token() === 79 /* CatchKeyword */ ? parseCatchClause() : undefined;
23650             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
23651             // one out no matter what.
23652             if (!node.catchClause || token() === 92 /* FinallyKeyword */) {
23653                 parseExpected(92 /* FinallyKeyword */);
23654                 node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23655             }
23656             return finishNode(node);
23657         }
23658         function parseCatchClause() {
23659             var result = createNode(280 /* CatchClause */);
23660             parseExpected(79 /* CatchKeyword */);
23661             if (parseOptional(20 /* OpenParenToken */)) {
23662                 result.variableDeclaration = parseVariableDeclaration();
23663                 parseExpected(21 /* CloseParenToken */);
23664             }
23665             else {
23666                 // Keep shape of node to avoid degrading performance.
23667                 result.variableDeclaration = undefined;
23668             }
23669             result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
23670             return finishNode(result);
23671         }
23672         function parseDebuggerStatement() {
23673             var node = createNode(241 /* DebuggerStatement */);
23674             parseExpected(83 /* DebuggerKeyword */);
23675             parseSemicolon();
23676             return finishNode(node);
23677         }
23678         function parseExpressionOrLabeledStatement() {
23679             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
23680             // out an expression, seeing if it is identifier and then seeing if it is followed by
23681             // a colon.
23682             var node = createNodeWithJSDoc(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */);
23683             var expression = allowInAnd(parseExpression);
23684             if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
23685                 node.kind = 238 /* LabeledStatement */;
23686                 node.label = expression;
23687                 node.statement = parseStatement();
23688             }
23689             else {
23690                 node.kind = 226 /* ExpressionStatement */;
23691                 node.expression = expression;
23692                 parseSemicolon();
23693             }
23694             return finishNode(node);
23695         }
23696         function nextTokenIsIdentifierOrKeywordOnSameLine() {
23697             nextToken();
23698             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
23699         }
23700         function nextTokenIsClassKeywordOnSameLine() {
23701             nextToken();
23702             return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
23703         }
23704         function nextTokenIsFunctionKeywordOnSameLine() {
23705             nextToken();
23706             return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
23707         }
23708         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
23709             nextToken();
23710             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
23711         }
23712         function isDeclaration() {
23713             while (true) {
23714                 switch (token()) {
23715                     case 109 /* VarKeyword */:
23716                     case 115 /* LetKeyword */:
23717                     case 81 /* ConstKeyword */:
23718                     case 94 /* FunctionKeyword */:
23719                     case 80 /* ClassKeyword */:
23720                     case 88 /* EnumKeyword */:
23721                         return true;
23722                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
23723                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
23724                     // count on to parse out the respective declarations. For instance, we exploit this to say that
23725                     //
23726                     //    namespace n
23727                     //
23728                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
23729                     //
23730                     //    namespace
23731                     //    n
23732                     //
23733                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
23734                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
23735                     //
23736                     // *Note*: 'interface' is actually a strict mode reserved word. So while
23737                     //
23738                     //   "use strict"
23739                     //   interface
23740                     //   I {}
23741                     //
23742                     // could be legal, it would add complexity for very little gain.
23743                     case 114 /* InterfaceKeyword */:
23744                     case 145 /* TypeKeyword */:
23745                         return nextTokenIsIdentifierOnSameLine();
23746                     case 135 /* ModuleKeyword */:
23747                     case 136 /* NamespaceKeyword */:
23748                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
23749                     case 122 /* AbstractKeyword */:
23750                     case 126 /* AsyncKeyword */:
23751                     case 130 /* DeclareKeyword */:
23752                     case 117 /* PrivateKeyword */:
23753                     case 118 /* ProtectedKeyword */:
23754                     case 119 /* PublicKeyword */:
23755                     case 138 /* ReadonlyKeyword */:
23756                         nextToken();
23757                         // ASI takes effect for this modifier.
23758                         if (scanner.hasPrecedingLineBreak()) {
23759                             return false;
23760                         }
23761                         continue;
23762                     case 150 /* GlobalKeyword */:
23763                         nextToken();
23764                         return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
23765                     case 96 /* ImportKeyword */:
23766                         nextToken();
23767                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
23768                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
23769                     case 89 /* ExportKeyword */:
23770                         var currentToken_1 = nextToken();
23771                         if (currentToken_1 === 145 /* TypeKeyword */) {
23772                             currentToken_1 = lookAhead(nextToken);
23773                         }
23774                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
23775                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
23776                             currentToken_1 === 123 /* AsKeyword */) {
23777                             return true;
23778                         }
23779                         continue;
23780                     case 120 /* StaticKeyword */:
23781                         nextToken();
23782                         continue;
23783                     default:
23784                         return false;
23785                 }
23786             }
23787         }
23788         function isStartOfDeclaration() {
23789             return lookAhead(isDeclaration);
23790         }
23791         function isStartOfStatement() {
23792             switch (token()) {
23793                 case 59 /* AtToken */:
23794                 case 26 /* SemicolonToken */:
23795                 case 18 /* OpenBraceToken */:
23796                 case 109 /* VarKeyword */:
23797                 case 115 /* LetKeyword */:
23798                 case 94 /* FunctionKeyword */:
23799                 case 80 /* ClassKeyword */:
23800                 case 88 /* EnumKeyword */:
23801                 case 95 /* IfKeyword */:
23802                 case 86 /* DoKeyword */:
23803                 case 111 /* WhileKeyword */:
23804                 case 93 /* ForKeyword */:
23805                 case 82 /* ContinueKeyword */:
23806                 case 77 /* BreakKeyword */:
23807                 case 101 /* ReturnKeyword */:
23808                 case 112 /* WithKeyword */:
23809                 case 103 /* SwitchKeyword */:
23810                 case 105 /* ThrowKeyword */:
23811                 case 107 /* TryKeyword */:
23812                 case 83 /* DebuggerKeyword */:
23813                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
23814                 // however, we say they are here so that we may gracefully parse them and error later.
23815                 // falls through
23816                 case 79 /* CatchKeyword */:
23817                 case 92 /* FinallyKeyword */:
23818                     return true;
23819                 case 96 /* ImportKeyword */:
23820                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
23821                 case 81 /* ConstKeyword */:
23822                 case 89 /* ExportKeyword */:
23823                     return isStartOfDeclaration();
23824                 case 126 /* AsyncKeyword */:
23825                 case 130 /* DeclareKeyword */:
23826                 case 114 /* InterfaceKeyword */:
23827                 case 135 /* ModuleKeyword */:
23828                 case 136 /* NamespaceKeyword */:
23829                 case 145 /* TypeKeyword */:
23830                 case 150 /* GlobalKeyword */:
23831                     // When these don't start a declaration, they're an identifier in an expression statement
23832                     return true;
23833                 case 119 /* PublicKeyword */:
23834                 case 117 /* PrivateKeyword */:
23835                 case 118 /* ProtectedKeyword */:
23836                 case 120 /* StaticKeyword */:
23837                 case 138 /* ReadonlyKeyword */:
23838                     // When these don't start a declaration, they may be the start of a class member if an identifier
23839                     // immediately follows. Otherwise they're an identifier in an expression statement.
23840                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
23841                 default:
23842                     return isStartOfExpression();
23843             }
23844         }
23845         function nextTokenIsIdentifierOrStartOfDestructuring() {
23846             nextToken();
23847             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
23848         }
23849         function isLetDeclaration() {
23850             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
23851             // or [.
23852             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
23853         }
23854         function parseStatement() {
23855             switch (token()) {
23856                 case 26 /* SemicolonToken */:
23857                     return parseEmptyStatement();
23858                 case 18 /* OpenBraceToken */:
23859                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
23860                 case 109 /* VarKeyword */:
23861                     return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23862                 case 115 /* LetKeyword */:
23863                     if (isLetDeclaration()) {
23864                         return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23865                     }
23866                     break;
23867                 case 94 /* FunctionKeyword */:
23868                     return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
23869                 case 80 /* ClassKeyword */:
23870                     return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
23871                 case 95 /* IfKeyword */:
23872                     return parseIfStatement();
23873                 case 86 /* DoKeyword */:
23874                     return parseDoStatement();
23875                 case 111 /* WhileKeyword */:
23876                     return parseWhileStatement();
23877                 case 93 /* ForKeyword */:
23878                     return parseForOrForInOrForOfStatement();
23879                 case 82 /* ContinueKeyword */:
23880                     return parseBreakOrContinueStatement(233 /* ContinueStatement */);
23881                 case 77 /* BreakKeyword */:
23882                     return parseBreakOrContinueStatement(234 /* BreakStatement */);
23883                 case 101 /* ReturnKeyword */:
23884                     return parseReturnStatement();
23885                 case 112 /* WithKeyword */:
23886                     return parseWithStatement();
23887                 case 103 /* SwitchKeyword */:
23888                     return parseSwitchStatement();
23889                 case 105 /* ThrowKeyword */:
23890                     return parseThrowStatement();
23891                 case 107 /* TryKeyword */:
23892                 // Include 'catch' and 'finally' for error recovery.
23893                 // falls through
23894                 case 79 /* CatchKeyword */:
23895                 case 92 /* FinallyKeyword */:
23896                     return parseTryStatement();
23897                 case 83 /* DebuggerKeyword */:
23898                     return parseDebuggerStatement();
23899                 case 59 /* AtToken */:
23900                     return parseDeclaration();
23901                 case 126 /* AsyncKeyword */:
23902                 case 114 /* InterfaceKeyword */:
23903                 case 145 /* TypeKeyword */:
23904                 case 135 /* ModuleKeyword */:
23905                 case 136 /* NamespaceKeyword */:
23906                 case 130 /* DeclareKeyword */:
23907                 case 81 /* ConstKeyword */:
23908                 case 88 /* EnumKeyword */:
23909                 case 89 /* ExportKeyword */:
23910                 case 96 /* ImportKeyword */:
23911                 case 117 /* PrivateKeyword */:
23912                 case 118 /* ProtectedKeyword */:
23913                 case 119 /* PublicKeyword */:
23914                 case 122 /* AbstractKeyword */:
23915                 case 120 /* StaticKeyword */:
23916                 case 138 /* ReadonlyKeyword */:
23917                 case 150 /* GlobalKeyword */:
23918                     if (isStartOfDeclaration()) {
23919                         return parseDeclaration();
23920                     }
23921                     break;
23922             }
23923             return parseExpressionOrLabeledStatement();
23924         }
23925         function isDeclareModifier(modifier) {
23926             return modifier.kind === 130 /* DeclareKeyword */;
23927         }
23928         function parseDeclaration() {
23929             var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
23930             // `parseListElement` attempted to get the reused node at this position,
23931             // but the ambient context flag was not yet set, so the node appeared
23932             // not reusable in that context.
23933             var isAmbient = ts.some(modifiers, isDeclareModifier);
23934             if (isAmbient) {
23935                 var node_3 = tryReuseAmbientDeclaration();
23936                 if (node_3) {
23937                     return node_3;
23938                 }
23939             }
23940             var node = createNodeWithJSDoc(0 /* Unknown */);
23941             node.decorators = parseDecorators();
23942             node.modifiers = parseModifiers();
23943             if (isAmbient) {
23944                 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
23945                     var m = _a[_i];
23946                     m.flags |= 8388608 /* Ambient */;
23947                 }
23948                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
23949             }
23950             else {
23951                 return parseDeclarationWorker(node);
23952             }
23953         }
23954         function tryReuseAmbientDeclaration() {
23955             return doInsideOfContext(8388608 /* Ambient */, function () {
23956                 var node = currentNode(parsingContext);
23957                 if (node) {
23958                     return consumeNode(node);
23959                 }
23960             });
23961         }
23962         function parseDeclarationWorker(node) {
23963             switch (token()) {
23964                 case 109 /* VarKeyword */:
23965                 case 115 /* LetKeyword */:
23966                 case 81 /* ConstKeyword */:
23967                     return parseVariableStatement(node);
23968                 case 94 /* FunctionKeyword */:
23969                     return parseFunctionDeclaration(node);
23970                 case 80 /* ClassKeyword */:
23971                     return parseClassDeclaration(node);
23972                 case 114 /* InterfaceKeyword */:
23973                     return parseInterfaceDeclaration(node);
23974                 case 145 /* TypeKeyword */:
23975                     return parseTypeAliasDeclaration(node);
23976                 case 88 /* EnumKeyword */:
23977                     return parseEnumDeclaration(node);
23978                 case 150 /* GlobalKeyword */:
23979                 case 135 /* ModuleKeyword */:
23980                 case 136 /* NamespaceKeyword */:
23981                     return parseModuleDeclaration(node);
23982                 case 96 /* ImportKeyword */:
23983                     return parseImportDeclarationOrImportEqualsDeclaration(node);
23984                 case 89 /* ExportKeyword */:
23985                     nextToken();
23986                     switch (token()) {
23987                         case 84 /* DefaultKeyword */:
23988                         case 62 /* EqualsToken */:
23989                             return parseExportAssignment(node);
23990                         case 123 /* AsKeyword */:
23991                             return parseNamespaceExportDeclaration(node);
23992                         default:
23993                             return parseExportDeclaration(node);
23994                     }
23995                 default:
23996                     if (node.decorators || node.modifiers) {
23997                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
23998                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
23999                         var missing = createMissingNode(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24000                         missing.pos = node.pos;
24001                         missing.decorators = node.decorators;
24002                         missing.modifiers = node.modifiers;
24003                         return finishNode(missing);
24004                     }
24005                     return undefined; // TODO: GH#18217
24006             }
24007         }
24008         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
24009             nextToken();
24010             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
24011         }
24012         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
24013             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
24014                 parseSemicolon();
24015                 return;
24016             }
24017             return parseFunctionBlock(flags, diagnosticMessage);
24018         }
24019         // DECLARATIONS
24020         function parseArrayBindingElement() {
24021             if (token() === 27 /* CommaToken */) {
24022                 return createNode(215 /* OmittedExpression */);
24023             }
24024             var node = createNode(191 /* BindingElement */);
24025             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24026             node.name = parseIdentifierOrPattern();
24027             node.initializer = parseInitializer();
24028             return finishNode(node);
24029         }
24030         function parseObjectBindingElement() {
24031             var node = createNode(191 /* BindingElement */);
24032             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24033             var tokenIsIdentifier = isIdentifier();
24034             var propertyName = parsePropertyName();
24035             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
24036                 node.name = propertyName;
24037             }
24038             else {
24039                 parseExpected(58 /* ColonToken */);
24040                 node.propertyName = propertyName;
24041                 node.name = parseIdentifierOrPattern();
24042             }
24043             node.initializer = parseInitializer();
24044             return finishNode(node);
24045         }
24046         function parseObjectBindingPattern() {
24047             var node = createNode(189 /* ObjectBindingPattern */);
24048             parseExpected(18 /* OpenBraceToken */);
24049             node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
24050             parseExpected(19 /* CloseBraceToken */);
24051             return finishNode(node);
24052         }
24053         function parseArrayBindingPattern() {
24054             var node = createNode(190 /* ArrayBindingPattern */);
24055             parseExpected(22 /* OpenBracketToken */);
24056             node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
24057             parseExpected(23 /* CloseBracketToken */);
24058             return finishNode(node);
24059         }
24060         function isIdentifierOrPrivateIdentifierOrPattern() {
24061             return token() === 18 /* OpenBraceToken */
24062                 || token() === 22 /* OpenBracketToken */
24063                 || token() === 76 /* PrivateIdentifier */
24064                 || isIdentifier();
24065         }
24066         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
24067             if (token() === 22 /* OpenBracketToken */) {
24068                 return parseArrayBindingPattern();
24069             }
24070             if (token() === 18 /* OpenBraceToken */) {
24071                 return parseObjectBindingPattern();
24072             }
24073             return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
24074         }
24075         function parseVariableDeclarationAllowExclamation() {
24076             return parseVariableDeclaration(/*allowExclamation*/ true);
24077         }
24078         function parseVariableDeclaration(allowExclamation) {
24079             var node = createNode(242 /* VariableDeclaration */);
24080             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
24081             if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
24082                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24083                 node.exclamationToken = parseTokenNode();
24084             }
24085             node.type = parseTypeAnnotation();
24086             if (!isInOrOfKeyword(token())) {
24087                 node.initializer = parseInitializer();
24088             }
24089             return finishNode(node);
24090         }
24091         function parseVariableDeclarationList(inForStatementInitializer) {
24092             var node = createNode(243 /* VariableDeclarationList */);
24093             switch (token()) {
24094                 case 109 /* VarKeyword */:
24095                     break;
24096                 case 115 /* LetKeyword */:
24097                     node.flags |= 1 /* Let */;
24098                     break;
24099                 case 81 /* ConstKeyword */:
24100                     node.flags |= 2 /* Const */;
24101                     break;
24102                 default:
24103                     ts.Debug.fail();
24104             }
24105             nextToken();
24106             // The user may have written the following:
24107             //
24108             //    for (let of X) { }
24109             //
24110             // In this case, we want to parse an empty declaration list, and then parse 'of'
24111             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
24112             // So we need to look ahead to determine if 'of' should be treated as a keyword in
24113             // this context.
24114             // The checker will then give an error that there is an empty declaration list.
24115             if (token() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
24116                 node.declarations = createMissingList();
24117             }
24118             else {
24119                 var savedDisallowIn = inDisallowInContext();
24120                 setDisallowInContext(inForStatementInitializer);
24121                 node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
24122                 setDisallowInContext(savedDisallowIn);
24123             }
24124             return finishNode(node);
24125         }
24126         function canFollowContextualOfKeyword() {
24127             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
24128         }
24129         function parseVariableStatement(node) {
24130             node.kind = 225 /* VariableStatement */;
24131             node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
24132             parseSemicolon();
24133             return finishNode(node);
24134         }
24135         function parseFunctionDeclaration(node) {
24136             node.kind = 244 /* FunctionDeclaration */;
24137             parseExpected(94 /* FunctionKeyword */);
24138             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24139             node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
24140             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
24141             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24142             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24143             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
24144             return finishNode(node);
24145         }
24146         function parseConstructorName() {
24147             if (token() === 129 /* ConstructorKeyword */) {
24148                 return parseExpected(129 /* ConstructorKeyword */);
24149             }
24150             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
24151                 return tryParse(function () {
24152                     var literalNode = parseLiteralNode();
24153                     return literalNode.text === "constructor" ? literalNode : undefined;
24154                 });
24155             }
24156         }
24157         function tryParseConstructorDeclaration(node) {
24158             return tryParse(function () {
24159                 if (parseConstructorName()) {
24160                     node.kind = 162 /* Constructor */;
24161                     fillSignature(58 /* ColonToken */, 0 /* None */, node);
24162                     node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
24163                     return finishNode(node);
24164                 }
24165             });
24166         }
24167         function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
24168             node.kind = 161 /* MethodDeclaration */;
24169             node.asteriskToken = asteriskToken;
24170             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
24171             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24172             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24173             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
24174             return finishNode(node);
24175         }
24176         function parsePropertyDeclaration(node) {
24177             node.kind = 159 /* PropertyDeclaration */;
24178             if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24179                 node.exclamationToken = parseTokenNode();
24180             }
24181             node.type = parseTypeAnnotation();
24182             node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
24183             parseSemicolon();
24184             return finishNode(node);
24185         }
24186         function parsePropertyOrMethodDeclaration(node) {
24187             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24188             node.name = parsePropertyName();
24189             // Note: this is not legal as per the grammar.  But we allow it in the parser and
24190             // report an error in the grammar checker.
24191             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
24192             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
24193                 return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
24194             }
24195             return parsePropertyDeclaration(node);
24196         }
24197         function parseAccessorDeclaration(node, kind) {
24198             node.kind = kind;
24199             node.name = parsePropertyName();
24200             fillSignature(58 /* ColonToken */, 0 /* None */, node);
24201             node.body = parseFunctionBlockOrSemicolon(0 /* None */);
24202             return finishNode(node);
24203         }
24204         function isClassMemberStart() {
24205             var idToken;
24206             if (token() === 59 /* AtToken */) {
24207                 return true;
24208             }
24209             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
24210             while (ts.isModifierKind(token())) {
24211                 idToken = token();
24212                 // If the idToken is a class modifier (protected, private, public, and static), it is
24213                 // certain that we are starting to parse class member. This allows better error recovery
24214                 // Example:
24215                 //      public foo() ...     // true
24216                 //      public @dec blah ... // true; we will then report an error later
24217                 //      export public ...    // true; we will then report an error later
24218                 if (ts.isClassMemberModifier(idToken)) {
24219                     return true;
24220                 }
24221                 nextToken();
24222             }
24223             if (token() === 41 /* AsteriskToken */) {
24224                 return true;
24225             }
24226             // Try to get the first property-like token following all modifiers.
24227             // This can either be an identifier or the 'get' or 'set' keywords.
24228             if (isLiteralPropertyName()) {
24229                 idToken = token();
24230                 nextToken();
24231             }
24232             // Index signatures and computed properties are class members; we can parse.
24233             if (token() === 22 /* OpenBracketToken */) {
24234                 return true;
24235             }
24236             // If we were able to get any potential identifier...
24237             if (idToken !== undefined) {
24238                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
24239                 if (!ts.isKeyword(idToken) || idToken === 142 /* SetKeyword */ || idToken === 131 /* GetKeyword */) {
24240                     return true;
24241                 }
24242                 // If it *is* a keyword, but not an accessor, check a little farther along
24243                 // to see if it should actually be parsed as a class member.
24244                 switch (token()) {
24245                     case 20 /* OpenParenToken */: // Method declaration
24246                     case 29 /* LessThanToken */: // Generic Method declaration
24247                     case 53 /* ExclamationToken */: // Non-null assertion on property name
24248                     case 58 /* ColonToken */: // Type Annotation for declaration
24249                     case 62 /* EqualsToken */: // Initializer for declaration
24250                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
24251                         return true;
24252                     default:
24253                         // Covers
24254                         //  - Semicolons     (declaration termination)
24255                         //  - Closing braces (end-of-class, must be declaration)
24256                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
24257                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
24258                         return canParseSemicolon();
24259                 }
24260             }
24261             return false;
24262         }
24263         function parseDecorators() {
24264             var list;
24265             var listPos = getNodePos();
24266             while (true) {
24267                 var decoratorStart = getNodePos();
24268                 if (!parseOptional(59 /* AtToken */)) {
24269                     break;
24270                 }
24271                 var decorator = createNode(157 /* Decorator */, decoratorStart);
24272                 decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
24273                 finishNode(decorator);
24274                 (list || (list = [])).push(decorator);
24275             }
24276             return list && createNodeArray(list, listPos);
24277         }
24278         /*
24279          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
24280          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
24281          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
24282          *
24283          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
24284          */
24285         function parseModifiers(permitInvalidConstAsModifier) {
24286             var list;
24287             var listPos = getNodePos();
24288             while (true) {
24289                 var modifierStart = scanner.getStartPos();
24290                 var modifierKind = token();
24291                 if (token() === 81 /* ConstKeyword */ && permitInvalidConstAsModifier) {
24292                     // We need to ensure that any subsequent modifiers appear on the same line
24293                     // so that when 'const' is a standalone declaration, we don't issue an error.
24294                     if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
24295                         break;
24296                     }
24297                 }
24298                 else {
24299                     if (!parseAnyContextualModifier()) {
24300                         break;
24301                     }
24302                 }
24303                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24304                 (list || (list = [])).push(modifier);
24305             }
24306             return list && createNodeArray(list, listPos);
24307         }
24308         function parseModifiersForArrowFunction() {
24309             var modifiers;
24310             if (token() === 126 /* AsyncKeyword */) {
24311                 var modifierStart = scanner.getStartPos();
24312                 var modifierKind = token();
24313                 nextToken();
24314                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24315                 modifiers = createNodeArray([modifier], modifierStart);
24316             }
24317             return modifiers;
24318         }
24319         function parseClassElement() {
24320             if (token() === 26 /* SemicolonToken */) {
24321                 var result = createNode(222 /* SemicolonClassElement */);
24322                 nextToken();
24323                 return finishNode(result);
24324             }
24325             var node = createNodeWithJSDoc(0 /* Unknown */);
24326             node.decorators = parseDecorators();
24327             node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
24328             if (parseContextualModifier(131 /* GetKeyword */)) {
24329                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
24330             }
24331             if (parseContextualModifier(142 /* SetKeyword */)) {
24332                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
24333             }
24334             if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
24335                 var constructorDeclaration = tryParseConstructorDeclaration(node);
24336                 if (constructorDeclaration) {
24337                     return constructorDeclaration;
24338                 }
24339             }
24340             if (isIndexSignature()) {
24341                 return parseIndexSignatureDeclaration(node);
24342             }
24343             // It is very important that we check this *after* checking indexers because
24344             // the [ token can start an index signature or a computed property name
24345             if (ts.tokenIsIdentifierOrKeyword(token()) ||
24346                 token() === 10 /* StringLiteral */ ||
24347                 token() === 8 /* NumericLiteral */ ||
24348                 token() === 41 /* AsteriskToken */ ||
24349                 token() === 22 /* OpenBracketToken */) {
24350                 var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
24351                 if (isAmbient) {
24352                     for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
24353                         var m = _a[_i];
24354                         m.flags |= 8388608 /* Ambient */;
24355                     }
24356                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
24357                 }
24358                 else {
24359                     return parsePropertyOrMethodDeclaration(node);
24360                 }
24361             }
24362             if (node.decorators || node.modifiers) {
24363                 // treat this as a property declaration with a missing name.
24364                 node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24365                 return parsePropertyDeclaration(node);
24366             }
24367             // 'isClassMemberStart' should have hinted not to attempt parsing.
24368             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
24369         }
24370         function parseClassExpression() {
24371             return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 214 /* ClassExpression */);
24372         }
24373         function parseClassDeclaration(node) {
24374             return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
24375         }
24376         function parseClassDeclarationOrExpression(node, kind) {
24377             node.kind = kind;
24378             parseExpected(80 /* ClassKeyword */);
24379             node.name = parseNameOfClassDeclarationOrExpression();
24380             node.typeParameters = parseTypeParameters();
24381             node.heritageClauses = parseHeritageClauses();
24382             if (parseExpected(18 /* OpenBraceToken */)) {
24383                 // ClassTail[Yield,Await] : (Modified) See 14.5
24384                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24385                 node.members = parseClassMembers();
24386                 parseExpected(19 /* CloseBraceToken */);
24387             }
24388             else {
24389                 node.members = createMissingList();
24390             }
24391             return finishNode(node);
24392         }
24393         function parseNameOfClassDeclarationOrExpression() {
24394             // implements is a future reserved word so
24395             // 'class implements' might mean either
24396             // - class expression with omitted name, 'implements' starts heritage clause
24397             // - class with name 'implements'
24398             // 'isImplementsClause' helps to disambiguate between these two cases
24399             return isIdentifier() && !isImplementsClause()
24400                 ? parseIdentifier()
24401                 : undefined;
24402         }
24403         function isImplementsClause() {
24404             return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
24405         }
24406         function parseHeritageClauses() {
24407             // ClassTail[Yield,Await] : (Modified) See 14.5
24408             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24409             if (isHeritageClause()) {
24410                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
24411             }
24412             return undefined;
24413         }
24414         function parseHeritageClause() {
24415             var tok = token();
24416             ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
24417             var node = createNode(279 /* HeritageClause */);
24418             node.token = tok;
24419             nextToken();
24420             node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
24421             return finishNode(node);
24422         }
24423         function parseExpressionWithTypeArguments() {
24424             var node = createNode(216 /* ExpressionWithTypeArguments */);
24425             node.expression = parseLeftHandSideExpressionOrHigher();
24426             node.typeArguments = tryParseTypeArguments();
24427             return finishNode(node);
24428         }
24429         function tryParseTypeArguments() {
24430             return token() === 29 /* LessThanToken */ ?
24431                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
24432         }
24433         function isHeritageClause() {
24434             return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
24435         }
24436         function parseClassMembers() {
24437             return parseList(5 /* ClassMembers */, parseClassElement);
24438         }
24439         function parseInterfaceDeclaration(node) {
24440             node.kind = 246 /* InterfaceDeclaration */;
24441             parseExpected(114 /* InterfaceKeyword */);
24442             node.name = parseIdentifier();
24443             node.typeParameters = parseTypeParameters();
24444             node.heritageClauses = parseHeritageClauses();
24445             node.members = parseObjectTypeMembers();
24446             return finishNode(node);
24447         }
24448         function parseTypeAliasDeclaration(node) {
24449             node.kind = 247 /* TypeAliasDeclaration */;
24450             parseExpected(145 /* TypeKeyword */);
24451             node.name = parseIdentifier();
24452             node.typeParameters = parseTypeParameters();
24453             parseExpected(62 /* EqualsToken */);
24454             node.type = parseType();
24455             parseSemicolon();
24456             return finishNode(node);
24457         }
24458         // In an ambient declaration, the grammar only allows integer literals as initializers.
24459         // In a non-ambient declaration, the grammar allows uninitialized members only in a
24460         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
24461         // or any time an integer literal initializer is encountered.
24462         function parseEnumMember() {
24463             var node = createNodeWithJSDoc(284 /* EnumMember */);
24464             node.name = parsePropertyName();
24465             node.initializer = allowInAnd(parseInitializer);
24466             return finishNode(node);
24467         }
24468         function parseEnumDeclaration(node) {
24469             node.kind = 248 /* EnumDeclaration */;
24470             parseExpected(88 /* EnumKeyword */);
24471             node.name = parseIdentifier();
24472             if (parseExpected(18 /* OpenBraceToken */)) {
24473                 node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
24474                 parseExpected(19 /* CloseBraceToken */);
24475             }
24476             else {
24477                 node.members = createMissingList();
24478             }
24479             return finishNode(node);
24480         }
24481         function parseModuleBlock() {
24482             var node = createNode(250 /* ModuleBlock */);
24483             if (parseExpected(18 /* OpenBraceToken */)) {
24484                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
24485                 parseExpected(19 /* CloseBraceToken */);
24486             }
24487             else {
24488                 node.statements = createMissingList();
24489             }
24490             return finishNode(node);
24491         }
24492         function parseModuleOrNamespaceDeclaration(node, flags) {
24493             node.kind = 249 /* ModuleDeclaration */;
24494             // If we are parsing a dotted namespace name, we want to
24495             // propagate the 'Namespace' flag across the names if set.
24496             var namespaceFlag = flags & 16 /* Namespace */;
24497             node.flags |= flags;
24498             node.name = parseIdentifier();
24499             node.body = parseOptional(24 /* DotToken */)
24500                 ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
24501                 : parseModuleBlock();
24502             return finishNode(node);
24503         }
24504         function parseAmbientExternalModuleDeclaration(node) {
24505             node.kind = 249 /* ModuleDeclaration */;
24506             if (token() === 150 /* GlobalKeyword */) {
24507                 // parse 'global' as name of global scope augmentation
24508                 node.name = parseIdentifier();
24509                 node.flags |= 1024 /* GlobalAugmentation */;
24510             }
24511             else {
24512                 node.name = parseLiteralNode();
24513                 node.name.text = internIdentifier(node.name.text);
24514             }
24515             if (token() === 18 /* OpenBraceToken */) {
24516                 node.body = parseModuleBlock();
24517             }
24518             else {
24519                 parseSemicolon();
24520             }
24521             return finishNode(node);
24522         }
24523         function parseModuleDeclaration(node) {
24524             var flags = 0;
24525             if (token() === 150 /* GlobalKeyword */) {
24526                 // global augmentation
24527                 return parseAmbientExternalModuleDeclaration(node);
24528             }
24529             else if (parseOptional(136 /* NamespaceKeyword */)) {
24530                 flags |= 16 /* Namespace */;
24531             }
24532             else {
24533                 parseExpected(135 /* ModuleKeyword */);
24534                 if (token() === 10 /* StringLiteral */) {
24535                     return parseAmbientExternalModuleDeclaration(node);
24536                 }
24537             }
24538             return parseModuleOrNamespaceDeclaration(node, flags);
24539         }
24540         function isExternalModuleReference() {
24541             return token() === 139 /* RequireKeyword */ &&
24542                 lookAhead(nextTokenIsOpenParen);
24543         }
24544         function nextTokenIsOpenParen() {
24545             return nextToken() === 20 /* OpenParenToken */;
24546         }
24547         function nextTokenIsSlash() {
24548             return nextToken() === 43 /* SlashToken */;
24549         }
24550         function parseNamespaceExportDeclaration(node) {
24551             node.kind = 252 /* NamespaceExportDeclaration */;
24552             parseExpected(123 /* AsKeyword */);
24553             parseExpected(136 /* NamespaceKeyword */);
24554             node.name = parseIdentifier();
24555             parseSemicolon();
24556             return finishNode(node);
24557         }
24558         function parseImportDeclarationOrImportEqualsDeclaration(node) {
24559             parseExpected(96 /* ImportKeyword */);
24560             var afterImportPos = scanner.getStartPos();
24561             var identifier;
24562             if (isIdentifier()) {
24563                 identifier = parseIdentifier();
24564             }
24565             var isTypeOnly = false;
24566             if (token() !== 149 /* FromKeyword */ &&
24567                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
24568                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
24569                 isTypeOnly = true;
24570                 identifier = isIdentifier() ? parseIdentifier() : undefined;
24571             }
24572             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
24573                 return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
24574             }
24575             // Import statement
24576             node.kind = 254 /* ImportDeclaration */;
24577             // ImportDeclaration:
24578             //  import ImportClause from ModuleSpecifier ;
24579             //  import ModuleSpecifier;
24580             if (identifier || // import id
24581                 token() === 41 /* AsteriskToken */ || // import *
24582                 token() === 18 /* OpenBraceToken */ // import {
24583             ) {
24584                 node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
24585                 parseExpected(149 /* FromKeyword */);
24586             }
24587             node.moduleSpecifier = parseModuleSpecifier();
24588             parseSemicolon();
24589             return finishNode(node);
24590         }
24591         function tokenAfterImportDefinitelyProducesImportDeclaration() {
24592             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
24593         }
24594         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
24595             // In `import id ___`, the current token decides whether to produce
24596             // an ImportDeclaration or ImportEqualsDeclaration.
24597             return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
24598         }
24599         function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
24600             node.kind = 253 /* ImportEqualsDeclaration */;
24601             node.name = identifier;
24602             parseExpected(62 /* EqualsToken */);
24603             node.moduleReference = parseModuleReference();
24604             parseSemicolon();
24605             var finished = finishNode(node);
24606             if (isTypeOnly) {
24607                 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
24608             }
24609             return finished;
24610         }
24611         function parseImportClause(identifier, fullStart, isTypeOnly) {
24612             // ImportClause:
24613             //  ImportedDefaultBinding
24614             //  NameSpaceImport
24615             //  NamedImports
24616             //  ImportedDefaultBinding, NameSpaceImport
24617             //  ImportedDefaultBinding, NamedImports
24618             var importClause = createNode(255 /* ImportClause */, fullStart);
24619             importClause.isTypeOnly = isTypeOnly;
24620             if (identifier) {
24621                 // ImportedDefaultBinding:
24622                 //  ImportedBinding
24623                 importClause.name = identifier;
24624             }
24625             // If there was no default import or if there is comma token after default import
24626             // parse namespace or named imports
24627             if (!importClause.name ||
24628                 parseOptional(27 /* CommaToken */)) {
24629                 importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
24630             }
24631             return finishNode(importClause);
24632         }
24633         function parseModuleReference() {
24634             return isExternalModuleReference()
24635                 ? parseExternalModuleReference()
24636                 : parseEntityName(/*allowReservedWords*/ false);
24637         }
24638         function parseExternalModuleReference() {
24639             var node = createNode(265 /* ExternalModuleReference */);
24640             parseExpected(139 /* RequireKeyword */);
24641             parseExpected(20 /* OpenParenToken */);
24642             node.expression = parseModuleSpecifier();
24643             parseExpected(21 /* CloseParenToken */);
24644             return finishNode(node);
24645         }
24646         function parseModuleSpecifier() {
24647             if (token() === 10 /* StringLiteral */) {
24648                 var result = parseLiteralNode();
24649                 result.text = internIdentifier(result.text);
24650                 return result;
24651             }
24652             else {
24653                 // We allow arbitrary expressions here, even though the grammar only allows string
24654                 // literals.  We check to ensure that it is only a string literal later in the grammar
24655                 // check pass.
24656                 return parseExpression();
24657             }
24658         }
24659         function parseNamespaceImport() {
24660             // NameSpaceImport:
24661             //  * as ImportedBinding
24662             var namespaceImport = createNode(256 /* NamespaceImport */);
24663             parseExpected(41 /* AsteriskToken */);
24664             parseExpected(123 /* AsKeyword */);
24665             namespaceImport.name = parseIdentifier();
24666             return finishNode(namespaceImport);
24667         }
24668         function parseNamedImportsOrExports(kind) {
24669             var node = createNode(kind);
24670             // NamedImports:
24671             //  { }
24672             //  { ImportsList }
24673             //  { ImportsList, }
24674             // ImportsList:
24675             //  ImportSpecifier
24676             //  ImportsList, ImportSpecifier
24677             node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
24678             return finishNode(node);
24679         }
24680         function parseExportSpecifier() {
24681             return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
24682         }
24683         function parseImportSpecifier() {
24684             return parseImportOrExportSpecifier(258 /* ImportSpecifier */);
24685         }
24686         function parseImportOrExportSpecifier(kind) {
24687             var node = createNode(kind);
24688             // ImportSpecifier:
24689             //   BindingIdentifier
24690             //   IdentifierName as BindingIdentifier
24691             // ExportSpecifier:
24692             //   IdentifierName
24693             //   IdentifierName as IdentifierName
24694             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24695             var checkIdentifierStart = scanner.getTokenPos();
24696             var checkIdentifierEnd = scanner.getTextPos();
24697             var identifierName = parseIdentifierName();
24698             if (token() === 123 /* AsKeyword */) {
24699                 node.propertyName = identifierName;
24700                 parseExpected(123 /* AsKeyword */);
24701                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24702                 checkIdentifierStart = scanner.getTokenPos();
24703                 checkIdentifierEnd = scanner.getTextPos();
24704                 node.name = parseIdentifierName();
24705             }
24706             else {
24707                 node.name = identifierName;
24708             }
24709             if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
24710                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
24711             }
24712             return finishNode(node);
24713         }
24714         function parseNamespaceExport(pos) {
24715             var node = createNode(262 /* NamespaceExport */, pos);
24716             node.name = parseIdentifier();
24717             return finishNode(node);
24718         }
24719         function parseExportDeclaration(node) {
24720             node.kind = 260 /* ExportDeclaration */;
24721             node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
24722             var namespaceExportPos = scanner.getStartPos();
24723             if (parseOptional(41 /* AsteriskToken */)) {
24724                 if (parseOptional(123 /* AsKeyword */)) {
24725                     node.exportClause = parseNamespaceExport(namespaceExportPos);
24726                 }
24727                 parseExpected(149 /* FromKeyword */);
24728                 node.moduleSpecifier = parseModuleSpecifier();
24729             }
24730             else {
24731                 node.exportClause = parseNamedImportsOrExports(261 /* NamedExports */);
24732                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
24733                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
24734                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
24735                 if (token() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
24736                     parseExpected(149 /* FromKeyword */);
24737                     node.moduleSpecifier = parseModuleSpecifier();
24738                 }
24739             }
24740             parseSemicolon();
24741             return finishNode(node);
24742         }
24743         function parseExportAssignment(node) {
24744             node.kind = 259 /* ExportAssignment */;
24745             if (parseOptional(62 /* EqualsToken */)) {
24746                 node.isExportEquals = true;
24747             }
24748             else {
24749                 parseExpected(84 /* DefaultKeyword */);
24750             }
24751             node.expression = parseAssignmentExpressionOrHigher();
24752             parseSemicolon();
24753             return finishNode(node);
24754         }
24755         function setExternalModuleIndicator(sourceFile) {
24756             // Try to use the first top-level import/export when available, then
24757             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
24758             sourceFile.externalModuleIndicator =
24759                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
24760                     getImportMetaIfNecessary(sourceFile);
24761         }
24762         function isAnExternalModuleIndicatorNode(node) {
24763             return hasModifierOfKind(node, 89 /* ExportKeyword */)
24764                 || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
24765                 || node.kind === 254 /* ImportDeclaration */
24766                 || node.kind === 259 /* ExportAssignment */
24767                 || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
24768         }
24769         function getImportMetaIfNecessary(sourceFile) {
24770             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
24771                 walkTreeForExternalModuleIndicators(sourceFile) :
24772                 undefined;
24773         }
24774         function walkTreeForExternalModuleIndicators(node) {
24775             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
24776         }
24777         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
24778         function hasModifierOfKind(node, kind) {
24779             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
24780         }
24781         function isImportMeta(node) {
24782             return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
24783         }
24784         var ParsingContext;
24785         (function (ParsingContext) {
24786             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
24787             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
24788             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
24789             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
24790             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
24791             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
24792             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
24793             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
24794             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
24795             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
24796             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
24797             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
24798             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
24799             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
24800             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
24801             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
24802             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
24803             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
24804             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
24805             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
24806             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
24807             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
24808             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
24809             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
24810             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
24811         })(ParsingContext || (ParsingContext = {}));
24812         var Tristate;
24813         (function (Tristate) {
24814             Tristate[Tristate["False"] = 0] = "False";
24815             Tristate[Tristate["True"] = 1] = "True";
24816             Tristate[Tristate["Unknown"] = 2] = "Unknown";
24817         })(Tristate || (Tristate = {}));
24818         var JSDocParser;
24819         (function (JSDocParser) {
24820             function parseJSDocTypeExpressionForTests(content, start, length) {
24821                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24822                 sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
24823                 scanner.setText(content, start, length);
24824                 currentToken = scanner.scan();
24825                 var jsDocTypeExpression = parseJSDocTypeExpression();
24826                 var diagnostics = parseDiagnostics;
24827                 clearState();
24828                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
24829             }
24830             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
24831             // Parses out a JSDoc type expression.
24832             function parseJSDocTypeExpression(mayOmitBraces) {
24833                 var result = createNode(294 /* JSDocTypeExpression */);
24834                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
24835                 result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
24836                 if (!mayOmitBraces || hasBrace) {
24837                     parseExpectedJSDoc(19 /* CloseBraceToken */);
24838                 }
24839                 fixupParentReferences(result);
24840                 return finishNode(result);
24841             }
24842             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
24843             function parseIsolatedJSDocComment(content, start, length) {
24844                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24845                 sourceFile = { languageVariant: 0 /* Standard */, text: content };
24846                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24847                 var diagnostics = parseDiagnostics;
24848                 clearState();
24849                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
24850             }
24851             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
24852             function parseJSDocComment(parent, start, length) {
24853                 var _a;
24854                 var saveToken = currentToken;
24855                 var saveParseDiagnosticsLength = parseDiagnostics.length;
24856                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
24857                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24858                 if (comment) {
24859                     comment.parent = parent;
24860                 }
24861                 if (contextFlags & 131072 /* JavaScriptFile */) {
24862                     if (!sourceFile.jsDocDiagnostics) {
24863                         sourceFile.jsDocDiagnostics = [];
24864                     }
24865                     (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
24866                 }
24867                 currentToken = saveToken;
24868                 parseDiagnostics.length = saveParseDiagnosticsLength;
24869                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
24870                 return comment;
24871             }
24872             JSDocParser.parseJSDocComment = parseJSDocComment;
24873             var JSDocState;
24874             (function (JSDocState) {
24875                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
24876                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
24877                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
24878                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
24879             })(JSDocState || (JSDocState = {}));
24880             var PropertyLikeParse;
24881             (function (PropertyLikeParse) {
24882                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
24883                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
24884                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
24885             })(PropertyLikeParse || (PropertyLikeParse = {}));
24886             function parseJSDocCommentWorker(start, length) {
24887                 if (start === void 0) { start = 0; }
24888                 var content = sourceText;
24889                 var end = length === undefined ? content.length : start + length;
24890                 length = end - start;
24891                 ts.Debug.assert(start >= 0);
24892                 ts.Debug.assert(start <= end);
24893                 ts.Debug.assert(end <= content.length);
24894                 // Check for /** (JSDoc opening part)
24895                 if (!isJSDocLikeText(content, start)) {
24896                     return undefined;
24897                 }
24898                 var tags;
24899                 var tagsPos;
24900                 var tagsEnd;
24901                 var comments = [];
24902                 // + 3 for leading /**, - 5 in total for /** */
24903                 return scanner.scanRange(start + 3, length - 5, function () {
24904                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
24905                     // This is so that /** * @type */ doesn't parse.
24906                     var state = 1 /* SawAsterisk */;
24907                     var margin;
24908                     // + 4 for leading '/** '
24909                     var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
24910                     function pushComment(text) {
24911                         if (!margin) {
24912                             margin = indent;
24913                         }
24914                         comments.push(text);
24915                         indent += text.length;
24916                     }
24917                     nextTokenJSDoc();
24918                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
24919                         ;
24920                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
24921                         state = 0 /* BeginningOfLine */;
24922                         indent = 0;
24923                     }
24924                     loop: while (true) {
24925                         switch (token()) {
24926                             case 59 /* AtToken */:
24927                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
24928                                     removeTrailingWhitespace(comments);
24929                                     addTag(parseTag(indent));
24930                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
24931                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
24932                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
24933                                     state = 0 /* BeginningOfLine */;
24934                                     margin = undefined;
24935                                 }
24936                                 else {
24937                                     pushComment(scanner.getTokenText());
24938                                 }
24939                                 break;
24940                             case 4 /* NewLineTrivia */:
24941                                 comments.push(scanner.getTokenText());
24942                                 state = 0 /* BeginningOfLine */;
24943                                 indent = 0;
24944                                 break;
24945                             case 41 /* AsteriskToken */:
24946                                 var asterisk = scanner.getTokenText();
24947                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
24948                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
24949                                     state = 2 /* SavingComments */;
24950                                     pushComment(asterisk);
24951                                 }
24952                                 else {
24953                                     // Ignore the first asterisk on a line
24954                                     state = 1 /* SawAsterisk */;
24955                                     indent += asterisk.length;
24956                                 }
24957                                 break;
24958                             case 5 /* WhitespaceTrivia */:
24959                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
24960                                 var whitespace = scanner.getTokenText();
24961                                 if (state === 2 /* SavingComments */) {
24962                                     comments.push(whitespace);
24963                                 }
24964                                 else if (margin !== undefined && indent + whitespace.length > margin) {
24965                                     comments.push(whitespace.slice(margin - indent - 1));
24966                                 }
24967                                 indent += whitespace.length;
24968                                 break;
24969                             case 1 /* EndOfFileToken */:
24970                                 break loop;
24971                             default:
24972                                 // Anything else is doc comment text. We just save it. Because it
24973                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
24974                                 // line break.
24975                                 state = 2 /* SavingComments */;
24976                                 pushComment(scanner.getTokenText());
24977                                 break;
24978                         }
24979                         nextTokenJSDoc();
24980                     }
24981                     removeLeadingNewlines(comments);
24982                     removeTrailingWhitespace(comments);
24983                     return createJSDocComment();
24984                 });
24985                 function removeLeadingNewlines(comments) {
24986                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
24987                         comments.shift();
24988                     }
24989                 }
24990                 function removeTrailingWhitespace(comments) {
24991                     while (comments.length && comments[comments.length - 1].trim() === "") {
24992                         comments.pop();
24993                     }
24994                 }
24995                 function createJSDocComment() {
24996                     var result = createNode(303 /* JSDocComment */, start);
24997                     result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
24998                     result.comment = comments.length ? comments.join("") : undefined;
24999                     return finishNode(result, end);
25000                 }
25001                 function isNextNonwhitespaceTokenEndOfFile() {
25002                     // We must use infinite lookahead, as there could be any number of newlines :(
25003                     while (true) {
25004                         nextTokenJSDoc();
25005                         if (token() === 1 /* EndOfFileToken */) {
25006                             return true;
25007                         }
25008                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
25009                             return false;
25010                         }
25011                     }
25012                 }
25013                 function skipWhitespace() {
25014                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25015                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25016                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25017                         }
25018                     }
25019                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25020                         nextTokenJSDoc();
25021                     }
25022                 }
25023                 function skipWhitespaceOrAsterisk() {
25024                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25025                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25026                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25027                         }
25028                     }
25029                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
25030                     var seenLineBreak = false;
25031                     var indentText = "";
25032                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25033                         indentText += scanner.getTokenText();
25034                         if (token() === 4 /* NewLineTrivia */) {
25035                             precedingLineBreak = true;
25036                             seenLineBreak = true;
25037                             indentText = "";
25038                         }
25039                         else if (token() === 41 /* AsteriskToken */) {
25040                             precedingLineBreak = false;
25041                         }
25042                         nextTokenJSDoc();
25043                     }
25044                     return seenLineBreak ? indentText : "";
25045                 }
25046                 function parseTag(margin) {
25047                     ts.Debug.assert(token() === 59 /* AtToken */);
25048                     var start = scanner.getTokenPos();
25049                     nextTokenJSDoc();
25050                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
25051                     var indentText = skipWhitespaceOrAsterisk();
25052                     var tag;
25053                     switch (tagName.escapedText) {
25054                         case "author":
25055                             tag = parseAuthorTag(start, tagName, margin);
25056                             break;
25057                         case "implements":
25058                             tag = parseImplementsTag(start, tagName);
25059                             break;
25060                         case "augments":
25061                         case "extends":
25062                             tag = parseAugmentsTag(start, tagName);
25063                             break;
25064                         case "class":
25065                         case "constructor":
25066                             tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName);
25067                             break;
25068                         case "public":
25069                             tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName);
25070                             break;
25071                         case "private":
25072                             tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName);
25073                             break;
25074                         case "protected":
25075                             tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName);
25076                             break;
25077                         case "readonly":
25078                             tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName);
25079                             break;
25080                         case "this":
25081                             tag = parseThisTag(start, tagName);
25082                             break;
25083                         case "enum":
25084                             tag = parseEnumTag(start, tagName);
25085                             break;
25086                         case "arg":
25087                         case "argument":
25088                         case "param":
25089                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
25090                         case "return":
25091                         case "returns":
25092                             tag = parseReturnTag(start, tagName);
25093                             break;
25094                         case "template":
25095                             tag = parseTemplateTag(start, tagName);
25096                             break;
25097                         case "type":
25098                             tag = parseTypeTag(start, tagName);
25099                             break;
25100                         case "typedef":
25101                             tag = parseTypedefTag(start, tagName, margin);
25102                             break;
25103                         case "callback":
25104                             tag = parseCallbackTag(start, tagName, margin);
25105                             break;
25106                         default:
25107                             tag = parseUnknownTag(start, tagName);
25108                             break;
25109                     }
25110                     if (!tag.comment) {
25111                         // some tags, like typedef and callback, have already parsed their comments earlier
25112                         if (!indentText) {
25113                             margin += tag.end - tag.pos;
25114                         }
25115                         tag.comment = parseTagComments(margin, indentText.slice(margin));
25116                     }
25117                     return tag;
25118                 }
25119                 function parseTagComments(indent, initialMargin) {
25120                     var comments = [];
25121                     var state = 0 /* BeginningOfLine */;
25122                     var margin;
25123                     function pushComment(text) {
25124                         if (!margin) {
25125                             margin = indent;
25126                         }
25127                         comments.push(text);
25128                         indent += text.length;
25129                     }
25130                     if (initialMargin !== undefined) {
25131                         // jump straight to saving comments if there is some initial indentation
25132                         if (initialMargin !== "") {
25133                             pushComment(initialMargin);
25134                         }
25135                         state = 1 /* SawAsterisk */;
25136                     }
25137                     var tok = token();
25138                     loop: while (true) {
25139                         switch (tok) {
25140                             case 4 /* NewLineTrivia */:
25141                                 if (state >= 1 /* SawAsterisk */) {
25142                                     state = 0 /* BeginningOfLine */;
25143                                     // don't use pushComment here because we want to keep the margin unchanged
25144                                     comments.push(scanner.getTokenText());
25145                                 }
25146                                 indent = 0;
25147                                 break;
25148                             case 59 /* AtToken */:
25149                                 if (state === 3 /* SavingBackticks */) {
25150                                     comments.push(scanner.getTokenText());
25151                                     break;
25152                                 }
25153                                 scanner.setTextPos(scanner.getTextPos() - 1);
25154                             // falls through
25155                             case 1 /* EndOfFileToken */:
25156                                 // Done
25157                                 break loop;
25158                             case 5 /* WhitespaceTrivia */:
25159                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
25160                                     pushComment(scanner.getTokenText());
25161                                 }
25162                                 else {
25163                                     var whitespace = scanner.getTokenText();
25164                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
25165                                     if (margin !== undefined && indent + whitespace.length > margin) {
25166                                         comments.push(whitespace.slice(margin - indent));
25167                                     }
25168                                     indent += whitespace.length;
25169                                 }
25170                                 break;
25171                             case 18 /* OpenBraceToken */:
25172                                 state = 2 /* SavingComments */;
25173                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
25174                                     pushComment(scanner.getTokenText());
25175                                     nextTokenJSDoc();
25176                                     pushComment(scanner.getTokenText());
25177                                     nextTokenJSDoc();
25178                                 }
25179                                 pushComment(scanner.getTokenText());
25180                                 break;
25181                             case 61 /* BacktickToken */:
25182                                 if (state === 3 /* SavingBackticks */) {
25183                                     state = 2 /* SavingComments */;
25184                                 }
25185                                 else {
25186                                     state = 3 /* SavingBackticks */;
25187                                 }
25188                                 pushComment(scanner.getTokenText());
25189                                 break;
25190                             case 41 /* AsteriskToken */:
25191                                 if (state === 0 /* BeginningOfLine */) {
25192                                     // leading asterisks start recording on the *next* (non-whitespace) token
25193                                     state = 1 /* SawAsterisk */;
25194                                     indent += 1;
25195                                     break;
25196                                 }
25197                             // record the * as a comment
25198                             // falls through
25199                             default:
25200                                 if (state !== 3 /* SavingBackticks */) {
25201                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
25202                                 }
25203                                 pushComment(scanner.getTokenText());
25204                                 break;
25205                         }
25206                         tok = nextTokenJSDoc();
25207                     }
25208                     removeLeadingNewlines(comments);
25209                     removeTrailingWhitespace(comments);
25210                     return comments.length === 0 ? undefined : comments.join("");
25211                 }
25212                 function parseUnknownTag(start, tagName) {
25213                     var result = createNode(306 /* JSDocTag */, start);
25214                     result.tagName = tagName;
25215                     return finishNode(result);
25216                 }
25217                 function addTag(tag) {
25218                     if (!tag) {
25219                         return;
25220                     }
25221                     if (!tags) {
25222                         tags = [tag];
25223                         tagsPos = tag.pos;
25224                     }
25225                     else {
25226                         tags.push(tag);
25227                     }
25228                     tagsEnd = tag.end;
25229                 }
25230                 function tryParseTypeExpression() {
25231                     skipWhitespaceOrAsterisk();
25232                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
25233                 }
25234                 function parseBracketNameInPropertyAndParamTag() {
25235                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
25236                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
25237                     if (isBracketed) {
25238                         skipWhitespace();
25239                     }
25240                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
25241                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
25242                     var name = parseJSDocEntityName();
25243                     if (isBackquoted) {
25244                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
25245                     }
25246                     if (isBracketed) {
25247                         skipWhitespace();
25248                         // May have an optional default, e.g. '[foo = 42]'
25249                         if (parseOptionalToken(62 /* EqualsToken */)) {
25250                             parseExpression();
25251                         }
25252                         parseExpected(23 /* CloseBracketToken */);
25253                     }
25254                     return { name: name, isBracketed: isBracketed };
25255                 }
25256                 function isObjectOrObjectArrayTypeReference(node) {
25257                     switch (node.kind) {
25258                         case 141 /* ObjectKeyword */:
25259                             return true;
25260                         case 174 /* ArrayType */:
25261                             return isObjectOrObjectArrayTypeReference(node.elementType);
25262                         default:
25263                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
25264                     }
25265                 }
25266                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
25267                     var typeExpression = tryParseTypeExpression();
25268                     var isNameFirst = !typeExpression;
25269                     skipWhitespaceOrAsterisk();
25270                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
25271                     skipWhitespace();
25272                     if (isNameFirst) {
25273                         typeExpression = tryParseTypeExpression();
25274                     }
25275                     var result = target === 1 /* Property */ ?
25276                         createNode(323 /* JSDocPropertyTag */, start) :
25277                         createNode(317 /* JSDocParameterTag */, start);
25278                     var comment = parseTagComments(indent + scanner.getStartPos() - start);
25279                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
25280                     if (nestedTypeLiteral) {
25281                         typeExpression = nestedTypeLiteral;
25282                         isNameFirst = true;
25283                     }
25284                     result.tagName = tagName;
25285                     result.typeExpression = typeExpression;
25286                     result.name = name;
25287                     result.isNameFirst = isNameFirst;
25288                     result.isBracketed = isBracketed;
25289                     result.comment = comment;
25290                     return finishNode(result);
25291                 }
25292                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
25293                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25294                         var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
25295                         var child = void 0;
25296                         var jsdocTypeLiteral = void 0;
25297                         var start_3 = scanner.getStartPos();
25298                         var children = void 0;
25299                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
25300                             if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) {
25301                                 children = ts.append(children, child);
25302                             }
25303                         }
25304                         if (children) {
25305                             jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
25306                             jsdocTypeLiteral.jsDocPropertyTags = children;
25307                             if (typeExpression.type.kind === 174 /* ArrayType */) {
25308                                 jsdocTypeLiteral.isArrayType = true;
25309                             }
25310                             typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
25311                             return finishNode(typeLiteralExpression);
25312                         }
25313                     }
25314                 }
25315                 function parseReturnTag(start, tagName) {
25316                     if (ts.some(tags, ts.isJSDocReturnTag)) {
25317                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25318                     }
25319                     var result = createNode(318 /* JSDocReturnTag */, start);
25320                     result.tagName = tagName;
25321                     result.typeExpression = tryParseTypeExpression();
25322                     return finishNode(result);
25323                 }
25324                 function parseTypeTag(start, tagName) {
25325                     if (ts.some(tags, ts.isJSDocTypeTag)) {
25326                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25327                     }
25328                     var result = createNode(320 /* JSDocTypeTag */, start);
25329                     result.tagName = tagName;
25330                     result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25331                     return finishNode(result);
25332                 }
25333                 function parseAuthorTag(start, tagName, indent) {
25334                     var result = createNode(309 /* JSDocAuthorTag */, start);
25335                     result.tagName = tagName;
25336                     var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
25337                     if (!authorInfoWithEmail) {
25338                         return finishNode(result);
25339                     }
25340                     result.comment = authorInfoWithEmail;
25341                     if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
25342                         var comment = parseTagComments(indent);
25343                         if (comment) {
25344                             result.comment += comment;
25345                         }
25346                     }
25347                     return finishNode(result);
25348                 }
25349                 function tryParseAuthorNameAndEmail() {
25350                     var comments = [];
25351                     var seenLessThan = false;
25352                     var seenGreaterThan = false;
25353                     var token = scanner.getToken();
25354                     loop: while (true) {
25355                         switch (token) {
25356                             case 75 /* Identifier */:
25357                             case 5 /* WhitespaceTrivia */:
25358                             case 24 /* DotToken */:
25359                             case 59 /* AtToken */:
25360                                 comments.push(scanner.getTokenText());
25361                                 break;
25362                             case 29 /* LessThanToken */:
25363                                 if (seenLessThan || seenGreaterThan) {
25364                                     return;
25365                                 }
25366                                 seenLessThan = true;
25367                                 comments.push(scanner.getTokenText());
25368                                 break;
25369                             case 31 /* GreaterThanToken */:
25370                                 if (!seenLessThan || seenGreaterThan) {
25371                                     return;
25372                                 }
25373                                 seenGreaterThan = true;
25374                                 comments.push(scanner.getTokenText());
25375                                 scanner.setTextPos(scanner.getTokenPos() + 1);
25376                                 break loop;
25377                             case 4 /* NewLineTrivia */:
25378                             case 1 /* EndOfFileToken */:
25379                                 break loop;
25380                         }
25381                         token = nextTokenJSDoc();
25382                     }
25383                     if (seenLessThan && seenGreaterThan) {
25384                         return comments.length === 0 ? undefined : comments.join("");
25385                     }
25386                 }
25387                 function parseImplementsTag(start, tagName) {
25388                     var result = createNode(308 /* JSDocImplementsTag */, start);
25389                     result.tagName = tagName;
25390                     result.class = parseExpressionWithTypeArgumentsForAugments();
25391                     return finishNode(result);
25392                 }
25393                 function parseAugmentsTag(start, tagName) {
25394                     var result = createNode(307 /* JSDocAugmentsTag */, start);
25395                     result.tagName = tagName;
25396                     result.class = parseExpressionWithTypeArgumentsForAugments();
25397                     return finishNode(result);
25398                 }
25399                 function parseExpressionWithTypeArgumentsForAugments() {
25400                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
25401                     var node = createNode(216 /* ExpressionWithTypeArguments */);
25402                     node.expression = parsePropertyAccessEntityNameExpression();
25403                     node.typeArguments = tryParseTypeArguments();
25404                     var res = finishNode(node);
25405                     if (usedBrace) {
25406                         parseExpected(19 /* CloseBraceToken */);
25407                     }
25408                     return res;
25409                 }
25410                 function parsePropertyAccessEntityNameExpression() {
25411                     var node = parseJSDocIdentifierName();
25412                     while (parseOptional(24 /* DotToken */)) {
25413                         var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
25414                         prop.expression = node;
25415                         prop.name = parseJSDocIdentifierName();
25416                         node = finishNode(prop);
25417                     }
25418                     return node;
25419                 }
25420                 function parseSimpleTag(start, kind, tagName) {
25421                     var tag = createNode(kind, start);
25422                     tag.tagName = tagName;
25423                     return finishNode(tag);
25424                 }
25425                 function parseThisTag(start, tagName) {
25426                     var tag = createNode(319 /* JSDocThisTag */, start);
25427                     tag.tagName = tagName;
25428                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25429                     skipWhitespace();
25430                     return finishNode(tag);
25431                 }
25432                 function parseEnumTag(start, tagName) {
25433                     var tag = createNode(316 /* JSDocEnumTag */, start);
25434                     tag.tagName = tagName;
25435                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25436                     skipWhitespace();
25437                     return finishNode(tag);
25438                 }
25439                 function parseTypedefTag(start, tagName, indent) {
25440                     var typeExpression = tryParseTypeExpression();
25441                     skipWhitespaceOrAsterisk();
25442                     var typedefTag = createNode(322 /* JSDocTypedefTag */, start);
25443                     typedefTag.tagName = tagName;
25444                     typedefTag.fullName = parseJSDocTypeNameWithNamespace();
25445                     typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
25446                     skipWhitespace();
25447                     typedefTag.comment = parseTagComments(indent);
25448                     typedefTag.typeExpression = typeExpression;
25449                     var end;
25450                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25451                         var child = void 0;
25452                         var jsdocTypeLiteral = void 0;
25453                         var childTypeTag = void 0;
25454                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
25455                             if (!jsdocTypeLiteral) {
25456                                 jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
25457                             }
25458                             if (child.kind === 320 /* JSDocTypeTag */) {
25459                                 if (childTypeTag) {
25460                                     break;
25461                                 }
25462                                 else {
25463                                     childTypeTag = child;
25464                                 }
25465                             }
25466                             else {
25467                                 jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
25468                             }
25469                         }
25470                         if (jsdocTypeLiteral) {
25471                             if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
25472                                 jsdocTypeLiteral.isArrayType = true;
25473                             }
25474                             typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
25475                                 childTypeTag.typeExpression :
25476                                 finishNode(jsdocTypeLiteral);
25477                             end = typedefTag.typeExpression.end;
25478                         }
25479                     }
25480                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
25481                     return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
25482                 }
25483                 function parseJSDocTypeNameWithNamespace(nested) {
25484                     var pos = scanner.getTokenPos();
25485                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25486                         return undefined;
25487                     }
25488                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
25489                     if (parseOptional(24 /* DotToken */)) {
25490                         var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
25491                         if (nested) {
25492                             jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
25493                         }
25494                         jsDocNamespaceNode.name = typeNameOrNamespaceName;
25495                         jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
25496                         return finishNode(jsDocNamespaceNode);
25497                     }
25498                     if (nested) {
25499                         typeNameOrNamespaceName.isInJSDocNamespace = true;
25500                     }
25501                     return typeNameOrNamespaceName;
25502                 }
25503                 function parseCallbackTag(start, tagName, indent) {
25504                     var callbackTag = createNode(315 /* JSDocCallbackTag */, start);
25505                     callbackTag.tagName = tagName;
25506                     callbackTag.fullName = parseJSDocTypeNameWithNamespace();
25507                     callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
25508                     skipWhitespace();
25509                     callbackTag.comment = parseTagComments(indent);
25510                     var child;
25511                     var jsdocSignature = createNode(305 /* JSDocSignature */, start);
25512                     jsdocSignature.parameters = [];
25513                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
25514                         jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
25515                     }
25516                     var returnTag = tryParse(function () {
25517                         if (parseOptionalJsdoc(59 /* AtToken */)) {
25518                             var tag = parseTag(indent);
25519                             if (tag && tag.kind === 318 /* JSDocReturnTag */) {
25520                                 return tag;
25521                             }
25522                         }
25523                     });
25524                     if (returnTag) {
25525                         jsdocSignature.type = returnTag;
25526                     }
25527                     callbackTag.typeExpression = finishNode(jsdocSignature);
25528                     return finishNode(callbackTag);
25529                 }
25530                 function getJSDocTypeAliasName(fullName) {
25531                     if (fullName) {
25532                         var rightNode = fullName;
25533                         while (true) {
25534                             if (ts.isIdentifier(rightNode) || !rightNode.body) {
25535                                 return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
25536                             }
25537                             rightNode = rightNode.body;
25538                         }
25539                     }
25540                 }
25541                 function escapedTextsEqual(a, b) {
25542                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
25543                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
25544                             a = a.left;
25545                             b = b.left;
25546                         }
25547                         else {
25548                             return false;
25549                         }
25550                     }
25551                     return a.escapedText === b.escapedText;
25552                 }
25553                 function parseChildPropertyTag(indent) {
25554                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
25555                 }
25556                 function parseChildParameterOrPropertyTag(target, indent, name) {
25557                     var canParseTag = true;
25558                     var seenAsterisk = false;
25559                     while (true) {
25560                         switch (nextTokenJSDoc()) {
25561                             case 59 /* AtToken */:
25562                                 if (canParseTag) {
25563                                     var child = tryParseChildTag(target, indent);
25564                                     if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) &&
25565                                         target !== 4 /* CallbackParameter */ &&
25566                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
25567                                         return false;
25568                                     }
25569                                     return child;
25570                                 }
25571                                 seenAsterisk = false;
25572                                 break;
25573                             case 4 /* NewLineTrivia */:
25574                                 canParseTag = true;
25575                                 seenAsterisk = false;
25576                                 break;
25577                             case 41 /* AsteriskToken */:
25578                                 if (seenAsterisk) {
25579                                     canParseTag = false;
25580                                 }
25581                                 seenAsterisk = true;
25582                                 break;
25583                             case 75 /* Identifier */:
25584                                 canParseTag = false;
25585                                 break;
25586                             case 1 /* EndOfFileToken */:
25587                                 return false;
25588                         }
25589                     }
25590                 }
25591                 function tryParseChildTag(target, indent) {
25592                     ts.Debug.assert(token() === 59 /* AtToken */);
25593                     var start = scanner.getStartPos();
25594                     nextTokenJSDoc();
25595                     var tagName = parseJSDocIdentifierName();
25596                     skipWhitespace();
25597                     var t;
25598                     switch (tagName.escapedText) {
25599                         case "type":
25600                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
25601                         case "prop":
25602                         case "property":
25603                             t = 1 /* Property */;
25604                             break;
25605                         case "arg":
25606                         case "argument":
25607                         case "param":
25608                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
25609                             break;
25610                         default:
25611                             return false;
25612                     }
25613                     if (!(target & t)) {
25614                         return false;
25615                     }
25616                     return parseParameterOrPropertyTag(start, tagName, target, indent);
25617                 }
25618                 function parseTemplateTag(start, tagName) {
25619                     // the template tag looks like '@template {Constraint} T,U,V'
25620                     var constraint;
25621                     if (token() === 18 /* OpenBraceToken */) {
25622                         constraint = parseJSDocTypeExpression();
25623                     }
25624                     var typeParameters = [];
25625                     var typeParametersPos = getNodePos();
25626                     do {
25627                         skipWhitespace();
25628                         var typeParameter = createNode(155 /* TypeParameter */);
25629                         typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
25630                         finishNode(typeParameter);
25631                         skipWhitespaceOrAsterisk();
25632                         typeParameters.push(typeParameter);
25633                     } while (parseOptionalJsdoc(27 /* CommaToken */));
25634                     var result = createNode(321 /* JSDocTemplateTag */, start);
25635                     result.tagName = tagName;
25636                     result.constraint = constraint;
25637                     result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
25638                     finishNode(result);
25639                     return result;
25640                 }
25641                 function parseOptionalJsdoc(t) {
25642                     if (token() === t) {
25643                         nextTokenJSDoc();
25644                         return true;
25645                     }
25646                     return false;
25647                 }
25648                 function parseJSDocEntityName() {
25649                     var entity = parseJSDocIdentifierName();
25650                     if (parseOptional(22 /* OpenBracketToken */)) {
25651                         parseExpected(23 /* CloseBracketToken */);
25652                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
25653                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
25654                         // but it's not worth it to enforce that restriction.
25655                     }
25656                     while (parseOptional(24 /* DotToken */)) {
25657                         var name = parseJSDocIdentifierName();
25658                         if (parseOptional(22 /* OpenBracketToken */)) {
25659                             parseExpected(23 /* CloseBracketToken */);
25660                         }
25661                         entity = createQualifiedName(entity, name);
25662                     }
25663                     return entity;
25664                 }
25665                 function parseJSDocIdentifierName(message) {
25666                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25667                         return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
25668                     }
25669                     identifierCount++;
25670                     var pos = scanner.getTokenPos();
25671                     var end = scanner.getTextPos();
25672                     var result = createNode(75 /* Identifier */, pos);
25673                     if (token() !== 75 /* Identifier */) {
25674                         result.originalKeywordKind = token();
25675                     }
25676                     result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
25677                     finishNode(result, end);
25678                     nextTokenJSDoc();
25679                     return result;
25680                 }
25681             }
25682         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
25683     })(Parser || (Parser = {}));
25684     var IncrementalParser;
25685     (function (IncrementalParser) {
25686         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
25687             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
25688             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
25689             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
25690                 // if the text didn't change, then we can just return our current source file as-is.
25691                 return sourceFile;
25692             }
25693             if (sourceFile.statements.length === 0) {
25694                 // If we don't have any statements in the current source file, then there's no real
25695                 // way to incrementally parse.  So just do a full parse instead.
25696                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
25697             }
25698             // Make sure we're not trying to incrementally update a source file more than once.  Once
25699             // we do an update the original source file is considered unusable from that point onwards.
25700             //
25701             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
25702             // tree and give them new positions and parents.  From that point on, trusting the old
25703             // tree at all is not possible as far too much of it may violate invariants.
25704             var incrementalSourceFile = sourceFile;
25705             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
25706             incrementalSourceFile.hasBeenIncrementallyParsed = true;
25707             var oldText = sourceFile.text;
25708             var syntaxCursor = createSyntaxCursor(sourceFile);
25709             // Make the actual change larger so that we know to reparse anything whose lookahead
25710             // might have intersected the change.
25711             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
25712             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
25713             // Ensure that extending the affected range only moved the start of the change range
25714             // earlier in the file.
25715             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
25716             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
25717             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
25718             // The is the amount the nodes after the edit range need to be adjusted.  It can be
25719             // positive (if the edit added characters), negative (if the edit deleted characters)
25720             // or zero (if this was a pure overwrite with nothing added/removed).
25721             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
25722             // If we added or removed characters during the edit, then we need to go and adjust all
25723             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
25724             // may move backward (if we deleted chars).
25725             //
25726             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
25727             // to reuse are already at the appropriate position in the new text.  That way when we
25728             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
25729             // it very easy to determine if we can reuse a node.  If the node's position is at where
25730             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
25731             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
25732             // us, then we'll need to skip it or crumble it as appropriate
25733             //
25734             // We will also adjust the positions of nodes that intersect the change range as well.
25735             // By doing this, we ensure that all the positions in the old tree are consistent, not
25736             // just the positions of nodes entirely before/after the change range.  By being
25737             // consistent, we can then easily map from positions to nodes in the old tree easily.
25738             //
25739             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
25740             // that we cannot reuse these elements.
25741             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
25742             // Now that we've set up our internal incremental state just proceed and parse the
25743             // source file in the normal fashion.  When possible the parser will retrieve and
25744             // reuse nodes from the old tree.
25745             //
25746             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
25747             // parsing, we will be reusing nodes from the old tree, and placing it into new
25748             // parents.  If we don't set the parents now, we'll end up with an observably
25749             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
25750             // will immediately bail out of walking any subtrees when we can see that their parents
25751             // are already correct.
25752             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
25753             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
25754             return result;
25755         }
25756         IncrementalParser.updateSourceFile = updateSourceFile;
25757         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
25758             if (!oldDirectives)
25759                 return newDirectives;
25760             var commentDirectives;
25761             var addedNewlyScannedDirectives = false;
25762             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
25763                 var directive = oldDirectives_1[_i];
25764                 var range = directive.range, type = directive.type;
25765                 // Range before the change
25766                 if (range.end < changeStart) {
25767                     commentDirectives = ts.append(commentDirectives, directive);
25768                 }
25769                 else if (range.pos > changeRangeOldEnd) {
25770                     addNewlyScannedDirectives();
25771                     // Node is entirely past the change range.  We need to move both its pos and
25772                     // end, forward or backward appropriately.
25773                     var updatedDirective = {
25774                         range: { pos: range.pos + delta, end: range.end + delta },
25775                         type: type
25776                     };
25777                     commentDirectives = ts.append(commentDirectives, updatedDirective);
25778                     if (aggressiveChecks) {
25779                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
25780                     }
25781                 }
25782                 // Ignore ranges that fall in change range
25783             }
25784             addNewlyScannedDirectives();
25785             return commentDirectives;
25786             function addNewlyScannedDirectives() {
25787                 if (addedNewlyScannedDirectives)
25788                     return;
25789                 addedNewlyScannedDirectives = true;
25790                 if (!commentDirectives) {
25791                     commentDirectives = newDirectives;
25792                 }
25793                 else if (newDirectives) {
25794                     commentDirectives.push.apply(commentDirectives, newDirectives);
25795                 }
25796             }
25797         }
25798         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
25799             if (isArray) {
25800                 visitArray(element);
25801             }
25802             else {
25803                 visitNode(element);
25804             }
25805             return;
25806             function visitNode(node) {
25807                 var text = "";
25808                 if (aggressiveChecks && shouldCheckNode(node)) {
25809                     text = oldText.substring(node.pos, node.end);
25810                 }
25811                 // Ditch any existing LS children we may have created.  This way we can avoid
25812                 // moving them forward.
25813                 if (node._children) {
25814                     node._children = undefined;
25815                 }
25816                 node.pos += delta;
25817                 node.end += delta;
25818                 if (aggressiveChecks && shouldCheckNode(node)) {
25819                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
25820                 }
25821                 forEachChild(node, visitNode, visitArray);
25822                 if (ts.hasJSDocNodes(node)) {
25823                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25824                         var jsDocComment = _a[_i];
25825                         visitNode(jsDocComment);
25826                     }
25827                 }
25828                 checkNodePositions(node, aggressiveChecks);
25829             }
25830             function visitArray(array) {
25831                 array._children = undefined;
25832                 array.pos += delta;
25833                 array.end += delta;
25834                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
25835                     var node = array_8[_i];
25836                     visitNode(node);
25837                 }
25838             }
25839         }
25840         function shouldCheckNode(node) {
25841             switch (node.kind) {
25842                 case 10 /* StringLiteral */:
25843                 case 8 /* NumericLiteral */:
25844                 case 75 /* Identifier */:
25845                     return true;
25846             }
25847             return false;
25848         }
25849         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
25850             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
25851             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
25852             ts.Debug.assert(element.pos <= element.end);
25853             // We have an element that intersects the change range in some way.  It may have its
25854             // start, or its end (or both) in the changed range.  We want to adjust any part
25855             // that intersects such that the final tree is in a consistent state.  i.e. all
25856             // children have spans within the span of their parent, and all siblings are ordered
25857             // properly.
25858             // We may need to update both the 'pos' and the 'end' of the element.
25859             // If the 'pos' is before the start of the change, then we don't need to touch it.
25860             // If it isn't, then the 'pos' must be inside the change.  How we update it will
25861             // depend if delta is positive or negative. If delta is positive then we have
25862             // something like:
25863             //
25864             //  -------------------AAA-----------------
25865             //  -------------------BBBCCCCCCC-----------------
25866             //
25867             // In this case, we consider any node that started in the change range to still be
25868             // starting at the same position.
25869             //
25870             // however, if the delta is negative, then we instead have something like this:
25871             //
25872             //  -------------------XXXYYYYYYY-----------------
25873             //  -------------------ZZZ-----------------
25874             //
25875             // In this case, any element that started in the 'X' range will keep its position.
25876             // However any element that started after that will have their pos adjusted to be
25877             // at the end of the new range.  i.e. any node that started in the 'Y' range will
25878             // be adjusted to have their start at the end of the 'Z' range.
25879             //
25880             // The element will keep its position if possible.  Or Move backward to the new-end
25881             // if it's in the 'Y' range.
25882             element.pos = Math.min(element.pos, changeRangeNewEnd);
25883             // If the 'end' is after the change range, then we always adjust it by the delta
25884             // amount.  However, if the end is in the change range, then how we adjust it
25885             // will depend on if delta is positive or negative.  If delta is positive then we
25886             // have something like:
25887             //
25888             //  -------------------AAA-----------------
25889             //  -------------------BBBCCCCCCC-----------------
25890             //
25891             // In this case, we consider any node that ended inside the change range to keep its
25892             // end position.
25893             //
25894             // however, if the delta is negative, then we instead have something like this:
25895             //
25896             //  -------------------XXXYYYYYYY-----------------
25897             //  -------------------ZZZ-----------------
25898             //
25899             // In this case, any element that ended in the 'X' range will keep its position.
25900             // However any element that ended after that will have their pos adjusted to be
25901             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
25902             // be adjusted to have their end at the end of the 'Z' range.
25903             if (element.end >= changeRangeOldEnd) {
25904                 // Element ends after the change range.  Always adjust the end pos.
25905                 element.end += delta;
25906             }
25907             else {
25908                 // Element ends in the change range.  The element will keep its position if
25909                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
25910                 element.end = Math.min(element.end, changeRangeNewEnd);
25911             }
25912             ts.Debug.assert(element.pos <= element.end);
25913             if (element.parent) {
25914                 ts.Debug.assert(element.pos >= element.parent.pos);
25915                 ts.Debug.assert(element.end <= element.parent.end);
25916             }
25917         }
25918         function checkNodePositions(node, aggressiveChecks) {
25919             if (aggressiveChecks) {
25920                 var pos_2 = node.pos;
25921                 var visitNode_1 = function (child) {
25922                     ts.Debug.assert(child.pos >= pos_2);
25923                     pos_2 = child.end;
25924                 };
25925                 if (ts.hasJSDocNodes(node)) {
25926                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25927                         var jsDocComment = _a[_i];
25928                         visitNode_1(jsDocComment);
25929                     }
25930                 }
25931                 forEachChild(node, visitNode_1);
25932                 ts.Debug.assert(pos_2 <= node.end);
25933             }
25934         }
25935         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
25936             visitNode(sourceFile);
25937             return;
25938             function visitNode(child) {
25939                 ts.Debug.assert(child.pos <= child.end);
25940                 if (child.pos > changeRangeOldEnd) {
25941                     // Node is entirely past the change range.  We need to move both its pos and
25942                     // end, forward or backward appropriately.
25943                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
25944                     return;
25945                 }
25946                 // Check if the element intersects the change range.  If it does, then it is not
25947                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25948                 // be able to use.
25949                 var fullEnd = child.end;
25950                 if (fullEnd >= changeStart) {
25951                     child.intersectsChange = true;
25952                     child._children = undefined;
25953                     // Adjust the pos or end (or both) of the intersecting element accordingly.
25954                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25955                     forEachChild(child, visitNode, visitArray);
25956                     if (ts.hasJSDocNodes(child)) {
25957                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
25958                             var jsDocComment = _a[_i];
25959                             visitNode(jsDocComment);
25960                         }
25961                     }
25962                     checkNodePositions(child, aggressiveChecks);
25963                     return;
25964                 }
25965                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
25966                 ts.Debug.assert(fullEnd < changeStart);
25967             }
25968             function visitArray(array) {
25969                 ts.Debug.assert(array.pos <= array.end);
25970                 if (array.pos > changeRangeOldEnd) {
25971                     // Array is entirely after the change range.  We need to move it, and move any of
25972                     // its children.
25973                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
25974                     return;
25975                 }
25976                 // Check if the element intersects the change range.  If it does, then it is not
25977                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25978                 // be able to use.
25979                 var fullEnd = array.end;
25980                 if (fullEnd >= changeStart) {
25981                     array.intersectsChange = true;
25982                     array._children = undefined;
25983                     // Adjust the pos or end (or both) of the intersecting array accordingly.
25984                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25985                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
25986                         var node = array_9[_i];
25987                         visitNode(node);
25988                     }
25989                     return;
25990                 }
25991                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
25992                 ts.Debug.assert(fullEnd < changeStart);
25993             }
25994         }
25995         function extendToAffectedRange(sourceFile, changeRange) {
25996             // Consider the following code:
25997             //      void foo() { /; }
25998             //
25999             // If the text changes with an insertion of / just before the semicolon then we end up with:
26000             //      void foo() { //; }
26001             //
26002             // If we were to just use the changeRange a is, then we would not rescan the { token
26003             // (as it does not intersect the actual original change range).  Because an edit may
26004             // change the token touching it, we actually need to look back *at least* one token so
26005             // that the prior token sees that change.
26006             var maxLookahead = 1;
26007             var start = changeRange.span.start;
26008             // the first iteration aligns us with the change start. subsequent iteration move us to
26009             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
26010             // start of the tree.
26011             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
26012                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
26013                 ts.Debug.assert(nearestNode.pos <= start);
26014                 var position = nearestNode.pos;
26015                 start = Math.max(0, position - 1);
26016             }
26017             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
26018             var finalLength = changeRange.newLength + (changeRange.span.start - start);
26019             return ts.createTextChangeRange(finalSpan, finalLength);
26020         }
26021         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
26022             var bestResult = sourceFile;
26023             var lastNodeEntirelyBeforePosition;
26024             forEachChild(sourceFile, visit);
26025             if (lastNodeEntirelyBeforePosition) {
26026                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
26027                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
26028                     bestResult = lastChildOfLastEntireNodeBeforePosition;
26029                 }
26030             }
26031             return bestResult;
26032             function getLastDescendant(node) {
26033                 while (true) {
26034                     var lastChild = ts.getLastChild(node);
26035                     if (lastChild) {
26036                         node = lastChild;
26037                     }
26038                     else {
26039                         return node;
26040                     }
26041                 }
26042             }
26043             function visit(child) {
26044                 if (ts.nodeIsMissing(child)) {
26045                     // Missing nodes are effectively invisible to us.  We never even consider them
26046                     // When trying to find the nearest node before us.
26047                     return;
26048                 }
26049                 // If the child intersects this position, then this node is currently the nearest
26050                 // node that starts before the position.
26051                 if (child.pos <= position) {
26052                     if (child.pos >= bestResult.pos) {
26053                         // This node starts before the position, and is closer to the position than
26054                         // the previous best node we found.  It is now the new best node.
26055                         bestResult = child;
26056                     }
26057                     // Now, the node may overlap the position, or it may end entirely before the
26058                     // position.  If it overlaps with the position, then either it, or one of its
26059                     // children must be the nearest node before the position.  So we can just
26060                     // recurse into this child to see if we can find something better.
26061                     if (position < child.end) {
26062                         // The nearest node is either this child, or one of the children inside
26063                         // of it.  We've already marked this child as the best so far.  Recurse
26064                         // in case one of the children is better.
26065                         forEachChild(child, visit);
26066                         // Once we look at the children of this node, then there's no need to
26067                         // continue any further.
26068                         return true;
26069                     }
26070                     else {
26071                         ts.Debug.assert(child.end <= position);
26072                         // The child ends entirely before this position.  Say you have the following
26073                         // (where $ is the position)
26074                         //
26075                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
26076                         //
26077                         // We would want to find the nearest preceding node in "complex expr 2".
26078                         // To support that, we keep track of this node, and once we're done searching
26079                         // for a best node, we recurse down this node to see if we can find a good
26080                         // result in it.
26081                         //
26082                         // This approach allows us to quickly skip over nodes that are entirely
26083                         // before the position, while still allowing us to find any nodes in the
26084                         // last one that might be what we want.
26085                         lastNodeEntirelyBeforePosition = child;
26086                     }
26087                 }
26088                 else {
26089                     ts.Debug.assert(child.pos > position);
26090                     // We're now at a node that is entirely past the position we're searching for.
26091                     // This node (and all following nodes) could never contribute to the result,
26092                     // so just skip them by returning 'true' here.
26093                     return true;
26094                 }
26095             }
26096         }
26097         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
26098             var oldText = sourceFile.text;
26099             if (textChangeRange) {
26100                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
26101                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
26102                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
26103                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
26104                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
26105                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
26106                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
26107                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
26108                 }
26109             }
26110         }
26111         function createSyntaxCursor(sourceFile) {
26112             var currentArray = sourceFile.statements;
26113             var currentArrayIndex = 0;
26114             ts.Debug.assert(currentArrayIndex < currentArray.length);
26115             var current = currentArray[currentArrayIndex];
26116             var lastQueriedPosition = -1 /* Value */;
26117             return {
26118                 currentNode: function (position) {
26119                     // Only compute the current node if the position is different than the last time
26120                     // we were asked.  The parser commonly asks for the node at the same position
26121                     // twice.  Once to know if can read an appropriate list element at a certain point,
26122                     // and then to actually read and consume the node.
26123                     if (position !== lastQueriedPosition) {
26124                         // Much of the time the parser will need the very next node in the array that
26125                         // we just returned a node from.So just simply check for that case and move
26126                         // forward in the array instead of searching for the node again.
26127                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
26128                             currentArrayIndex++;
26129                             current = currentArray[currentArrayIndex];
26130                         }
26131                         // If we don't have a node, or the node we have isn't in the right position,
26132                         // then try to find a viable node at the position requested.
26133                         if (!current || current.pos !== position) {
26134                             findHighestListElementThatStartsAtPosition(position);
26135                         }
26136                     }
26137                     // Cache this query so that we don't do any extra work if the parser calls back
26138                     // into us.  Note: this is very common as the parser will make pairs of calls like
26139                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
26140                     // called with 'isListElement', we don't want to redo the work when parseListElement
26141                     // is called immediately after.
26142                     lastQueriedPosition = position;
26143                     // Either we don'd have a node, or we have a node at the position being asked for.
26144                     ts.Debug.assert(!current || current.pos === position);
26145                     return current;
26146                 }
26147             };
26148             // Finds the highest element in the tree we can find that starts at the provided position.
26149             // The element must be a direct child of some node list in the tree.  This way after we
26150             // return it, we can easily return its next sibling in the list.
26151             function findHighestListElementThatStartsAtPosition(position) {
26152                 // Clear out any cached state about the last node we found.
26153                 currentArray = undefined;
26154                 currentArrayIndex = -1 /* Value */;
26155                 current = undefined;
26156                 // Recurse into the source file to find the highest node at this position.
26157                 forEachChild(sourceFile, visitNode, visitArray);
26158                 return;
26159                 function visitNode(node) {
26160                     if (position >= node.pos && position < node.end) {
26161                         // Position was within this node.  Keep searching deeper to find the node.
26162                         forEachChild(node, visitNode, visitArray);
26163                         // don't proceed any further in the search.
26164                         return true;
26165                     }
26166                     // position wasn't in this node, have to keep searching.
26167                     return false;
26168                 }
26169                 function visitArray(array) {
26170                     if (position >= array.pos && position < array.end) {
26171                         // position was in this array.  Search through this array to see if we find a
26172                         // viable element.
26173                         for (var i = 0; i < array.length; i++) {
26174                             var child = array[i];
26175                             if (child) {
26176                                 if (child.pos === position) {
26177                                     // Found the right node.  We're done.
26178                                     currentArray = array;
26179                                     currentArrayIndex = i;
26180                                     current = child;
26181                                     return true;
26182                                 }
26183                                 else {
26184                                     if (child.pos < position && position < child.end) {
26185                                         // Position in somewhere within this child.  Search in it and
26186                                         // stop searching in this array.
26187                                         forEachChild(child, visitNode, visitArray);
26188                                         return true;
26189                                     }
26190                                 }
26191                             }
26192                         }
26193                     }
26194                     // position wasn't in this array, have to keep searching.
26195                     return false;
26196                 }
26197             }
26198         }
26199         var InvalidPosition;
26200         (function (InvalidPosition) {
26201             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
26202         })(InvalidPosition || (InvalidPosition = {}));
26203     })(IncrementalParser || (IncrementalParser = {}));
26204     /** @internal */
26205     function isDeclarationFileName(fileName) {
26206         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
26207     }
26208     ts.isDeclarationFileName = isDeclarationFileName;
26209     /*@internal*/
26210     function processCommentPragmas(context, sourceText) {
26211         var pragmas = [];
26212         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
26213             var range = _a[_i];
26214             var comment = sourceText.substring(range.pos, range.end);
26215             extractPragmas(pragmas, range, comment);
26216         }
26217         context.pragmas = ts.createMap();
26218         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
26219             var pragma = pragmas_1[_b];
26220             if (context.pragmas.has(pragma.name)) {
26221                 var currentValue = context.pragmas.get(pragma.name);
26222                 if (currentValue instanceof Array) {
26223                     currentValue.push(pragma.args);
26224                 }
26225                 else {
26226                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
26227                 }
26228                 continue;
26229             }
26230             context.pragmas.set(pragma.name, pragma.args);
26231         }
26232     }
26233     ts.processCommentPragmas = processCommentPragmas;
26234     /*@internal*/
26235     function processPragmasIntoFields(context, reportDiagnostic) {
26236         context.checkJsDirective = undefined;
26237         context.referencedFiles = [];
26238         context.typeReferenceDirectives = [];
26239         context.libReferenceDirectives = [];
26240         context.amdDependencies = [];
26241         context.hasNoDefaultLib = false;
26242         context.pragmas.forEach(function (entryOrList, key) {
26243             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
26244             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
26245             switch (key) {
26246                 case "reference": {
26247                     var referencedFiles_1 = context.referencedFiles;
26248                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
26249                     var libReferenceDirectives_1 = context.libReferenceDirectives;
26250                     ts.forEach(ts.toArray(entryOrList), function (arg) {
26251                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
26252                         if (arg.arguments["no-default-lib"]) {
26253                             context.hasNoDefaultLib = true;
26254                         }
26255                         else if (types) {
26256                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
26257                         }
26258                         else if (lib) {
26259                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
26260                         }
26261                         else if (path) {
26262                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
26263                         }
26264                         else {
26265                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
26266                         }
26267                     });
26268                     break;
26269                 }
26270                 case "amd-dependency": {
26271                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
26272                     break;
26273                 }
26274                 case "amd-module": {
26275                     if (entryOrList instanceof Array) {
26276                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
26277                             var entry = entryOrList_1[_i];
26278                             if (context.moduleName) {
26279                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
26280                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
26281                             }
26282                             context.moduleName = entry.arguments.name;
26283                         }
26284                     }
26285                     else {
26286                         context.moduleName = entryOrList.arguments.name;
26287                     }
26288                     break;
26289                 }
26290                 case "ts-nocheck":
26291                 case "ts-check": {
26292                     // _last_ of either nocheck or check in a file is the "winner"
26293                     ts.forEach(ts.toArray(entryOrList), function (entry) {
26294                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
26295                             context.checkJsDirective = {
26296                                 enabled: key === "ts-check",
26297                                 end: entry.range.end,
26298                                 pos: entry.range.pos
26299                             };
26300                         }
26301                     });
26302                     break;
26303                 }
26304                 case "jsx": return; // Accessed directly
26305                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
26306             }
26307         });
26308     }
26309     ts.processPragmasIntoFields = processPragmasIntoFields;
26310     var namedArgRegExCache = ts.createMap();
26311     function getNamedArgRegEx(name) {
26312         if (namedArgRegExCache.has(name)) {
26313             return namedArgRegExCache.get(name);
26314         }
26315         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
26316         namedArgRegExCache.set(name, result);
26317         return result;
26318     }
26319     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
26320     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
26321     function extractPragmas(pragmas, range, text) {
26322         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
26323         if (tripleSlash) {
26324             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
26325             var pragma = ts.commentPragmas[name];
26326             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
26327                 return;
26328             }
26329             if (pragma.args) {
26330                 var argument = {};
26331                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
26332                     var arg = _a[_i];
26333                     var matcher = getNamedArgRegEx(arg.name);
26334                     var matchResult = matcher.exec(text);
26335                     if (!matchResult && !arg.optional) {
26336                         return; // Missing required argument, don't parse
26337                     }
26338                     else if (matchResult) {
26339                         if (arg.captureSpan) {
26340                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
26341                             argument[arg.name] = {
26342                                 value: matchResult[3],
26343                                 pos: startPos,
26344                                 end: startPos + matchResult[3].length
26345                             };
26346                         }
26347                         else {
26348                             argument[arg.name] = matchResult[3];
26349                         }
26350                     }
26351                 }
26352                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
26353             }
26354             else {
26355                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
26356             }
26357             return;
26358         }
26359         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
26360         if (singleLine) {
26361             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
26362         }
26363         if (range.kind === 3 /* MultiLineCommentTrivia */) {
26364             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
26365             var multiLineMatch = void 0;
26366             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
26367                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
26368             }
26369         }
26370     }
26371     function addPragmaForMatch(pragmas, range, kind, match) {
26372         if (!match)
26373             return;
26374         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
26375         var pragma = ts.commentPragmas[name];
26376         if (!pragma || !(pragma.kind & kind)) {
26377             return;
26378         }
26379         var args = match[2]; // Split on spaces and match up positionally with definition
26380         var argument = getNamedPragmaArguments(pragma, args);
26381         if (argument === "fail")
26382             return; // Missing required argument, fail to parse it
26383         pragmas.push({ name: name, args: { arguments: argument, range: range } });
26384         return;
26385     }
26386     function getNamedPragmaArguments(pragma, text) {
26387         if (!text)
26388             return {};
26389         if (!pragma.args)
26390             return {};
26391         var args = text.split(/\s+/);
26392         var argMap = {};
26393         for (var i = 0; i < pragma.args.length; i++) {
26394             var argument = pragma.args[i];
26395             if (!args[i] && !argument.optional) {
26396                 return "fail";
26397             }
26398             if (argument.captureSpan) {
26399                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
26400             }
26401             argMap[argument.name] = args[i];
26402         }
26403         return argMap;
26404     }
26405     /** @internal */
26406     function tagNamesAreEquivalent(lhs, rhs) {
26407         if (lhs.kind !== rhs.kind) {
26408             return false;
26409         }
26410         if (lhs.kind === 75 /* Identifier */) {
26411             return lhs.escapedText === rhs.escapedText;
26412         }
26413         if (lhs.kind === 104 /* ThisKeyword */) {
26414             return true;
26415         }
26416         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
26417         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
26418         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
26419         return lhs.name.escapedText === rhs.name.escapedText &&
26420             tagNamesAreEquivalent(lhs.expression, rhs.expression);
26421     }
26422     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
26423 })(ts || (ts = {}));
26424 var ts;
26425 (function (ts) {
26426     /* @internal */
26427     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
26428     // NOTE: The order here is important to default lib ordering as entries will have the same
26429     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
26430     //       order also affects overload resolution when a type declared in one lib is
26431     //       augmented in another lib.
26432     var libEntries = [
26433         // JavaScript only
26434         ["es5", "lib.es5.d.ts"],
26435         ["es6", "lib.es2015.d.ts"],
26436         ["es2015", "lib.es2015.d.ts"],
26437         ["es7", "lib.es2016.d.ts"],
26438         ["es2016", "lib.es2016.d.ts"],
26439         ["es2017", "lib.es2017.d.ts"],
26440         ["es2018", "lib.es2018.d.ts"],
26441         ["es2019", "lib.es2019.d.ts"],
26442         ["es2020", "lib.es2020.d.ts"],
26443         ["esnext", "lib.esnext.d.ts"],
26444         // Host only
26445         ["dom", "lib.dom.d.ts"],
26446         ["dom.iterable", "lib.dom.iterable.d.ts"],
26447         ["webworker", "lib.webworker.d.ts"],
26448         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
26449         ["scripthost", "lib.scripthost.d.ts"],
26450         // ES2015 Or ESNext By-feature options
26451         ["es2015.core", "lib.es2015.core.d.ts"],
26452         ["es2015.collection", "lib.es2015.collection.d.ts"],
26453         ["es2015.generator", "lib.es2015.generator.d.ts"],
26454         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
26455         ["es2015.promise", "lib.es2015.promise.d.ts"],
26456         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
26457         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
26458         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
26459         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
26460         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
26461         ["es2017.object", "lib.es2017.object.d.ts"],
26462         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
26463         ["es2017.string", "lib.es2017.string.d.ts"],
26464         ["es2017.intl", "lib.es2017.intl.d.ts"],
26465         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
26466         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
26467         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
26468         ["es2018.intl", "lib.es2018.intl.d.ts"],
26469         ["es2018.promise", "lib.es2018.promise.d.ts"],
26470         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
26471         ["es2019.array", "lib.es2019.array.d.ts"],
26472         ["es2019.object", "lib.es2019.object.d.ts"],
26473         ["es2019.string", "lib.es2019.string.d.ts"],
26474         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
26475         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
26476         ["es2020.promise", "lib.es2020.promise.d.ts"],
26477         ["es2020.string", "lib.es2020.string.d.ts"],
26478         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
26479         ["esnext.array", "lib.es2019.array.d.ts"],
26480         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
26481         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
26482         ["esnext.intl", "lib.esnext.intl.d.ts"],
26483         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
26484         ["esnext.string", "lib.esnext.string.d.ts"],
26485         ["esnext.promise", "lib.esnext.promise.d.ts"]
26486     ];
26487     /**
26488      * An array of supported "lib" reference file names used to determine the order for inclusion
26489      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
26490      * overload resolution when a type declared in one lib is extended by another.
26491      */
26492     /* @internal */
26493     ts.libs = libEntries.map(function (entry) { return entry[0]; });
26494     /**
26495      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
26496      * option as well as for resolving lib reference directives.
26497      */
26498     /* @internal */
26499     ts.libMap = ts.createMapFromEntries(libEntries);
26500     // Watch related options
26501     /* @internal */
26502     ts.optionsForWatch = [
26503         {
26504             name: "watchFile",
26505             type: ts.createMapFromTemplate({
26506                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
26507                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
26508                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
26509                 usefsevents: ts.WatchFileKind.UseFsEvents,
26510                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
26511             }),
26512             category: ts.Diagnostics.Advanced_Options,
26513             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
26514         },
26515         {
26516             name: "watchDirectory",
26517             type: ts.createMapFromTemplate({
26518                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
26519                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
26520                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
26521             }),
26522             category: ts.Diagnostics.Advanced_Options,
26523             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
26524         },
26525         {
26526             name: "fallbackPolling",
26527             type: ts.createMapFromTemplate({
26528                 fixedinterval: ts.PollingWatchKind.FixedInterval,
26529                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
26530                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
26531             }),
26532             category: ts.Diagnostics.Advanced_Options,
26533             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
26534         },
26535         {
26536             name: "synchronousWatchDirectory",
26537             type: "boolean",
26538             category: ts.Diagnostics.Advanced_Options,
26539             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
26540         },
26541     ];
26542     /* @internal */
26543     ts.commonOptionsWithBuild = [
26544         {
26545             name: "help",
26546             shortName: "h",
26547             type: "boolean",
26548             showInSimplifiedHelpView: true,
26549             category: ts.Diagnostics.Command_line_Options,
26550             description: ts.Diagnostics.Print_this_message,
26551         },
26552         {
26553             name: "help",
26554             shortName: "?",
26555             type: "boolean"
26556         },
26557         {
26558             name: "watch",
26559             shortName: "w",
26560             type: "boolean",
26561             showInSimplifiedHelpView: true,
26562             category: ts.Diagnostics.Command_line_Options,
26563             description: ts.Diagnostics.Watch_input_files,
26564         },
26565         {
26566             name: "preserveWatchOutput",
26567             type: "boolean",
26568             showInSimplifiedHelpView: false,
26569             category: ts.Diagnostics.Command_line_Options,
26570             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
26571         },
26572         {
26573             name: "listFiles",
26574             type: "boolean",
26575             category: ts.Diagnostics.Advanced_Options,
26576             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
26577         },
26578         {
26579             name: "listEmittedFiles",
26580             type: "boolean",
26581             category: ts.Diagnostics.Advanced_Options,
26582             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
26583         },
26584         {
26585             name: "pretty",
26586             type: "boolean",
26587             showInSimplifiedHelpView: true,
26588             category: ts.Diagnostics.Command_line_Options,
26589             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
26590         },
26591         {
26592             name: "traceResolution",
26593             type: "boolean",
26594             category: ts.Diagnostics.Advanced_Options,
26595             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
26596         },
26597         {
26598             name: "diagnostics",
26599             type: "boolean",
26600             category: ts.Diagnostics.Advanced_Options,
26601             description: ts.Diagnostics.Show_diagnostic_information
26602         },
26603         {
26604             name: "extendedDiagnostics",
26605             type: "boolean",
26606             category: ts.Diagnostics.Advanced_Options,
26607             description: ts.Diagnostics.Show_verbose_diagnostic_information
26608         },
26609         {
26610             name: "generateCpuProfile",
26611             type: "string",
26612             isFilePath: true,
26613             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26614             category: ts.Diagnostics.Advanced_Options,
26615             description: ts.Diagnostics.Generates_a_CPU_profile
26616         },
26617         {
26618             name: "incremental",
26619             shortName: "i",
26620             type: "boolean",
26621             category: ts.Diagnostics.Basic_Options,
26622             description: ts.Diagnostics.Enable_incremental_compilation,
26623             transpileOptionValue: undefined
26624         },
26625         {
26626             name: "assumeChangesOnlyAffectDirectDependencies",
26627             type: "boolean",
26628             affectsSemanticDiagnostics: true,
26629             affectsEmit: true,
26630             category: ts.Diagnostics.Advanced_Options,
26631             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
26632         },
26633         {
26634             name: "locale",
26635             type: "string",
26636             category: ts.Diagnostics.Advanced_Options,
26637             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
26638         },
26639     ];
26640     /* @internal */
26641     ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
26642         {
26643             name: "all",
26644             type: "boolean",
26645             showInSimplifiedHelpView: true,
26646             category: ts.Diagnostics.Command_line_Options,
26647             description: ts.Diagnostics.Show_all_compiler_options,
26648         },
26649         {
26650             name: "version",
26651             shortName: "v",
26652             type: "boolean",
26653             showInSimplifiedHelpView: true,
26654             category: ts.Diagnostics.Command_line_Options,
26655             description: ts.Diagnostics.Print_the_compiler_s_version,
26656         },
26657         {
26658             name: "init",
26659             type: "boolean",
26660             showInSimplifiedHelpView: true,
26661             category: ts.Diagnostics.Command_line_Options,
26662             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
26663         },
26664         {
26665             name: "project",
26666             shortName: "p",
26667             type: "string",
26668             isFilePath: true,
26669             showInSimplifiedHelpView: true,
26670             category: ts.Diagnostics.Command_line_Options,
26671             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26672             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
26673         },
26674         {
26675             name: "build",
26676             type: "boolean",
26677             shortName: "b",
26678             showInSimplifiedHelpView: true,
26679             category: ts.Diagnostics.Command_line_Options,
26680             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
26681         },
26682         {
26683             name: "showConfig",
26684             type: "boolean",
26685             category: ts.Diagnostics.Command_line_Options,
26686             isCommandLineOnly: true,
26687             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
26688         },
26689         {
26690             name: "listFilesOnly",
26691             type: "boolean",
26692             category: ts.Diagnostics.Command_line_Options,
26693             affectsSemanticDiagnostics: true,
26694             affectsEmit: true,
26695             isCommandLineOnly: true,
26696             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
26697         },
26698         // Basic
26699         {
26700             name: "target",
26701             shortName: "t",
26702             type: ts.createMapFromTemplate({
26703                 es3: 0 /* ES3 */,
26704                 es5: 1 /* ES5 */,
26705                 es6: 2 /* ES2015 */,
26706                 es2015: 2 /* ES2015 */,
26707                 es2016: 3 /* ES2016 */,
26708                 es2017: 4 /* ES2017 */,
26709                 es2018: 5 /* ES2018 */,
26710                 es2019: 6 /* ES2019 */,
26711                 es2020: 7 /* ES2020 */,
26712                 esnext: 99 /* ESNext */,
26713             }),
26714             affectsSourceFile: true,
26715             affectsModuleResolution: true,
26716             affectsEmit: true,
26717             paramType: ts.Diagnostics.VERSION,
26718             showInSimplifiedHelpView: true,
26719             category: ts.Diagnostics.Basic_Options,
26720             description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
26721         },
26722         {
26723             name: "module",
26724             shortName: "m",
26725             type: ts.createMapFromTemplate({
26726                 none: ts.ModuleKind.None,
26727                 commonjs: ts.ModuleKind.CommonJS,
26728                 amd: ts.ModuleKind.AMD,
26729                 system: ts.ModuleKind.System,
26730                 umd: ts.ModuleKind.UMD,
26731                 es6: ts.ModuleKind.ES2015,
26732                 es2015: ts.ModuleKind.ES2015,
26733                 es2020: ts.ModuleKind.ES2020,
26734                 esnext: ts.ModuleKind.ESNext
26735             }),
26736             affectsModuleResolution: true,
26737             affectsEmit: true,
26738             paramType: ts.Diagnostics.KIND,
26739             showInSimplifiedHelpView: true,
26740             category: ts.Diagnostics.Basic_Options,
26741             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
26742         },
26743         {
26744             name: "lib",
26745             type: "list",
26746             element: {
26747                 name: "lib",
26748                 type: ts.libMap
26749             },
26750             affectsModuleResolution: true,
26751             showInSimplifiedHelpView: true,
26752             category: ts.Diagnostics.Basic_Options,
26753             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
26754             transpileOptionValue: undefined
26755         },
26756         {
26757             name: "allowJs",
26758             type: "boolean",
26759             affectsModuleResolution: true,
26760             showInSimplifiedHelpView: true,
26761             category: ts.Diagnostics.Basic_Options,
26762             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
26763         },
26764         {
26765             name: "checkJs",
26766             type: "boolean",
26767             category: ts.Diagnostics.Basic_Options,
26768             description: ts.Diagnostics.Report_errors_in_js_files
26769         },
26770         {
26771             name: "jsx",
26772             type: ts.createMapFromTemplate({
26773                 "preserve": 1 /* Preserve */,
26774                 "react-native": 3 /* ReactNative */,
26775                 "react": 2 /* React */
26776             }),
26777             affectsSourceFile: true,
26778             paramType: ts.Diagnostics.KIND,
26779             showInSimplifiedHelpView: true,
26780             category: ts.Diagnostics.Basic_Options,
26781             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
26782         },
26783         {
26784             name: "declaration",
26785             shortName: "d",
26786             type: "boolean",
26787             affectsEmit: true,
26788             showInSimplifiedHelpView: true,
26789             category: ts.Diagnostics.Basic_Options,
26790             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
26791             transpileOptionValue: undefined
26792         },
26793         {
26794             name: "declarationMap",
26795             type: "boolean",
26796             affectsEmit: true,
26797             showInSimplifiedHelpView: true,
26798             category: ts.Diagnostics.Basic_Options,
26799             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
26800             transpileOptionValue: undefined
26801         },
26802         {
26803             name: "emitDeclarationOnly",
26804             type: "boolean",
26805             affectsEmit: true,
26806             category: ts.Diagnostics.Advanced_Options,
26807             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
26808             transpileOptionValue: undefined
26809         },
26810         {
26811             name: "sourceMap",
26812             type: "boolean",
26813             affectsEmit: true,
26814             showInSimplifiedHelpView: true,
26815             category: ts.Diagnostics.Basic_Options,
26816             description: ts.Diagnostics.Generates_corresponding_map_file,
26817         },
26818         {
26819             name: "outFile",
26820             type: "string",
26821             affectsEmit: true,
26822             isFilePath: true,
26823             paramType: ts.Diagnostics.FILE,
26824             showInSimplifiedHelpView: true,
26825             category: ts.Diagnostics.Basic_Options,
26826             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
26827             transpileOptionValue: undefined
26828         },
26829         {
26830             name: "outDir",
26831             type: "string",
26832             affectsEmit: true,
26833             isFilePath: true,
26834             paramType: ts.Diagnostics.DIRECTORY,
26835             showInSimplifiedHelpView: true,
26836             category: ts.Diagnostics.Basic_Options,
26837             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
26838         },
26839         {
26840             name: "rootDir",
26841             type: "string",
26842             affectsEmit: true,
26843             isFilePath: true,
26844             paramType: ts.Diagnostics.LOCATION,
26845             category: ts.Diagnostics.Basic_Options,
26846             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
26847         },
26848         {
26849             name: "composite",
26850             type: "boolean",
26851             affectsEmit: true,
26852             isTSConfigOnly: true,
26853             category: ts.Diagnostics.Basic_Options,
26854             description: ts.Diagnostics.Enable_project_compilation,
26855             transpileOptionValue: undefined
26856         },
26857         {
26858             name: "tsBuildInfoFile",
26859             type: "string",
26860             affectsEmit: true,
26861             isFilePath: true,
26862             paramType: ts.Diagnostics.FILE,
26863             category: ts.Diagnostics.Basic_Options,
26864             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
26865             transpileOptionValue: undefined
26866         },
26867         {
26868             name: "removeComments",
26869             type: "boolean",
26870             affectsEmit: true,
26871             showInSimplifiedHelpView: true,
26872             category: ts.Diagnostics.Basic_Options,
26873             description: ts.Diagnostics.Do_not_emit_comments_to_output,
26874         },
26875         {
26876             name: "noEmit",
26877             type: "boolean",
26878             affectsEmit: true,
26879             showInSimplifiedHelpView: true,
26880             category: ts.Diagnostics.Basic_Options,
26881             description: ts.Diagnostics.Do_not_emit_outputs,
26882             transpileOptionValue: undefined
26883         },
26884         {
26885             name: "importHelpers",
26886             type: "boolean",
26887             affectsEmit: true,
26888             category: ts.Diagnostics.Basic_Options,
26889             description: ts.Diagnostics.Import_emit_helpers_from_tslib
26890         },
26891         {
26892             name: "importsNotUsedAsValues",
26893             type: ts.createMapFromTemplate({
26894                 remove: 0 /* Remove */,
26895                 preserve: 1 /* Preserve */,
26896                 error: 2 /* Error */
26897             }),
26898             affectsEmit: true,
26899             affectsSemanticDiagnostics: true,
26900             category: ts.Diagnostics.Advanced_Options,
26901             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
26902         },
26903         {
26904             name: "downlevelIteration",
26905             type: "boolean",
26906             affectsEmit: true,
26907             category: ts.Diagnostics.Basic_Options,
26908             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
26909         },
26910         {
26911             name: "isolatedModules",
26912             type: "boolean",
26913             category: ts.Diagnostics.Basic_Options,
26914             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
26915             transpileOptionValue: true
26916         },
26917         // Strict Type Checks
26918         {
26919             name: "strict",
26920             type: "boolean",
26921             showInSimplifiedHelpView: true,
26922             category: ts.Diagnostics.Strict_Type_Checking_Options,
26923             description: ts.Diagnostics.Enable_all_strict_type_checking_options
26924         },
26925         {
26926             name: "noImplicitAny",
26927             type: "boolean",
26928             affectsSemanticDiagnostics: true,
26929             strictFlag: true,
26930             showInSimplifiedHelpView: true,
26931             category: ts.Diagnostics.Strict_Type_Checking_Options,
26932             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
26933         },
26934         {
26935             name: "strictNullChecks",
26936             type: "boolean",
26937             affectsSemanticDiagnostics: true,
26938             strictFlag: true,
26939             showInSimplifiedHelpView: true,
26940             category: ts.Diagnostics.Strict_Type_Checking_Options,
26941             description: ts.Diagnostics.Enable_strict_null_checks
26942         },
26943         {
26944             name: "strictFunctionTypes",
26945             type: "boolean",
26946             affectsSemanticDiagnostics: true,
26947             strictFlag: true,
26948             showInSimplifiedHelpView: true,
26949             category: ts.Diagnostics.Strict_Type_Checking_Options,
26950             description: ts.Diagnostics.Enable_strict_checking_of_function_types
26951         },
26952         {
26953             name: "strictBindCallApply",
26954             type: "boolean",
26955             strictFlag: true,
26956             showInSimplifiedHelpView: true,
26957             category: ts.Diagnostics.Strict_Type_Checking_Options,
26958             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
26959         },
26960         {
26961             name: "strictPropertyInitialization",
26962             type: "boolean",
26963             affectsSemanticDiagnostics: true,
26964             strictFlag: true,
26965             showInSimplifiedHelpView: true,
26966             category: ts.Diagnostics.Strict_Type_Checking_Options,
26967             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
26968         },
26969         {
26970             name: "noImplicitThis",
26971             type: "boolean",
26972             affectsSemanticDiagnostics: true,
26973             strictFlag: true,
26974             showInSimplifiedHelpView: true,
26975             category: ts.Diagnostics.Strict_Type_Checking_Options,
26976             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
26977         },
26978         {
26979             name: "alwaysStrict",
26980             type: "boolean",
26981             affectsSourceFile: true,
26982             strictFlag: true,
26983             showInSimplifiedHelpView: true,
26984             category: ts.Diagnostics.Strict_Type_Checking_Options,
26985             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
26986         },
26987         // Additional Checks
26988         {
26989             name: "noUnusedLocals",
26990             type: "boolean",
26991             affectsSemanticDiagnostics: true,
26992             showInSimplifiedHelpView: true,
26993             category: ts.Diagnostics.Additional_Checks,
26994             description: ts.Diagnostics.Report_errors_on_unused_locals,
26995         },
26996         {
26997             name: "noUnusedParameters",
26998             type: "boolean",
26999             affectsSemanticDiagnostics: true,
27000             showInSimplifiedHelpView: true,
27001             category: ts.Diagnostics.Additional_Checks,
27002             description: ts.Diagnostics.Report_errors_on_unused_parameters,
27003         },
27004         {
27005             name: "noImplicitReturns",
27006             type: "boolean",
27007             affectsSemanticDiagnostics: true,
27008             showInSimplifiedHelpView: true,
27009             category: ts.Diagnostics.Additional_Checks,
27010             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
27011         },
27012         {
27013             name: "noFallthroughCasesInSwitch",
27014             type: "boolean",
27015             affectsBindDiagnostics: true,
27016             affectsSemanticDiagnostics: true,
27017             showInSimplifiedHelpView: true,
27018             category: ts.Diagnostics.Additional_Checks,
27019             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
27020         },
27021         // Module Resolution
27022         {
27023             name: "moduleResolution",
27024             type: ts.createMapFromTemplate({
27025                 node: ts.ModuleResolutionKind.NodeJs,
27026                 classic: ts.ModuleResolutionKind.Classic,
27027             }),
27028             affectsModuleResolution: true,
27029             paramType: ts.Diagnostics.STRATEGY,
27030             category: ts.Diagnostics.Module_Resolution_Options,
27031             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
27032         },
27033         {
27034             name: "baseUrl",
27035             type: "string",
27036             affectsModuleResolution: true,
27037             isFilePath: true,
27038             category: ts.Diagnostics.Module_Resolution_Options,
27039             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
27040         },
27041         {
27042             // this option can only be specified in tsconfig.json
27043             // use type = object to copy the value as-is
27044             name: "paths",
27045             type: "object",
27046             affectsModuleResolution: true,
27047             isTSConfigOnly: true,
27048             category: ts.Diagnostics.Module_Resolution_Options,
27049             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
27050             transpileOptionValue: undefined
27051         },
27052         {
27053             // this option can only be specified in tsconfig.json
27054             // use type = object to copy the value as-is
27055             name: "rootDirs",
27056             type: "list",
27057             isTSConfigOnly: true,
27058             element: {
27059                 name: "rootDirs",
27060                 type: "string",
27061                 isFilePath: true
27062             },
27063             affectsModuleResolution: true,
27064             category: ts.Diagnostics.Module_Resolution_Options,
27065             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
27066             transpileOptionValue: undefined
27067         },
27068         {
27069             name: "typeRoots",
27070             type: "list",
27071             element: {
27072                 name: "typeRoots",
27073                 type: "string",
27074                 isFilePath: true
27075             },
27076             affectsModuleResolution: true,
27077             category: ts.Diagnostics.Module_Resolution_Options,
27078             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
27079         },
27080         {
27081             name: "types",
27082             type: "list",
27083             element: {
27084                 name: "types",
27085                 type: "string"
27086             },
27087             affectsModuleResolution: true,
27088             showInSimplifiedHelpView: true,
27089             category: ts.Diagnostics.Module_Resolution_Options,
27090             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
27091             transpileOptionValue: undefined
27092         },
27093         {
27094             name: "allowSyntheticDefaultImports",
27095             type: "boolean",
27096             affectsSemanticDiagnostics: true,
27097             category: ts.Diagnostics.Module_Resolution_Options,
27098             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
27099         },
27100         {
27101             name: "esModuleInterop",
27102             type: "boolean",
27103             affectsSemanticDiagnostics: true,
27104             affectsEmit: true,
27105             showInSimplifiedHelpView: true,
27106             category: ts.Diagnostics.Module_Resolution_Options,
27107             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
27108         },
27109         {
27110             name: "preserveSymlinks",
27111             type: "boolean",
27112             category: ts.Diagnostics.Module_Resolution_Options,
27113             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
27114         },
27115         {
27116             name: "allowUmdGlobalAccess",
27117             type: "boolean",
27118             affectsSemanticDiagnostics: true,
27119             category: ts.Diagnostics.Module_Resolution_Options,
27120             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
27121         },
27122         // Source Maps
27123         {
27124             name: "sourceRoot",
27125             type: "string",
27126             affectsEmit: true,
27127             paramType: ts.Diagnostics.LOCATION,
27128             category: ts.Diagnostics.Source_Map_Options,
27129             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
27130         },
27131         {
27132             name: "mapRoot",
27133             type: "string",
27134             affectsEmit: true,
27135             paramType: ts.Diagnostics.LOCATION,
27136             category: ts.Diagnostics.Source_Map_Options,
27137             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
27138         },
27139         {
27140             name: "inlineSourceMap",
27141             type: "boolean",
27142             affectsEmit: true,
27143             category: ts.Diagnostics.Source_Map_Options,
27144             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
27145         },
27146         {
27147             name: "inlineSources",
27148             type: "boolean",
27149             affectsEmit: true,
27150             category: ts.Diagnostics.Source_Map_Options,
27151             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
27152         },
27153         // Experimental
27154         {
27155             name: "experimentalDecorators",
27156             type: "boolean",
27157             affectsSemanticDiagnostics: true,
27158             category: ts.Diagnostics.Experimental_Options,
27159             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
27160         },
27161         {
27162             name: "emitDecoratorMetadata",
27163             type: "boolean",
27164             affectsSemanticDiagnostics: true,
27165             affectsEmit: true,
27166             category: ts.Diagnostics.Experimental_Options,
27167             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
27168         },
27169         // Advanced
27170         {
27171             name: "jsxFactory",
27172             type: "string",
27173             category: ts.Diagnostics.Advanced_Options,
27174             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
27175         },
27176         {
27177             name: "resolveJsonModule",
27178             type: "boolean",
27179             affectsModuleResolution: true,
27180             category: ts.Diagnostics.Advanced_Options,
27181             description: ts.Diagnostics.Include_modules_imported_with_json_extension
27182         },
27183         {
27184             name: "out",
27185             type: "string",
27186             affectsEmit: true,
27187             isFilePath: false,
27188             // for correct behaviour, please use outFile
27189             category: ts.Diagnostics.Advanced_Options,
27190             paramType: ts.Diagnostics.FILE,
27191             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
27192             transpileOptionValue: undefined
27193         },
27194         {
27195             name: "reactNamespace",
27196             type: "string",
27197             affectsEmit: true,
27198             category: ts.Diagnostics.Advanced_Options,
27199             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
27200         },
27201         {
27202             name: "skipDefaultLibCheck",
27203             type: "boolean",
27204             category: ts.Diagnostics.Advanced_Options,
27205             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
27206         },
27207         {
27208             name: "charset",
27209             type: "string",
27210             category: ts.Diagnostics.Advanced_Options,
27211             description: ts.Diagnostics.The_character_set_of_the_input_files
27212         },
27213         {
27214             name: "emitBOM",
27215             type: "boolean",
27216             affectsEmit: true,
27217             category: ts.Diagnostics.Advanced_Options,
27218             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
27219         },
27220         {
27221             name: "newLine",
27222             type: ts.createMapFromTemplate({
27223                 crlf: 0 /* CarriageReturnLineFeed */,
27224                 lf: 1 /* LineFeed */
27225             }),
27226             affectsEmit: true,
27227             paramType: ts.Diagnostics.NEWLINE,
27228             category: ts.Diagnostics.Advanced_Options,
27229             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
27230         },
27231         {
27232             name: "noErrorTruncation",
27233             type: "boolean",
27234             affectsSemanticDiagnostics: true,
27235             category: ts.Diagnostics.Advanced_Options,
27236             description: ts.Diagnostics.Do_not_truncate_error_messages
27237         },
27238         {
27239             name: "noLib",
27240             type: "boolean",
27241             affectsModuleResolution: true,
27242             category: ts.Diagnostics.Advanced_Options,
27243             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
27244             // We are not returning a sourceFile for lib file when asked by the program,
27245             // so pass --noLib to avoid reporting a file not found error.
27246             transpileOptionValue: true
27247         },
27248         {
27249             name: "noResolve",
27250             type: "boolean",
27251             affectsModuleResolution: true,
27252             category: ts.Diagnostics.Advanced_Options,
27253             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
27254             // We are not doing a full typecheck, we are not resolving the whole context,
27255             // so pass --noResolve to avoid reporting missing file errors.
27256             transpileOptionValue: true
27257         },
27258         {
27259             name: "stripInternal",
27260             type: "boolean",
27261             affectsEmit: true,
27262             category: ts.Diagnostics.Advanced_Options,
27263             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
27264         },
27265         {
27266             name: "disableSizeLimit",
27267             type: "boolean",
27268             affectsSourceFile: true,
27269             category: ts.Diagnostics.Advanced_Options,
27270             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
27271         },
27272         {
27273             name: "disableSourceOfProjectReferenceRedirect",
27274             type: "boolean",
27275             isTSConfigOnly: true,
27276             category: ts.Diagnostics.Advanced_Options,
27277             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
27278         },
27279         {
27280             name: "disableSolutionSearching",
27281             type: "boolean",
27282             isTSConfigOnly: true,
27283             category: ts.Diagnostics.Advanced_Options,
27284             description: ts.Diagnostics.Disable_solution_searching_for_this_project
27285         },
27286         {
27287             name: "noImplicitUseStrict",
27288             type: "boolean",
27289             affectsSemanticDiagnostics: true,
27290             category: ts.Diagnostics.Advanced_Options,
27291             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
27292         },
27293         {
27294             name: "noEmitHelpers",
27295             type: "boolean",
27296             affectsEmit: true,
27297             category: ts.Diagnostics.Advanced_Options,
27298             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
27299         },
27300         {
27301             name: "noEmitOnError",
27302             type: "boolean",
27303             affectsEmit: true,
27304             category: ts.Diagnostics.Advanced_Options,
27305             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
27306             transpileOptionValue: undefined
27307         },
27308         {
27309             name: "preserveConstEnums",
27310             type: "boolean",
27311             affectsEmit: true,
27312             category: ts.Diagnostics.Advanced_Options,
27313             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
27314         },
27315         {
27316             name: "declarationDir",
27317             type: "string",
27318             affectsEmit: true,
27319             isFilePath: true,
27320             paramType: ts.Diagnostics.DIRECTORY,
27321             category: ts.Diagnostics.Advanced_Options,
27322             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
27323             transpileOptionValue: undefined
27324         },
27325         {
27326             name: "skipLibCheck",
27327             type: "boolean",
27328             category: ts.Diagnostics.Advanced_Options,
27329             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
27330         },
27331         {
27332             name: "allowUnusedLabels",
27333             type: "boolean",
27334             affectsBindDiagnostics: true,
27335             affectsSemanticDiagnostics: true,
27336             category: ts.Diagnostics.Advanced_Options,
27337             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
27338         },
27339         {
27340             name: "allowUnreachableCode",
27341             type: "boolean",
27342             affectsBindDiagnostics: true,
27343             affectsSemanticDiagnostics: true,
27344             category: ts.Diagnostics.Advanced_Options,
27345             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
27346         },
27347         {
27348             name: "suppressExcessPropertyErrors",
27349             type: "boolean",
27350             affectsSemanticDiagnostics: true,
27351             category: ts.Diagnostics.Advanced_Options,
27352             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
27353         },
27354         {
27355             name: "suppressImplicitAnyIndexErrors",
27356             type: "boolean",
27357             affectsSemanticDiagnostics: true,
27358             category: ts.Diagnostics.Advanced_Options,
27359             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
27360         },
27361         {
27362             name: "forceConsistentCasingInFileNames",
27363             type: "boolean",
27364             affectsModuleResolution: true,
27365             category: ts.Diagnostics.Advanced_Options,
27366             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
27367         },
27368         {
27369             name: "maxNodeModuleJsDepth",
27370             type: "number",
27371             affectsModuleResolution: true,
27372             category: ts.Diagnostics.Advanced_Options,
27373             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
27374         },
27375         {
27376             name: "noStrictGenericChecks",
27377             type: "boolean",
27378             affectsSemanticDiagnostics: true,
27379             category: ts.Diagnostics.Advanced_Options,
27380             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
27381         },
27382         {
27383             name: "useDefineForClassFields",
27384             type: "boolean",
27385             affectsSemanticDiagnostics: true,
27386             affectsEmit: true,
27387             category: ts.Diagnostics.Advanced_Options,
27388             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
27389         },
27390         {
27391             name: "keyofStringsOnly",
27392             type: "boolean",
27393             category: ts.Diagnostics.Advanced_Options,
27394             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
27395         },
27396         {
27397             // A list of plugins to load in the language service
27398             name: "plugins",
27399             type: "list",
27400             isTSConfigOnly: true,
27401             element: {
27402                 name: "plugin",
27403                 type: "object"
27404             },
27405             description: ts.Diagnostics.List_of_language_service_plugins
27406         },
27407     ]);
27408     /* @internal */
27409     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
27410     /* @internal */
27411     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
27412     /* @internal */
27413     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
27414     /* @internal */
27415     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
27416         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
27417     });
27418     /* @internal */
27419     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
27420         return ts.hasProperty(option, "transpileOptionValue");
27421     });
27422     /* @internal */
27423     ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
27424         {
27425             name: "verbose",
27426             shortName: "v",
27427             category: ts.Diagnostics.Command_line_Options,
27428             description: ts.Diagnostics.Enable_verbose_logging,
27429             type: "boolean"
27430         },
27431         {
27432             name: "dry",
27433             shortName: "d",
27434             category: ts.Diagnostics.Command_line_Options,
27435             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
27436             type: "boolean"
27437         },
27438         {
27439             name: "force",
27440             shortName: "f",
27441             category: ts.Diagnostics.Command_line_Options,
27442             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
27443             type: "boolean"
27444         },
27445         {
27446             name: "clean",
27447             category: ts.Diagnostics.Command_line_Options,
27448             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
27449             type: "boolean"
27450         }
27451     ]);
27452     /* @internal */
27453     ts.typeAcquisitionDeclarations = [
27454         {
27455             /* @deprecated typingOptions.enableAutoDiscovery
27456              * Use typeAcquisition.enable instead.
27457              */
27458             name: "enableAutoDiscovery",
27459             type: "boolean",
27460         },
27461         {
27462             name: "enable",
27463             type: "boolean",
27464         },
27465         {
27466             name: "include",
27467             type: "list",
27468             element: {
27469                 name: "include",
27470                 type: "string"
27471             }
27472         },
27473         {
27474             name: "exclude",
27475             type: "list",
27476             element: {
27477                 name: "exclude",
27478                 type: "string"
27479             }
27480         }
27481     ];
27482     /*@internal*/
27483     function createOptionNameMap(optionDeclarations) {
27484         var optionsNameMap = ts.createMap();
27485         var shortOptionNames = ts.createMap();
27486         ts.forEach(optionDeclarations, function (option) {
27487             optionsNameMap.set(option.name.toLowerCase(), option);
27488             if (option.shortName) {
27489                 shortOptionNames.set(option.shortName, option.name);
27490             }
27491         });
27492         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
27493     }
27494     ts.createOptionNameMap = createOptionNameMap;
27495     var optionsNameMapCache;
27496     /* @internal */
27497     function getOptionsNameMap() {
27498         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
27499     }
27500     ts.getOptionsNameMap = getOptionsNameMap;
27501     /* @internal */
27502     ts.defaultInitCompilerOptions = {
27503         module: ts.ModuleKind.CommonJS,
27504         target: 1 /* ES5 */,
27505         strict: true,
27506         esModuleInterop: true,
27507         forceConsistentCasingInFileNames: true,
27508         skipLibCheck: true
27509     };
27510     /* @internal */
27511     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
27512         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
27513         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
27514             return {
27515                 enable: typeAcquisition.enableAutoDiscovery,
27516                 include: typeAcquisition.include || [],
27517                 exclude: typeAcquisition.exclude || []
27518             };
27519         }
27520         return typeAcquisition;
27521     }
27522     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
27523     /* @internal */
27524     function createCompilerDiagnosticForInvalidCustomType(opt) {
27525         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
27526     }
27527     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
27528     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
27529         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
27530         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
27531     }
27532     /* @internal */
27533     function parseCustomTypeOption(opt, value, errors) {
27534         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
27535     }
27536     ts.parseCustomTypeOption = parseCustomTypeOption;
27537     /* @internal */
27538     function parseListTypeOption(opt, value, errors) {
27539         if (value === void 0) { value = ""; }
27540         value = trimString(value);
27541         if (ts.startsWith(value, "-")) {
27542             return undefined;
27543         }
27544         if (value === "") {
27545             return [];
27546         }
27547         var values = value.split(",");
27548         switch (opt.element.type) {
27549             case "number":
27550                 return ts.map(values, parseInt);
27551             case "string":
27552                 return ts.map(values, function (v) { return v || ""; });
27553             default:
27554                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
27555         }
27556     }
27557     ts.parseListTypeOption = parseListTypeOption;
27558     function getOptionName(option) {
27559         return option.name;
27560     }
27561     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
27562         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
27563         return possibleOption ?
27564             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
27565             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
27566     }
27567     /*@internal*/
27568     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
27569         var options = {};
27570         var watchOptions;
27571         var fileNames = [];
27572         var errors = [];
27573         parseStrings(commandLine);
27574         return {
27575             options: options,
27576             watchOptions: watchOptions,
27577             fileNames: fileNames,
27578             errors: errors
27579         };
27580         function parseStrings(args) {
27581             var i = 0;
27582             while (i < args.length) {
27583                 var s = args[i];
27584                 i++;
27585                 if (s.charCodeAt(0) === 64 /* at */) {
27586                     parseResponseFile(s.slice(1));
27587                 }
27588                 else if (s.charCodeAt(0) === 45 /* minus */) {
27589                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
27590                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27591                     if (opt) {
27592                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
27593                     }
27594                     else {
27595                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27596                         if (watchOpt) {
27597                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
27598                         }
27599                         else {
27600                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
27601                         }
27602                     }
27603                 }
27604                 else {
27605                     fileNames.push(s);
27606                 }
27607             }
27608         }
27609         function parseResponseFile(fileName) {
27610             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
27611             if (!ts.isString(text)) {
27612                 errors.push(text);
27613                 return;
27614             }
27615             var args = [];
27616             var pos = 0;
27617             while (true) {
27618                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
27619                     pos++;
27620                 if (pos >= text.length)
27621                     break;
27622                 var start = pos;
27623                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
27624                     pos++;
27625                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
27626                         pos++;
27627                     if (pos < text.length) {
27628                         args.push(text.substring(start + 1, pos));
27629                         pos++;
27630                     }
27631                     else {
27632                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
27633                     }
27634                 }
27635                 else {
27636                     while (text.charCodeAt(pos) > 32 /* space */)
27637                         pos++;
27638                     args.push(text.substring(start, pos));
27639                 }
27640             }
27641             parseStrings(args);
27642         }
27643     }
27644     ts.parseCommandLineWorker = parseCommandLineWorker;
27645     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
27646         if (opt.isTSConfigOnly) {
27647             var optValue = args[i];
27648             if (optValue === "null") {
27649                 options[opt.name] = undefined;
27650                 i++;
27651             }
27652             else if (opt.type === "boolean") {
27653                 if (optValue === "false") {
27654                     options[opt.name] = false;
27655                     i++;
27656                 }
27657                 else {
27658                     if (optValue === "true")
27659                         i++;
27660                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name));
27661                 }
27662             }
27663             else {
27664                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name));
27665                 if (optValue && !ts.startsWith(optValue, "-"))
27666                     i++;
27667             }
27668         }
27669         else {
27670             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
27671             if (!args[i] && opt.type !== "boolean") {
27672                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
27673             }
27674             if (args[i] !== "null") {
27675                 switch (opt.type) {
27676                     case "number":
27677                         options[opt.name] = parseInt(args[i]);
27678                         i++;
27679                         break;
27680                     case "boolean":
27681                         // boolean flag has optional value true, false, others
27682                         var optValue = args[i];
27683                         options[opt.name] = optValue !== "false";
27684                         // consume next argument as boolean flag value
27685                         if (optValue === "false" || optValue === "true") {
27686                             i++;
27687                         }
27688                         break;
27689                     case "string":
27690                         options[opt.name] = args[i] || "";
27691                         i++;
27692                         break;
27693                     case "list":
27694                         var result = parseListTypeOption(opt, args[i], errors);
27695                         options[opt.name] = result || [];
27696                         if (result) {
27697                             i++;
27698                         }
27699                         break;
27700                     // If not a primitive, the possible types are specified in what is effectively a map of options.
27701                     default:
27702                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
27703                         i++;
27704                         break;
27705                 }
27706             }
27707             else {
27708                 options[opt.name] = undefined;
27709                 i++;
27710             }
27711         }
27712         return i;
27713     }
27714     /*@internal*/
27715     ts.compilerOptionsDidYouMeanDiagnostics = {
27716         getOptionsNameMap: getOptionsNameMap,
27717         optionDeclarations: ts.optionDeclarations,
27718         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
27719         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
27720         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
27721     };
27722     function parseCommandLine(commandLine, readFile) {
27723         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
27724     }
27725     ts.parseCommandLine = parseCommandLine;
27726     /** @internal */
27727     function getOptionFromName(optionName, allowShort) {
27728         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
27729     }
27730     ts.getOptionFromName = getOptionFromName;
27731     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
27732         if (allowShort === void 0) { allowShort = false; }
27733         optionName = optionName.toLowerCase();
27734         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
27735         // Try to translate short option names to their full equivalents.
27736         if (allowShort) {
27737             var short = shortOptionNames.get(optionName);
27738             if (short !== undefined) {
27739                 optionName = short;
27740             }
27741         }
27742         return optionsNameMap.get(optionName);
27743     }
27744     var buildOptionsNameMapCache;
27745     function getBuildOptionsNameMap() {
27746         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
27747     }
27748     var buildOptionsDidYouMeanDiagnostics = {
27749         getOptionsNameMap: getBuildOptionsNameMap,
27750         optionDeclarations: ts.buildOpts,
27751         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
27752         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
27753         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
27754     };
27755     /*@internal*/
27756     function parseBuildCommand(args) {
27757         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
27758         var buildOptions = options;
27759         if (projects.length === 0) {
27760             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
27761             projects.push(".");
27762         }
27763         // Nonsensical combinations
27764         if (buildOptions.clean && buildOptions.force) {
27765             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
27766         }
27767         if (buildOptions.clean && buildOptions.verbose) {
27768             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
27769         }
27770         if (buildOptions.clean && buildOptions.watch) {
27771             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
27772         }
27773         if (buildOptions.watch && buildOptions.dry) {
27774             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
27775         }
27776         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
27777     }
27778     ts.parseBuildCommand = parseBuildCommand;
27779     /* @internal */
27780     function getDiagnosticText(_message) {
27781         var _args = [];
27782         for (var _i = 1; _i < arguments.length; _i++) {
27783             _args[_i - 1] = arguments[_i];
27784         }
27785         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
27786         return diagnostic.messageText;
27787     }
27788     ts.getDiagnosticText = getDiagnosticText;
27789     /**
27790      * Reads the config file, reports errors if any and exits if the config file cannot be found
27791      */
27792     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
27793         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
27794         if (!ts.isString(configFileText)) {
27795             host.onUnRecoverableConfigFileDiagnostic(configFileText);
27796             return undefined;
27797         }
27798         var result = ts.parseJsonText(configFileName, configFileText);
27799         var cwd = host.getCurrentDirectory();
27800         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
27801         result.resolvedPath = result.path;
27802         result.originalFileName = result.fileName;
27803         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
27804         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
27805     }
27806     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
27807     /**
27808      * Read tsconfig.json file
27809      * @param fileName The path to the config file
27810      */
27811     function readConfigFile(fileName, readFile) {
27812         var textOrDiagnostic = tryReadFile(fileName, readFile);
27813         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
27814     }
27815     ts.readConfigFile = readConfigFile;
27816     /**
27817      * Parse the text of the tsconfig.json file
27818      * @param fileName The path to the config file
27819      * @param jsonText The text of the config file
27820      */
27821     function parseConfigFileTextToJson(fileName, jsonText) {
27822         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
27823         return {
27824             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
27825             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
27826         };
27827     }
27828     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
27829     /**
27830      * Read tsconfig.json file
27831      * @param fileName The path to the config file
27832      */
27833     function readJsonConfigFile(fileName, readFile) {
27834         var textOrDiagnostic = tryReadFile(fileName, readFile);
27835         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
27836     }
27837     ts.readJsonConfigFile = readJsonConfigFile;
27838     /*@internal*/
27839     function tryReadFile(fileName, readFile) {
27840         var text;
27841         try {
27842             text = readFile(fileName);
27843         }
27844         catch (e) {
27845             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
27846         }
27847         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
27848     }
27849     ts.tryReadFile = tryReadFile;
27850     function commandLineOptionsToMap(options) {
27851         return ts.arrayToMap(options, getOptionName);
27852     }
27853     var typeAcquisitionDidYouMeanDiagnostics = {
27854         optionDeclarations: ts.typeAcquisitionDeclarations,
27855         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
27856         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
27857     };
27858     var watchOptionsNameMapCache;
27859     function getWatchOptionsNameMap() {
27860         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
27861     }
27862     var watchOptionsDidYouMeanDiagnostics = {
27863         getOptionsNameMap: getWatchOptionsNameMap,
27864         optionDeclarations: ts.optionsForWatch,
27865         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
27866         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
27867         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
27868     };
27869     var commandLineCompilerOptionsMapCache;
27870     function getCommandLineCompilerOptionsMap() {
27871         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
27872     }
27873     var commandLineWatchOptionsMapCache;
27874     function getCommandLineWatchOptionsMap() {
27875         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
27876     }
27877     var commandLineTypeAcquisitionMapCache;
27878     function getCommandLineTypeAcquisitionMap() {
27879         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
27880     }
27881     var _tsconfigRootOptions;
27882     function getTsconfigRootOptionsMap() {
27883         if (_tsconfigRootOptions === undefined) {
27884             _tsconfigRootOptions = {
27885                 name: undefined,
27886                 type: "object",
27887                 elementOptions: commandLineOptionsToMap([
27888                     {
27889                         name: "compilerOptions",
27890                         type: "object",
27891                         elementOptions: getCommandLineCompilerOptionsMap(),
27892                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
27893                     },
27894                     {
27895                         name: "watchOptions",
27896                         type: "object",
27897                         elementOptions: getCommandLineWatchOptionsMap(),
27898                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
27899                     },
27900                     {
27901                         name: "typingOptions",
27902                         type: "object",
27903                         elementOptions: getCommandLineTypeAcquisitionMap(),
27904                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
27905                     },
27906                     {
27907                         name: "typeAcquisition",
27908                         type: "object",
27909                         elementOptions: getCommandLineTypeAcquisitionMap(),
27910                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
27911                     },
27912                     {
27913                         name: "extends",
27914                         type: "string"
27915                     },
27916                     {
27917                         name: "references",
27918                         type: "list",
27919                         element: {
27920                             name: "references",
27921                             type: "object"
27922                         }
27923                     },
27924                     {
27925                         name: "files",
27926                         type: "list",
27927                         element: {
27928                             name: "files",
27929                             type: "string"
27930                         }
27931                     },
27932                     {
27933                         name: "include",
27934                         type: "list",
27935                         element: {
27936                             name: "include",
27937                             type: "string"
27938                         }
27939                     },
27940                     {
27941                         name: "exclude",
27942                         type: "list",
27943                         element: {
27944                             name: "exclude",
27945                             type: "string"
27946                         }
27947                     },
27948                     ts.compileOnSaveCommandLineOption
27949                 ])
27950             };
27951         }
27952         return _tsconfigRootOptions;
27953     }
27954     /**
27955      * Convert the json syntax tree into the json value
27956      */
27957     function convertToObject(sourceFile, errors) {
27958         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
27959     }
27960     ts.convertToObject = convertToObject;
27961     /**
27962      * Convert the json syntax tree into the json value and report errors
27963      * This returns the json value (apart from checking errors) only if returnValue provided is true.
27964      * Otherwise it just checks the errors and returns undefined
27965      */
27966     /*@internal*/
27967     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
27968         if (!sourceFile.statements.length) {
27969             return returnValue ? {} : undefined;
27970         }
27971         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
27972         function isRootOptionMap(knownOptions) {
27973             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
27974         }
27975         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
27976             var result = returnValue ? {} : undefined;
27977             var _loop_3 = function (element) {
27978                 if (element.kind !== 281 /* PropertyAssignment */) {
27979                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
27980                     return "continue";
27981                 }
27982                 if (element.questionToken) {
27983                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
27984                 }
27985                 if (!isDoubleQuotedString(element.name)) {
27986                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
27987                 }
27988                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
27989                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
27990                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
27991                 if (keyText && extraKeyDiagnostics && !option) {
27992                     if (knownOptions) {
27993                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
27994                     }
27995                     else {
27996                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
27997                     }
27998                 }
27999                 var value = convertPropertyValueToJson(element.initializer, option);
28000                 if (typeof keyText !== "undefined") {
28001                     if (returnValue) {
28002                         result[keyText] = value;
28003                     }
28004                     // Notify key value set, if user asked for it
28005                     if (jsonConversionNotifier &&
28006                         // Current callbacks are only on known parent option or if we are setting values in the root
28007                         (parentOption || isRootOptionMap(knownOptions))) {
28008                         var isValidOptionValue = isCompilerOptionsValue(option, value);
28009                         if (parentOption) {
28010                             if (isValidOptionValue) {
28011                                 // Notify option set in the parent if its a valid option value
28012                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
28013                             }
28014                         }
28015                         else if (isRootOptionMap(knownOptions)) {
28016                             if (isValidOptionValue) {
28017                                 // Notify about the valid root key value being set
28018                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28019                             }
28020                             else if (!option) {
28021                                 // Notify about the unknown root key value being set
28022                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28023                             }
28024                         }
28025                     }
28026                 }
28027             };
28028             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
28029                 var element = _a[_i];
28030                 _loop_3(element);
28031             }
28032             return result;
28033         }
28034         function convertArrayLiteralExpressionToJson(elements, elementOption) {
28035             if (!returnValue) {
28036                 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
28037             }
28038             // Filter out invalid values
28039             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
28040         }
28041         function convertPropertyValueToJson(valueExpression, option) {
28042             switch (valueExpression.kind) {
28043                 case 106 /* TrueKeyword */:
28044                     reportInvalidOptionValue(option && option.type !== "boolean");
28045                     return true;
28046                 case 91 /* FalseKeyword */:
28047                     reportInvalidOptionValue(option && option.type !== "boolean");
28048                     return false;
28049                 case 100 /* NullKeyword */:
28050                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
28051                     return null; // eslint-disable-line no-null/no-null
28052                 case 10 /* StringLiteral */:
28053                     if (!isDoubleQuotedString(valueExpression)) {
28054                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
28055                     }
28056                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
28057                     var text = valueExpression.text;
28058                     if (option && !ts.isString(option.type)) {
28059                         var customOption = option;
28060                         // Validate custom option type
28061                         if (!customOption.type.has(text.toLowerCase())) {
28062                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
28063                         }
28064                     }
28065                     return text;
28066                 case 8 /* NumericLiteral */:
28067                     reportInvalidOptionValue(option && option.type !== "number");
28068                     return Number(valueExpression.text);
28069                 case 207 /* PrefixUnaryExpression */:
28070                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
28071                         break; // not valid JSON syntax
28072                     }
28073                     reportInvalidOptionValue(option && option.type !== "number");
28074                     return -Number(valueExpression.operand.text);
28075                 case 193 /* ObjectLiteralExpression */:
28076                     reportInvalidOptionValue(option && option.type !== "object");
28077                     var objectLiteralExpression = valueExpression;
28078                     // Currently having element option declaration in the tsconfig with type "object"
28079                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
28080                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
28081                     // that satifies it and need it to modify options set in them (for normalizing file paths)
28082                     // vs what we set in the json
28083                     // If need arises, we can modify this interface and callbacks as needed
28084                     if (option) {
28085                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
28086                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
28087                     }
28088                     else {
28089                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
28090                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
28091                     }
28092                 case 192 /* ArrayLiteralExpression */:
28093                     reportInvalidOptionValue(option && option.type !== "list");
28094                     return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
28095             }
28096             // Not in expected format
28097             if (option) {
28098                 reportInvalidOptionValue(/*isError*/ true);
28099             }
28100             else {
28101                 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal));
28102             }
28103             return undefined;
28104             function reportInvalidOptionValue(isError) {
28105                 if (isError) {
28106                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
28107                 }
28108             }
28109         }
28110         function isDoubleQuotedString(node) {
28111             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
28112         }
28113     }
28114     ts.convertToObjectWorker = convertToObjectWorker;
28115     function getCompilerOptionValueTypeString(option) {
28116         return option.type === "list" ?
28117             "Array" :
28118             ts.isString(option.type) ? option.type : "string";
28119     }
28120     function isCompilerOptionsValue(option, value) {
28121         if (option) {
28122             if (isNullOrUndefined(value))
28123                 return true; // All options are undefinable/nullable
28124             if (option.type === "list") {
28125                 return ts.isArray(value);
28126             }
28127             var expectedType = ts.isString(option.type) ? option.type : "string";
28128             return typeof value === expectedType;
28129         }
28130         return false;
28131     }
28132     /**
28133      * Generate an uncommented, complete tsconfig for use with "--showConfig"
28134      * @param configParseResult options to be generated into tsconfig.json
28135      * @param configFileName name of the parsed config file - output paths will be generated relative to this
28136      * @param host provides current directory and case sensitivity services
28137      */
28138     /** @internal */
28139     function convertToTSConfig(configParseResult, configFileName, host) {
28140         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28141         var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
28142         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
28143         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
28144         var config = __assign(__assign({ compilerOptions: __assign(__assign({}, optionMapToObject(optionMap)), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign(__assign({}, r), { path: r.originalPath ? r.originalPath : "", originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? {
28145             include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
28146             exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
28147         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
28148         return config;
28149     }
28150     ts.convertToTSConfig = convertToTSConfig;
28151     function optionMapToObject(optionMap) {
28152         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
28153             var _a;
28154             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
28155         }, {}));
28156     }
28157     function filterSameAsDefaultInclude(specs) {
28158         if (!ts.length(specs))
28159             return undefined;
28160         if (ts.length(specs) !== 1)
28161             return specs;
28162         if (specs[0] === "**/*")
28163             return undefined;
28164         return specs;
28165     }
28166     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
28167         if (!includeSpecs)
28168             return function (_) { return true; };
28169         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
28170         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
28171         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
28172         if (includeRe) {
28173             if (excludeRe) {
28174                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
28175             }
28176             return function (path) { return !includeRe.test(path); };
28177         }
28178         if (excludeRe) {
28179             return function (path) { return excludeRe.test(path); };
28180         }
28181         return function (_) { return true; };
28182     }
28183     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
28184         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
28185             // this is of a type CommandLineOptionOfPrimitiveType
28186             return undefined;
28187         }
28188         else if (optionDefinition.type === "list") {
28189             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
28190         }
28191         else {
28192             return optionDefinition.type;
28193         }
28194     }
28195     function getNameOfCompilerOptionValue(value, customTypeMap) {
28196         // There is a typeMap associated with this command-line option so use it to map value back to its name
28197         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
28198             if (mapValue === value) {
28199                 return key;
28200             }
28201         });
28202     }
28203     function serializeCompilerOptions(options, pathOptions) {
28204         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
28205     }
28206     function serializeWatchOptions(options) {
28207         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
28208     }
28209     function serializeOptionBaseObject(options, _a, pathOptions) {
28210         var optionsNameMap = _a.optionsNameMap;
28211         var result = ts.createMap();
28212         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
28213         var _loop_4 = function (name) {
28214             if (ts.hasProperty(options, name)) {
28215                 // tsconfig only options cannot be specified via command line,
28216                 // so we can assume that only types that can appear here string | number | boolean
28217                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
28218                     return "continue";
28219                 }
28220                 var value = options[name];
28221                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
28222                 if (optionDefinition) {
28223                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
28224                     if (!customTypeMap_1) {
28225                         // There is no map associated with this compiler option then use the value as-is
28226                         // This is the case if the value is expect to be string, number, boolean or list of string
28227                         if (pathOptions && optionDefinition.isFilePath) {
28228                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
28229                         }
28230                         else {
28231                             result.set(name, value);
28232                         }
28233                     }
28234                     else {
28235                         if (optionDefinition.type === "list") {
28236                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
28237                         }
28238                         else {
28239                             // There is a typeMap associated with this command-line option so use it to map value back to its name
28240                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
28241                         }
28242                     }
28243                 }
28244             }
28245         };
28246         for (var name in options) {
28247             _loop_4(name);
28248         }
28249         return result;
28250     }
28251     /**
28252      * Generate tsconfig configuration when running command line "--init"
28253      * @param options commandlineOptions to be generated into tsconfig.json
28254      * @param fileNames array of filenames to be generated into tsconfig.json
28255      */
28256     /* @internal */
28257     function generateTSConfig(options, fileNames, newLine) {
28258         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
28259         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
28260         return writeConfigurations();
28261         function getDefaultValueForOption(option) {
28262             switch (option.type) {
28263                 case "number":
28264                     return 1;
28265                 case "boolean":
28266                     return true;
28267                 case "string":
28268                     return option.isFilePath ? "./" : "";
28269                 case "list":
28270                     return [];
28271                 case "object":
28272                     return {};
28273                 default:
28274                     var iterResult = option.type.keys().next();
28275                     if (!iterResult.done)
28276                         return iterResult.value;
28277                     return ts.Debug.fail("Expected 'option.type' to have entries.");
28278             }
28279         }
28280         function makePadding(paddingLength) {
28281             return Array(paddingLength + 1).join(" ");
28282         }
28283         function isAllowedOption(_a) {
28284             var category = _a.category, name = _a.name;
28285             // Skip options which do not have a category or have category `Command_line_Options`
28286             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
28287             return category !== undefined
28288                 && category !== ts.Diagnostics.Command_line_Options
28289                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
28290         }
28291         function writeConfigurations() {
28292             // Filter applicable options to place in the file
28293             var categorizedOptions = ts.createMultiMap();
28294             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
28295                 var option = optionDeclarations_1[_i];
28296                 var category = option.category;
28297                 if (isAllowedOption(option)) {
28298                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
28299                 }
28300             }
28301             // Serialize all options and their descriptions
28302             var marginLength = 0;
28303             var seenKnownKeys = 0;
28304             var entries = [];
28305             categorizedOptions.forEach(function (options, category) {
28306                 if (entries.length !== 0) {
28307                     entries.push({ value: "" });
28308                 }
28309                 entries.push({ value: "/* " + category + " */" });
28310                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
28311                     var option = options_1[_i];
28312                     var optionName = void 0;
28313                     if (compilerOptionsMap.has(option.name)) {
28314                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
28315                     }
28316                     else {
28317                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
28318                     }
28319                     entries.push({
28320                         value: optionName,
28321                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
28322                     });
28323                     marginLength = Math.max(optionName.length, marginLength);
28324                 }
28325             });
28326             // Write the output
28327             var tab = makePadding(2);
28328             var result = [];
28329             result.push("{");
28330             result.push(tab + "\"compilerOptions\": {");
28331             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
28332             result.push("");
28333             // Print out each row, aligning all the descriptions on the same column.
28334             for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) {
28335                 var entry = entries_3[_a];
28336                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
28337                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
28338             }
28339             if (fileNames.length) {
28340                 result.push(tab + "},");
28341                 result.push(tab + "\"files\": [");
28342                 for (var i = 0; i < fileNames.length; i++) {
28343                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
28344                 }
28345                 result.push(tab + "]");
28346             }
28347             else {
28348                 result.push(tab + "}");
28349             }
28350             result.push("}");
28351             return result.join(newLine) + newLine;
28352         }
28353     }
28354     ts.generateTSConfig = generateTSConfig;
28355     /* @internal */
28356     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
28357         var result = {};
28358         var optionsNameMap = getOptionsNameMap().optionsNameMap;
28359         for (var name in options) {
28360             if (ts.hasProperty(options, name)) {
28361                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
28362             }
28363         }
28364         if (result.configFilePath) {
28365             result.configFilePath = toAbsolutePath(result.configFilePath);
28366         }
28367         return result;
28368     }
28369     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
28370     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
28371         if (option && !isNullOrUndefined(value)) {
28372             if (option.type === "list") {
28373                 var values = value;
28374                 if (option.element.isFilePath && values.length) {
28375                     return values.map(toAbsolutePath);
28376                 }
28377             }
28378             else if (option.isFilePath) {
28379                 return toAbsolutePath(value);
28380             }
28381         }
28382         return value;
28383     }
28384     /**
28385      * Parse the contents of a config file (tsconfig.json).
28386      * @param json The contents of the config file to parse
28387      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28388      * @param basePath A root directory to resolve relative path entries in the config
28389      *    file to. e.g. outDir
28390      */
28391     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28392         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28393     }
28394     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
28395     /**
28396      * Parse the contents of a config file (tsconfig.json).
28397      * @param jsonNode The contents of the config file to parse
28398      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28399      * @param basePath A root directory to resolve relative path entries in the config
28400      *    file to. e.g. outDir
28401      */
28402     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28403         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28404     }
28405     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
28406     /*@internal*/
28407     function setConfigFileInOptions(options, configFile) {
28408         if (configFile) {
28409             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
28410         }
28411     }
28412     ts.setConfigFileInOptions = setConfigFileInOptions;
28413     function isNullOrUndefined(x) {
28414         return x === undefined || x === null; // eslint-disable-line no-null/no-null
28415     }
28416     function directoryOfCombinedPath(fileName, basePath) {
28417         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
28418         // until consistent casing errors are reported
28419         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
28420     }
28421     /**
28422      * Parse the contents of a config file from json or json source file (tsconfig.json).
28423      * @param json The contents of the config file to parse
28424      * @param sourceFile sourceFile corresponding to the Json
28425      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28426      * @param basePath A root directory to resolve relative path entries in the config
28427      *    file to. e.g. outDir
28428      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
28429      */
28430     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
28431         if (existingOptions === void 0) { existingOptions = {}; }
28432         if (resolutionStack === void 0) { resolutionStack = []; }
28433         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28434         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
28435         var errors = [];
28436         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
28437         var raw = parsedConfig.raw;
28438         var options = ts.extend(existingOptions, parsedConfig.options || {});
28439         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
28440             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
28441             parsedConfig.watchOptions || existingWatchOptions;
28442         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
28443         setConfigFileInOptions(options, sourceFile);
28444         var projectReferences;
28445         var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
28446         return {
28447             options: options,
28448             watchOptions: watchOptions,
28449             fileNames: fileNames,
28450             projectReferences: projectReferences,
28451             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
28452             raw: raw,
28453             errors: errors,
28454             wildcardDirectories: wildcardDirectories,
28455             compileOnSave: !!raw.compileOnSave,
28456             configFileSpecs: spec
28457         };
28458         function getFileNames() {
28459             var filesSpecs;
28460             if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
28461                 if (ts.isArray(raw.files)) {
28462                     filesSpecs = raw.files;
28463                     var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
28464                     var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
28465                     var hasExtends = ts.hasProperty(raw, "extends");
28466                     if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
28467                         if (sourceFile) {
28468                             var fileName = configFileName || "tsconfig.json";
28469                             var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
28470                             var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
28471                             var error = nodeValue
28472                                 ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
28473                                 : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
28474                             errors.push(error);
28475                         }
28476                         else {
28477                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
28478                         }
28479                     }
28480                 }
28481                 else {
28482                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
28483                 }
28484             }
28485             var includeSpecs;
28486             if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
28487                 if (ts.isArray(raw.include)) {
28488                     includeSpecs = raw.include;
28489                 }
28490                 else {
28491                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
28492                 }
28493             }
28494             var excludeSpecs;
28495             if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
28496                 if (ts.isArray(raw.exclude)) {
28497                     excludeSpecs = raw.exclude;
28498                 }
28499                 else {
28500                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
28501                 }
28502             }
28503             else if (raw.compilerOptions) {
28504                 var outDir = raw.compilerOptions.outDir;
28505                 var declarationDir = raw.compilerOptions.declarationDir;
28506                 if (outDir || declarationDir) {
28507                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
28508                 }
28509             }
28510             if (filesSpecs === undefined && includeSpecs === undefined) {
28511                 includeSpecs = ["**/*"];
28512             }
28513             var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
28514             if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
28515                 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
28516             }
28517             if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
28518                 if (ts.isArray(raw.references)) {
28519                     for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
28520                         var ref = _a[_i];
28521                         if (typeof ref.path !== "string") {
28522                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
28523                         }
28524                         else {
28525                             (projectReferences || (projectReferences = [])).push({
28526                                 path: ts.getNormalizedAbsolutePath(ref.path, basePath),
28527                                 originalPath: ref.path,
28528                                 prepend: ref.prepend,
28529                                 circular: ref.circular
28530                             });
28531                         }
28532                     }
28533                 }
28534                 else {
28535                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
28536                 }
28537             }
28538             return result;
28539         }
28540         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
28541             if (!sourceFile) {
28542                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
28543             }
28544         }
28545     }
28546     function isErrorNoInputFiles(error) {
28547         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
28548     }
28549     function getErrorForNoInputFiles(_a, configFileName) {
28550         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
28551         return ts.createCompilerDiagnostic(ts.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 || []));
28552     }
28553     function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
28554         return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
28555     }
28556     /*@internal*/
28557     function canJsonReportNoInutFiles(raw) {
28558         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
28559     }
28560     ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
28561     /*@internal*/
28562     function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
28563         var existingErrors = configParseDiagnostics.length;
28564         if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
28565             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
28566         }
28567         else {
28568             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
28569         }
28570         return existingErrors !== configParseDiagnostics.length;
28571     }
28572     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
28573     function isSuccessfulParsedTsconfig(value) {
28574         return !!value.options;
28575     }
28576     /**
28577      * This *just* extracts options/include/exclude/files out of a config file.
28578      * It does *not* resolve the included files.
28579      */
28580     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
28581         basePath = ts.normalizeSlashes(basePath);
28582         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
28583         if (resolutionStack.indexOf(resolvedPath) >= 0) {
28584             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
28585             return { raw: json || convertToObject(sourceFile, errors) };
28586         }
28587         var ownConfig = json ?
28588             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
28589             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
28590         if (ownConfig.extendedConfigPath) {
28591             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
28592             resolutionStack = resolutionStack.concat([resolvedPath]);
28593             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
28594             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
28595                 var baseRaw_1 = extendedConfig.raw;
28596                 var raw_1 = ownConfig.raw;
28597                 var setPropertyInRawIfNotUndefined = function (propertyName) {
28598                     var value = raw_1[propertyName] || baseRaw_1[propertyName];
28599                     if (value) {
28600                         raw_1[propertyName] = value;
28601                     }
28602                 };
28603                 setPropertyInRawIfNotUndefined("include");
28604                 setPropertyInRawIfNotUndefined("exclude");
28605                 setPropertyInRawIfNotUndefined("files");
28606                 if (raw_1.compileOnSave === undefined) {
28607                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
28608                 }
28609                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
28610                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
28611                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
28612                     ownConfig.watchOptions || extendedConfig.watchOptions;
28613                 // TODO extend type typeAcquisition
28614             }
28615         }
28616         return ownConfig;
28617     }
28618     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
28619         if (ts.hasProperty(json, "excludes")) {
28620             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28621         }
28622         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
28623         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
28624         // It should be removed in future releases - use typeAcquisition instead.
28625         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
28626         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
28627         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
28628         var extendedConfigPath;
28629         if (json.extends) {
28630             if (!ts.isString(json.extends)) {
28631                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
28632             }
28633             else {
28634                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28635                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
28636             }
28637         }
28638         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28639     }
28640     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
28641         var options = getDefaultCompilerOptions(configFileName);
28642         var typeAcquisition, typingOptionstypeAcquisition;
28643         var watchOptions;
28644         var extendedConfigPath;
28645         var optionsIterator = {
28646             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
28647                 var currentOption;
28648                 switch (parentOption) {
28649                     case "compilerOptions":
28650                         currentOption = options;
28651                         break;
28652                     case "watchOptions":
28653                         currentOption = (watchOptions || (watchOptions = {}));
28654                         break;
28655                     case "typeAcquisition":
28656                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
28657                         break;
28658                     case "typingOptions":
28659                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
28660                         break;
28661                     default:
28662                         ts.Debug.fail("Unknown option");
28663                 }
28664                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
28665             },
28666             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
28667                 switch (key) {
28668                     case "extends":
28669                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28670                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
28671                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
28672                         });
28673                         return;
28674                 }
28675             },
28676             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
28677                 if (key === "excludes") {
28678                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28679                 }
28680             }
28681         };
28682         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
28683         if (!typeAcquisition) {
28684             if (typingOptionstypeAcquisition) {
28685                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
28686                     {
28687                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
28688                         include: typingOptionstypeAcquisition.include,
28689                         exclude: typingOptionstypeAcquisition.exclude
28690                     } :
28691                     typingOptionstypeAcquisition;
28692             }
28693             else {
28694                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
28695             }
28696         }
28697         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28698     }
28699     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
28700         extendedConfig = ts.normalizeSlashes(extendedConfig);
28701         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
28702             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
28703             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
28704                 extendedConfigPath = extendedConfigPath + ".json";
28705                 if (!host.fileExists(extendedConfigPath)) {
28706                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28707                     return undefined;
28708                 }
28709             }
28710             return extendedConfigPath;
28711         }
28712         // If the path isn't a rooted or relative path, resolve like a module
28713         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
28714         if (resolved.resolvedModule) {
28715             return resolved.resolvedModule.resolvedFileName;
28716         }
28717         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28718         return undefined;
28719     }
28720     function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
28721         var _a;
28722         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
28723         var value;
28724         var extendedResult;
28725         var extendedConfig;
28726         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
28727             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
28728         }
28729         else {
28730             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
28731             if (!extendedResult.parseDiagnostics.length) {
28732                 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
28733                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
28734                 if (isSuccessfulParsedTsconfig(extendedConfig)) {
28735                     // Update the paths to reflect base path
28736                     var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
28737                     var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
28738                     var mapPropertiesInRawIfNotUndefined = function (propertyName) {
28739                         if (raw_2[propertyName]) {
28740                             raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
28741                         }
28742                     };
28743                     var raw_2 = extendedConfig.raw;
28744                     mapPropertiesInRawIfNotUndefined("include");
28745                     mapPropertiesInRawIfNotUndefined("exclude");
28746                     mapPropertiesInRawIfNotUndefined("files");
28747                 }
28748             }
28749             if (extendedConfigCache) {
28750                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
28751             }
28752         }
28753         if (sourceFile) {
28754             sourceFile.extendedSourceFiles = [extendedResult.fileName];
28755             if (extendedResult.extendedSourceFiles) {
28756                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
28757             }
28758         }
28759         if (extendedResult.parseDiagnostics.length) {
28760             errors.push.apply(errors, extendedResult.parseDiagnostics);
28761             return undefined;
28762         }
28763         return extendedConfig;
28764     }
28765     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
28766         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
28767             return false;
28768         }
28769         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
28770         return typeof result === "boolean" && result;
28771     }
28772     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
28773         var errors = [];
28774         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28775         return { options: options, errors: errors };
28776     }
28777     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
28778     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
28779         var errors = [];
28780         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28781         return { options: options, errors: errors };
28782     }
28783     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
28784     function getDefaultCompilerOptions(configFileName) {
28785         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
28786             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
28787             : {};
28788         return options;
28789     }
28790     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28791         var options = getDefaultCompilerOptions(configFileName);
28792         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
28793         if (configFileName) {
28794             options.configFilePath = ts.normalizeSlashes(configFileName);
28795         }
28796         return options;
28797     }
28798     function getDefaultTypeAcquisition(configFileName) {
28799         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
28800     }
28801     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28802         var options = getDefaultTypeAcquisition(configFileName);
28803         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
28804         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
28805         return options;
28806     }
28807     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
28808         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
28809     }
28810     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
28811         if (!jsonOptions) {
28812             return;
28813         }
28814         for (var id in jsonOptions) {
28815             var opt = optionsNameMap.get(id);
28816             if (opt) {
28817                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
28818             }
28819             else {
28820                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
28821             }
28822         }
28823         return defaultOptions;
28824     }
28825     function convertJsonOption(opt, value, basePath, errors) {
28826         if (isCompilerOptionsValue(opt, value)) {
28827             var optType = opt.type;
28828             if (optType === "list" && ts.isArray(value)) {
28829                 return convertJsonOptionOfListType(opt, value, basePath, errors);
28830             }
28831             else if (!ts.isString(optType)) {
28832                 return convertJsonOptionOfCustomType(opt, value, errors);
28833             }
28834             return normalizeNonListOptionValue(opt, basePath, value);
28835         }
28836         else {
28837             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
28838         }
28839     }
28840     function normalizeOptionValue(option, basePath, value) {
28841         if (isNullOrUndefined(value))
28842             return undefined;
28843         if (option.type === "list") {
28844             var listOption_1 = option;
28845             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
28846                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
28847             }
28848             return value;
28849         }
28850         else if (!ts.isString(option.type)) {
28851             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
28852         }
28853         return normalizeNonListOptionValue(option, basePath, value);
28854     }
28855     function normalizeNonListOptionValue(option, basePath, value) {
28856         if (option.isFilePath) {
28857             value = ts.getNormalizedAbsolutePath(value, basePath);
28858             if (value === "") {
28859                 value = ".";
28860             }
28861         }
28862         return value;
28863     }
28864     function convertJsonOptionOfCustomType(opt, value, errors) {
28865         if (isNullOrUndefined(value))
28866             return undefined;
28867         var key = value.toLowerCase();
28868         var val = opt.type.get(key);
28869         if (val !== undefined) {
28870             return val;
28871         }
28872         else {
28873             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
28874         }
28875     }
28876     function convertJsonOptionOfListType(option, values, basePath, errors) {
28877         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
28878     }
28879     function trimString(s) {
28880         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
28881     }
28882     /**
28883      * Tests for a path that ends in a recursive directory wildcard.
28884      * Matches **, \**, **\, and \**\, but not a**b.
28885      *
28886      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28887      *
28888      * Breakdown:
28889      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28890      *  \*\*        # matches the recursive directory wildcard "**".
28891      *  \/?$        # matches an optional trailing directory separator at the end of the string.
28892      */
28893     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
28894     /**
28895      * Tests for a path where .. appears after a recursive directory wildcard.
28896      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
28897      *
28898      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28899      *
28900      * Breakdown:
28901      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28902      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
28903      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
28904      *  \.\.        # matches a parent directory path component ".."
28905      *  ($|\/)      # matches either the end of the string or a directory separator.
28906      */
28907     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
28908     /**
28909      * Tests for a path containing a wildcard character in a directory component of the path.
28910      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
28911      *
28912      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28913      *
28914      * Breakdown:
28915      *  \/          # matches a directory separator.
28916      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
28917      *  [*?]        # matches either a wildcard character (* or ?)
28918      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
28919      *  \/          # matches a directory separator.
28920      */
28921     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
28922     /**
28923      * Matches the portion of a wildcard path that does not contain wildcards.
28924      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
28925      *
28926      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28927      *
28928      * Breakdown:
28929      *  ^                   # matches the beginning of the string
28930      *  [^*?]*              # matches any number of non-wildcard characters
28931      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
28932      *                      # a path component that contains at least one wildcard character (* or ?).
28933      */
28934     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
28935     /**
28936      * Expands an array of file specifications.
28937      *
28938      * @param filesSpecs The literal file names to include.
28939      * @param includeSpecs The wildcard file specifications to include.
28940      * @param excludeSpecs The wildcard file specifications to exclude.
28941      * @param basePath The base path for any relative file specifications.
28942      * @param options Compiler options.
28943      * @param host The host used to resolve files and directories.
28944      * @param errors An array for diagnostic reporting.
28945      */
28946     function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
28947         basePath = ts.normalizePath(basePath);
28948         var validatedIncludeSpecs, validatedExcludeSpecs;
28949         // The exclude spec list is converted into a regular expression, which allows us to quickly
28950         // test whether a file or directory should be excluded before recursively traversing the
28951         // file system.
28952         if (includeSpecs) {
28953             validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
28954         }
28955         if (excludeSpecs) {
28956             validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
28957         }
28958         // Wildcard directories (provided as part of a wildcard path) are stored in a
28959         // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
28960         // or a recursive directory. This information is used by filesystem watchers to monitor for
28961         // new entries in these paths.
28962         var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
28963         var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
28964         return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
28965     }
28966     /**
28967      * Gets the file names from the provided config file specs that contain, files, include, exclude and
28968      * other properties needed to resolve the file names
28969      * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
28970      * @param basePath The base path for any relative file specifications.
28971      * @param options Compiler options.
28972      * @param host The host used to resolve files and directories.
28973      * @param extraFileExtensions optionaly file extra file extension information from host
28974      */
28975     /* @internal */
28976     function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
28977         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28978         basePath = ts.normalizePath(basePath);
28979         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28980         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
28981         // file map with a possibly case insensitive key. We use this map later when when including
28982         // wildcard paths.
28983         var literalFileMap = ts.createMap();
28984         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
28985         // file map with a possibly case insensitive key. We use this map to store paths matched
28986         // via wildcard, and to handle extension priority.
28987         var wildcardFileMap = ts.createMap();
28988         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
28989         // file map with a possibly case insensitive key. We use this map to store paths matched
28990         // via wildcard of *.json kind
28991         var wildCardJsonFileMap = ts.createMap();
28992         var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
28993         // Rather than requery this for each file and filespec, we query the supported extensions
28994         // once and store it on the expansion context.
28995         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
28996         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
28997         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
28998         // remove a literal file.
28999         if (filesSpecs) {
29000             for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
29001                 var fileName = filesSpecs_1[_i];
29002                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
29003                 literalFileMap.set(keyMapper(file), file);
29004             }
29005         }
29006         var jsonOnlyIncludeRegexes;
29007         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
29008             var _loop_5 = function (file) {
29009                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
29010                     // Valid only if *.json specified
29011                     if (!jsonOnlyIncludeRegexes) {
29012                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
29013                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
29014                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
29015                     }
29016                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
29017                     if (includeIndex !== -1) {
29018                         var key_1 = keyMapper(file);
29019                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
29020                             wildCardJsonFileMap.set(key_1, file);
29021                         }
29022                     }
29023                     return "continue";
29024                 }
29025                 // If we have already included a literal or wildcard path with a
29026                 // higher priority extension, we should skip this file.
29027                 //
29028                 // This handles cases where we may encounter both <file>.ts and
29029                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
29030                 // directory when they are compilation outputs.
29031                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
29032                     return "continue";
29033                 }
29034                 // We may have included a wildcard path with a lower priority
29035                 // extension due to the user-defined order of entries in the
29036                 // "include" array. If there is a lower priority extension in the
29037                 // same directory, we should remove it.
29038                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
29039                 var key = keyMapper(file);
29040                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
29041                     wildcardFileMap.set(key, file);
29042                 }
29043             };
29044             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
29045                 var file = _b[_a];
29046                 _loop_5(file);
29047             }
29048         }
29049         var literalFiles = ts.arrayFrom(literalFileMap.values());
29050         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
29051         return {
29052             fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
29053             wildcardDirectories: wildcardDirectories,
29054             spec: spec
29055         };
29056     }
29057     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
29058     function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
29059         return specs.filter(function (spec) {
29060             var diag = specToDiagnostic(spec, allowTrailingRecursion);
29061             if (diag !== undefined) {
29062                 errors.push(createDiagnostic(diag, spec));
29063             }
29064             return diag === undefined;
29065         });
29066         function createDiagnostic(message, spec) {
29067             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
29068             return element ?
29069                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
29070                 ts.createCompilerDiagnostic(message, spec);
29071         }
29072     }
29073     function specToDiagnostic(spec, allowTrailingRecursion) {
29074         if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
29075             return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29076         }
29077         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
29078             return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29079         }
29080     }
29081     /**
29082      * Gets directories in a set of include patterns that should be watched for changes.
29083      */
29084     function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
29085         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
29086         // of the pattern:
29087         //
29088         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
29089         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
29090         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
29091         //
29092         // We watch a directory without recursion if it contains a wildcard in the file segment of
29093         // the pattern:
29094         //
29095         //  /a/b/*      - Watch /a/b directly to catch any new file
29096         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
29097         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
29098         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
29099         var wildcardDirectories = {};
29100         if (include !== undefined) {
29101             var recursiveKeys = [];
29102             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
29103                 var file = include_1[_i];
29104                 var spec = ts.normalizePath(ts.combinePaths(path, file));
29105                 if (excludeRegex && excludeRegex.test(spec)) {
29106                     continue;
29107                 }
29108                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
29109                 if (match) {
29110                     var key = match.key, flags = match.flags;
29111                     var existingFlags = wildcardDirectories[key];
29112                     if (existingFlags === undefined || existingFlags < flags) {
29113                         wildcardDirectories[key] = flags;
29114                         if (flags === 1 /* Recursive */) {
29115                             recursiveKeys.push(key);
29116                         }
29117                     }
29118                 }
29119             }
29120             // Remove any subpaths under an existing recursively watched directory.
29121             for (var key in wildcardDirectories) {
29122                 if (ts.hasProperty(wildcardDirectories, key)) {
29123                     for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
29124                         var recursiveKey = recursiveKeys_1[_a];
29125                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
29126                             delete wildcardDirectories[key];
29127                         }
29128                     }
29129                 }
29130             }
29131         }
29132         return wildcardDirectories;
29133     }
29134     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
29135         var match = wildcardDirectoryPattern.exec(spec);
29136         if (match) {
29137             return {
29138                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
29139                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
29140             };
29141         }
29142         if (ts.isImplicitGlob(spec)) {
29143             return { key: spec, flags: 1 /* Recursive */ };
29144         }
29145         return undefined;
29146     }
29147     /**
29148      * Determines whether a literal or wildcard file has already been included that has a higher
29149      * extension priority.
29150      *
29151      * @param file The path to the file.
29152      * @param extensionPriority The priority of the extension.
29153      * @param context The expansion context.
29154      */
29155     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
29156         var extensionPriority = ts.getExtensionPriority(file, extensions);
29157         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
29158         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
29159             var higherPriorityExtension = extensions[i];
29160             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
29161             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
29162                 return true;
29163             }
29164         }
29165         return false;
29166     }
29167     /**
29168      * Removes files included via wildcard expansion with a lower extension priority that have
29169      * already been included.
29170      *
29171      * @param file The path to the file.
29172      * @param extensionPriority The priority of the extension.
29173      * @param context The expansion context.
29174      */
29175     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
29176         var extensionPriority = ts.getExtensionPriority(file, extensions);
29177         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
29178         for (var i = nextExtensionPriority; i < extensions.length; i++) {
29179             var lowerPriorityExtension = extensions[i];
29180             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
29181             wildcardFiles.delete(lowerPriorityPath);
29182         }
29183     }
29184     /**
29185      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
29186      * Also converts enum values back to strings.
29187      */
29188     /* @internal */
29189     function convertCompilerOptionsForTelemetry(opts) {
29190         var out = {};
29191         for (var key in opts) {
29192             if (opts.hasOwnProperty(key)) {
29193                 var type = getOptionFromName(key);
29194                 if (type !== undefined) { // Ignore unknown options
29195                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
29196                 }
29197             }
29198         }
29199         return out;
29200     }
29201     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
29202     function getOptionValueWithEmptyStrings(value, option) {
29203         switch (option.type) {
29204             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
29205                 return "";
29206             case "string": // Could be any arbitrary string -- use empty string instead.
29207                 return "";
29208             case "number": // Allow numbers, but be sure to check it's actually a number.
29209                 return typeof value === "number" ? value : "";
29210             case "boolean":
29211                 return typeof value === "boolean" ? value : "";
29212             case "list":
29213                 var elementType_1 = option.element;
29214                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
29215             default:
29216                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
29217                     if (optionEnumValue === value) {
29218                         return optionStringValue;
29219                     }
29220                 }); // TODO: GH#18217
29221         }
29222     }
29223 })(ts || (ts = {}));
29224 var ts;
29225 (function (ts) {
29226     function trace(host) {
29227         host.trace(ts.formatMessage.apply(undefined, arguments));
29228     }
29229     ts.trace = trace;
29230     /* @internal */
29231     function isTraceEnabled(compilerOptions, host) {
29232         return !!compilerOptions.traceResolution && host.trace !== undefined;
29233     }
29234     ts.isTraceEnabled = isTraceEnabled;
29235     function withPackageId(packageInfo, r) {
29236         var packageId;
29237         if (r && packageInfo) {
29238             var packageJsonContent = packageInfo.packageJsonContent;
29239             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
29240                 packageId = {
29241                     name: packageJsonContent.name,
29242                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
29243                     version: packageJsonContent.version
29244                 };
29245             }
29246         }
29247         return r && { path: r.path, extension: r.ext, packageId: packageId };
29248     }
29249     function noPackageId(r) {
29250         return withPackageId(/*packageInfo*/ undefined, r);
29251     }
29252     function removeIgnoredPackageId(r) {
29253         if (r) {
29254             ts.Debug.assert(r.packageId === undefined);
29255             return { path: r.path, ext: r.extension };
29256         }
29257     }
29258     /**
29259      * Kinds of file that we are currently looking for.
29260      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
29261      */
29262     var Extensions;
29263     (function (Extensions) {
29264         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
29265         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
29266         Extensions[Extensions["Json"] = 2] = "Json";
29267         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
29268         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
29269     })(Extensions || (Extensions = {}));
29270     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
29271     function resolvedTypeScriptOnly(resolved) {
29272         if (!resolved) {
29273             return undefined;
29274         }
29275         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
29276         return { fileName: resolved.path, packageId: resolved.packageId };
29277     }
29278     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
29279         var _a;
29280         if (resultFromCache) {
29281             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
29282             return resultFromCache;
29283         }
29284         return {
29285             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
29286             failedLookupLocations: failedLookupLocations
29287         };
29288     }
29289     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
29290         if (!ts.hasProperty(jsonContent, fieldName)) {
29291             if (state.traceEnabled) {
29292                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
29293             }
29294             return;
29295         }
29296         var value = jsonContent[fieldName];
29297         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
29298             if (state.traceEnabled) {
29299                 // eslint-disable-next-line no-null/no-null
29300                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
29301             }
29302             return;
29303         }
29304         return value;
29305     }
29306     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
29307         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
29308         if (fileName === undefined) {
29309             return;
29310         }
29311         if (!fileName) {
29312             if (state.traceEnabled) {
29313                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
29314             }
29315             return;
29316         }
29317         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
29318         if (state.traceEnabled) {
29319             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
29320         }
29321         return path;
29322     }
29323     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
29324         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
29325             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
29326     }
29327     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
29328         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
29329     }
29330     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
29331         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
29332     }
29333     function readPackageJsonTypesVersionsField(jsonContent, state) {
29334         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
29335         if (typesVersions === undefined)
29336             return;
29337         if (state.traceEnabled) {
29338             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
29339         }
29340         return typesVersions;
29341     }
29342     function readPackageJsonTypesVersionPaths(jsonContent, state) {
29343         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
29344         if (typesVersions === undefined)
29345             return;
29346         if (state.traceEnabled) {
29347             for (var key in typesVersions) {
29348                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
29349                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
29350                 }
29351             }
29352         }
29353         var result = getPackageJsonTypesVersionsPaths(typesVersions);
29354         if (!result) {
29355             if (state.traceEnabled) {
29356                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
29357             }
29358             return;
29359         }
29360         var bestVersionKey = result.version, bestVersionPaths = result.paths;
29361         if (typeof bestVersionPaths !== "object") {
29362             if (state.traceEnabled) {
29363                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
29364             }
29365             return;
29366         }
29367         return result;
29368     }
29369     var typeScriptVersion;
29370     /* @internal */
29371     function getPackageJsonTypesVersionsPaths(typesVersions) {
29372         if (!typeScriptVersion)
29373             typeScriptVersion = new ts.Version(ts.version);
29374         for (var key in typesVersions) {
29375             if (!ts.hasProperty(typesVersions, key))
29376                 continue;
29377             var keyRange = ts.VersionRange.tryParse(key);
29378             if (keyRange === undefined) {
29379                 continue;
29380             }
29381             // return the first entry whose range matches the current compiler version.
29382             if (keyRange.test(typeScriptVersion)) {
29383                 return { version: key, paths: typesVersions[key] };
29384             }
29385         }
29386     }
29387     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
29388     function getEffectiveTypeRoots(options, host) {
29389         if (options.typeRoots) {
29390             return options.typeRoots;
29391         }
29392         var currentDirectory;
29393         if (options.configFilePath) {
29394             currentDirectory = ts.getDirectoryPath(options.configFilePath);
29395         }
29396         else if (host.getCurrentDirectory) {
29397             currentDirectory = host.getCurrentDirectory();
29398         }
29399         if (currentDirectory !== undefined) {
29400             return getDefaultTypeRoots(currentDirectory, host);
29401         }
29402     }
29403     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
29404     /**
29405      * Returns the path to every node_modules/@types directory from some ancestor directory.
29406      * Returns undefined if there are none.
29407      */
29408     function getDefaultTypeRoots(currentDirectory, host) {
29409         if (!host.directoryExists) {
29410             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
29411             // And if it doesn't exist, tough.
29412         }
29413         var typeRoots;
29414         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
29415             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
29416             if (host.directoryExists(atTypes)) {
29417                 (typeRoots || (typeRoots = [])).push(atTypes);
29418             }
29419             return undefined;
29420         });
29421         return typeRoots;
29422     }
29423     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
29424     /**
29425      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
29426      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
29427      * is assumed to be the same as root directory of the project.
29428      */
29429     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
29430         var traceEnabled = isTraceEnabled(options, host);
29431         if (redirectedReference) {
29432             options = redirectedReference.commandLine.options;
29433         }
29434         var failedLookupLocations = [];
29435         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29436         var typeRoots = getEffectiveTypeRoots(options, host);
29437         if (traceEnabled) {
29438             if (containingFile === undefined) {
29439                 if (typeRoots === undefined) {
29440                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
29441                 }
29442                 else {
29443                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
29444                 }
29445             }
29446             else {
29447                 if (typeRoots === undefined) {
29448                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
29449                 }
29450                 else {
29451                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
29452                 }
29453             }
29454             if (redirectedReference) {
29455                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29456             }
29457         }
29458         var resolved = primaryLookup();
29459         var primary = true;
29460         if (!resolved) {
29461             resolved = secondaryLookup();
29462             primary = false;
29463         }
29464         var resolvedTypeReferenceDirective;
29465         if (resolved) {
29466             var fileName = resolved.fileName, packageId = resolved.packageId;
29467             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
29468             if (traceEnabled) {
29469                 if (packageId) {
29470                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary);
29471                 }
29472                 else {
29473                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
29474                 }
29475             }
29476             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
29477         }
29478         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
29479         function primaryLookup() {
29480             // Check primary library paths
29481             if (typeRoots && typeRoots.length) {
29482                 if (traceEnabled) {
29483                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
29484                 }
29485                 return ts.firstDefined(typeRoots, function (typeRoot) {
29486                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
29487                     var candidateDirectory = ts.getDirectoryPath(candidate);
29488                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
29489                     if (!directoryExists && traceEnabled) {
29490                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
29491                     }
29492                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
29493                 });
29494             }
29495             else {
29496                 if (traceEnabled) {
29497                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
29498                 }
29499             }
29500         }
29501         function secondaryLookup() {
29502             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
29503             if (initialLocationForSecondaryLookup !== undefined) {
29504                 // check secondary locations
29505                 if (traceEnabled) {
29506                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
29507                 }
29508                 var result = void 0;
29509                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
29510                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
29511                     result = searchResult && searchResult.value;
29512                 }
29513                 else {
29514                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
29515                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
29516                 }
29517                 var resolvedFile = resolvedTypeScriptOnly(result);
29518                 if (!resolvedFile && traceEnabled) {
29519                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
29520                 }
29521                 return resolvedFile;
29522             }
29523             else {
29524                 if (traceEnabled) {
29525                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
29526                 }
29527             }
29528         }
29529     }
29530     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
29531     /**
29532      * Given a set of options, returns the set of type directive names
29533      *   that should be included for this program automatically.
29534      * This list could either come from the config file,
29535      *   or from enumerating the types root + initial secondary types lookup location.
29536      * More type directives might appear in the program later as a result of loading actual source files;
29537      *   this list is only the set of defaults that are implicitly included.
29538      */
29539     function getAutomaticTypeDirectiveNames(options, host) {
29540         // Use explicit type list from tsconfig.json
29541         if (options.types) {
29542             return options.types;
29543         }
29544         // Walk the primary type lookup locations
29545         var result = [];
29546         if (host.directoryExists && host.getDirectories) {
29547             var typeRoots = getEffectiveTypeRoots(options, host);
29548             if (typeRoots) {
29549                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
29550                     var root = typeRoots_1[_i];
29551                     if (host.directoryExists(root)) {
29552                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
29553                             var typeDirectivePath = _b[_a];
29554                             var normalized = ts.normalizePath(typeDirectivePath);
29555                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
29556                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
29557                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
29558                             // eslint-disable-next-line no-null/no-null
29559                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
29560                             if (!isNotNeededPackage) {
29561                                 var baseFileName = ts.getBaseFileName(normalized);
29562                                 // At this stage, skip results with leading dot.
29563                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
29564                                     // Return just the type directive names
29565                                     result.push(baseFileName);
29566                                 }
29567                             }
29568                         }
29569                     }
29570                 }
29571             }
29572         }
29573         return result;
29574     }
29575     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
29576     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
29577         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
29578     }
29579     ts.createModuleResolutionCache = createModuleResolutionCache;
29580     /*@internal*/
29581     function createCacheWithRedirects(options) {
29582         var ownMap = ts.createMap();
29583         var redirectsMap = ts.createMap();
29584         return {
29585             ownMap: ownMap,
29586             redirectsMap: redirectsMap,
29587             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
29588             clear: clear,
29589             setOwnOptions: setOwnOptions,
29590             setOwnMap: setOwnMap
29591         };
29592         function setOwnOptions(newOptions) {
29593             options = newOptions;
29594         }
29595         function setOwnMap(newOwnMap) {
29596             ownMap = newOwnMap;
29597         }
29598         function getOrCreateMapOfCacheRedirects(redirectedReference) {
29599             if (!redirectedReference) {
29600                 return ownMap;
29601             }
29602             var path = redirectedReference.sourceFile.path;
29603             var redirects = redirectsMap.get(path);
29604             if (!redirects) {
29605                 // Reuse map if redirected reference map uses same resolution
29606                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? ts.createMap() : ownMap;
29607                 redirectsMap.set(path, redirects);
29608             }
29609             return redirects;
29610         }
29611         function clear() {
29612             ownMap.clear();
29613             redirectsMap.clear();
29614         }
29615     }
29616     ts.createCacheWithRedirects = createCacheWithRedirects;
29617     /*@internal*/
29618     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
29619         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
29620         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
29621             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
29622             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
29623         }
29624         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
29625             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
29626             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
29627         }
29628         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
29629             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
29630             var result = cache.get(key);
29631             if (!result) {
29632                 result = create();
29633                 cache.set(key, result);
29634             }
29635             return result;
29636         }
29637         function createPerModuleNameCache() {
29638             var directoryPathMap = ts.createMap();
29639             return { get: get, set: set };
29640             function get(directory) {
29641                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
29642             }
29643             /**
29644              * At first this function add entry directory -> module resolution result to the table.
29645              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
29646              * and for every parent folder in set it adds entry: parent -> module resolution. .
29647              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
29648              * Set of parent folders that should have the same result will be:
29649              * [
29650              *     /a/b/c/d, /a/b/c, /a/b
29651              * ]
29652              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
29653              */
29654             function set(directory, result) {
29655                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
29656                 // if entry is already in cache do nothing
29657                 if (directoryPathMap.has(path)) {
29658                     return;
29659                 }
29660                 directoryPathMap.set(path, result);
29661                 var resolvedFileName = result.resolvedModule &&
29662                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
29663                 // find common prefix between directory and resolved file name
29664                 // this common prefix should be the shortest path that has the same resolution
29665                 // directory: /a/b/c/d/e
29666                 // resolvedFileName: /a/b/foo.d.ts
29667                 // commonPrefix: /a/b
29668                 // for failed lookups cache the result for every directory up to root
29669                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
29670                 var current = path;
29671                 while (current !== commonPrefix) {
29672                     var parent = ts.getDirectoryPath(current);
29673                     if (parent === current || directoryPathMap.has(parent)) {
29674                         break;
29675                     }
29676                     directoryPathMap.set(parent, result);
29677                     current = parent;
29678                 }
29679             }
29680             function getCommonPrefix(directory, resolution) {
29681                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
29682                 // find first position where directory and resolution differs
29683                 var i = 0;
29684                 var limit = Math.min(directory.length, resolutionDirectory.length);
29685                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
29686                     i++;
29687                 }
29688                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
29689                     return directory;
29690                 }
29691                 var rootLength = ts.getRootLength(directory);
29692                 if (i < rootLength) {
29693                     return undefined;
29694                 }
29695                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
29696                 if (sep === -1) {
29697                     return undefined;
29698                 }
29699                 return directory.substr(0, Math.max(sep, rootLength));
29700             }
29701         }
29702     }
29703     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
29704     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
29705         var containingDirectory = ts.getDirectoryPath(containingFile);
29706         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
29707         return perFolderCache && perFolderCache.get(moduleName);
29708     }
29709     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
29710     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
29711         var traceEnabled = isTraceEnabled(compilerOptions, host);
29712         if (redirectedReference) {
29713             compilerOptions = redirectedReference.commandLine.options;
29714         }
29715         if (traceEnabled) {
29716             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
29717             if (redirectedReference) {
29718                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29719             }
29720         }
29721         var containingDirectory = ts.getDirectoryPath(containingFile);
29722         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
29723         var result = perFolderCache && perFolderCache.get(moduleName);
29724         if (result) {
29725             if (traceEnabled) {
29726                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
29727             }
29728         }
29729         else {
29730             var moduleResolution = compilerOptions.moduleResolution;
29731             if (moduleResolution === undefined) {
29732                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
29733                 if (traceEnabled) {
29734                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
29735                 }
29736             }
29737             else {
29738                 if (traceEnabled) {
29739                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
29740                 }
29741             }
29742             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
29743             switch (moduleResolution) {
29744                 case ts.ModuleResolutionKind.NodeJs:
29745                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29746                     break;
29747                 case ts.ModuleResolutionKind.Classic:
29748                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29749                     break;
29750                 default:
29751                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
29752             }
29753             if (result && result.resolvedModule)
29754                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
29755             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
29756             if (perFolderCache) {
29757                 perFolderCache.set(moduleName, result);
29758                 if (!ts.isExternalModuleNameRelative(moduleName)) {
29759                     // put result in per-module name cache
29760                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
29761                 }
29762             }
29763         }
29764         if (traceEnabled) {
29765             if (result.resolvedModule) {
29766                 if (result.resolvedModule.packageId) {
29767                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, ts.packageIdToString(result.resolvedModule.packageId));
29768                 }
29769                 else {
29770                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
29771                 }
29772             }
29773             else {
29774                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
29775             }
29776         }
29777         return result;
29778     }
29779     ts.resolveModuleName = resolveModuleName;
29780     /**
29781      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
29782      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
29783      * can be resolved successfully by TypeScript compiler and runtime module loader.
29784      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
29785      * fallback to standard resolution routine.
29786      *
29787      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
29788      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
29789      * be '/a/b/c/d'
29790      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
29791      * will be resolved based on the content of the module name.
29792      * Structure of 'paths' compiler options
29793      * 'paths': {
29794      *    pattern-1: [...substitutions],
29795      *    pattern-2: [...substitutions],
29796      *    ...
29797      *    pattern-n: [...substitutions]
29798      * }
29799      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
29800      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
29801      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
29802      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
29803      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
29804      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
29805      * from the candidate location.
29806      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
29807      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
29808      * will be converted to absolute using baseUrl.
29809      * For example:
29810      * baseUrl: /a/b/c
29811      * "paths": {
29812      *     // match all module names
29813      *     "*": [
29814      *         "*",        // use matched name as is,
29815      *                     // <matched name> will be looked as /a/b/c/<matched name>
29816      *
29817      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
29818      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
29819      *     ],
29820      *     // match module names that start with 'components/'
29821      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
29822      *                                              // it is rooted so it will be final candidate location
29823      * }
29824      *
29825      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
29826      * they were in the same location. For example lets say there are two files
29827      * '/local/src/content/file1.ts'
29828      * '/shared/components/contracts/src/content/protocols/file2.ts'
29829      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
29830      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
29831      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
29832      * root dirs were merged together.
29833      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
29834      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
29835      * '/local/src/content/protocols/file2' and try to load it - failure.
29836      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
29837      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
29838      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
29839      */
29840     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
29841         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
29842         if (resolved)
29843             return resolved.value;
29844         if (!ts.isExternalModuleNameRelative(moduleName)) {
29845             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
29846         }
29847         else {
29848             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
29849         }
29850     }
29851     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
29852         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
29853         if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
29854             if (state.traceEnabled) {
29855                 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29856                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
29857             }
29858             return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
29859         }
29860     }
29861     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
29862         if (!state.compilerOptions.rootDirs) {
29863             return undefined;
29864         }
29865         if (state.traceEnabled) {
29866             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
29867         }
29868         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
29869         var matchedRootDir;
29870         var matchedNormalizedPrefix;
29871         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
29872             var rootDir = _a[_i];
29873             // rootDirs are expected to be absolute
29874             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
29875             // using location of tsconfig.json as base location
29876             var normalizedRoot = ts.normalizePath(rootDir);
29877             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
29878                 normalizedRoot += ts.directorySeparator;
29879             }
29880             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
29881                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
29882             if (state.traceEnabled) {
29883                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
29884             }
29885             if (isLongestMatchingPrefix) {
29886                 matchedNormalizedPrefix = normalizedRoot;
29887                 matchedRootDir = rootDir;
29888             }
29889         }
29890         if (matchedNormalizedPrefix) {
29891             if (state.traceEnabled) {
29892                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
29893             }
29894             var suffix = candidate.substr(matchedNormalizedPrefix.length);
29895             // first - try to load from a initial location
29896             if (state.traceEnabled) {
29897                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
29898             }
29899             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
29900             if (resolvedFileName) {
29901                 return resolvedFileName;
29902             }
29903             if (state.traceEnabled) {
29904                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
29905             }
29906             // then try to resolve using remaining entries in rootDirs
29907             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
29908                 var rootDir = _c[_b];
29909                 if (rootDir === matchedRootDir) {
29910                     // skip the initially matched entry
29911                     continue;
29912                 }
29913                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
29914                 if (state.traceEnabled) {
29915                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
29916                 }
29917                 var baseDirectory = ts.getDirectoryPath(candidate_1);
29918                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
29919                 if (resolvedFileName_1) {
29920                     return resolvedFileName_1;
29921                 }
29922             }
29923             if (state.traceEnabled) {
29924                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
29925             }
29926         }
29927         return undefined;
29928     }
29929     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
29930         var baseUrl = state.compilerOptions.baseUrl;
29931         if (!baseUrl) {
29932             return undefined;
29933         }
29934         if (state.traceEnabled) {
29935             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29936         }
29937         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
29938         if (state.traceEnabled) {
29939             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
29940         }
29941         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
29942     }
29943     /**
29944      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
29945      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
29946      * Throws an error if the module can't be resolved.
29947      */
29948     /* @internal */
29949     function resolveJSModule(moduleName, initialDir, host) {
29950         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
29951         if (!resolvedModule) {
29952             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
29953         }
29954         return resolvedModule.resolvedFileName;
29955     }
29956     ts.resolveJSModule = resolveJSModule;
29957     /* @internal */
29958     function tryResolveJSModule(moduleName, initialDir, host) {
29959         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
29960         return resolvedModule && resolvedModule.resolvedFileName;
29961     }
29962     ts.tryResolveJSModule = tryResolveJSModule;
29963     var jsOnlyExtensions = [Extensions.JavaScript];
29964     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
29965     var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
29966     var tsconfigExtensions = [Extensions.TSConfig];
29967     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
29968         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
29969     }
29970     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
29971         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
29972     }
29973     ts.nodeModuleNameResolver = nodeModuleNameResolver;
29974     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
29975         var _a, _b;
29976         var traceEnabled = isTraceEnabled(compilerOptions, host);
29977         var failedLookupLocations = [];
29978         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29979         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
29980         return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache);
29981         function tryResolve(extensions) {
29982             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
29983             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
29984             if (resolved) {
29985                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
29986             }
29987             if (!ts.isExternalModuleNameRelative(moduleName)) {
29988                 if (traceEnabled) {
29989                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
29990                 }
29991                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
29992                 if (!resolved_1)
29993                     return undefined;
29994                 var resolvedValue = resolved_1.value;
29995                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
29996                     var path = realPath(resolvedValue.path, host, traceEnabled);
29997                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
29998                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
29999                 }
30000                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
30001                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
30002             }
30003             else {
30004                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
30005                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
30006                 // Treat explicit "node_modules" import as an external library import.
30007                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
30008             }
30009         }
30010     }
30011     function realPath(path, host, traceEnabled) {
30012         if (!host.realpath) {
30013             return path;
30014         }
30015         var real = ts.normalizePath(host.realpath(path));
30016         if (traceEnabled) {
30017             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
30018         }
30019         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
30020         return real;
30021     }
30022     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30023         if (state.traceEnabled) {
30024             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
30025         }
30026         if (!ts.hasTrailingDirectorySeparator(candidate)) {
30027             if (!onlyRecordFailures) {
30028                 var parentOfCandidate = ts.getDirectoryPath(candidate);
30029                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
30030                     if (state.traceEnabled) {
30031                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
30032                     }
30033                     onlyRecordFailures = true;
30034                 }
30035             }
30036             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
30037             if (resolvedFromFile) {
30038                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
30039                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
30040                 return withPackageId(packageInfo, resolvedFromFile);
30041             }
30042         }
30043         if (!onlyRecordFailures) {
30044             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
30045             if (!candidateExists) {
30046                 if (state.traceEnabled) {
30047                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
30048                 }
30049                 onlyRecordFailures = true;
30050             }
30051         }
30052         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
30053     }
30054     /*@internal*/
30055     ts.nodeModulesPathPart = "/node_modules/";
30056     /*@internal*/
30057     function pathContainsNodeModules(path) {
30058         return ts.stringContains(path, ts.nodeModulesPathPart);
30059     }
30060     ts.pathContainsNodeModules = pathContainsNodeModules;
30061     /**
30062      * This will be called on the successfully resolved path from `loadModuleFromFile`.
30063      * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
30064      *
30065      * packageDirectory is the directory of the package itself.
30066      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
30067      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
30068      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
30069      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
30070      */
30071     function parseNodeModuleFromPath(resolved) {
30072         var path = ts.normalizePath(resolved.path);
30073         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
30074         if (idx === -1) {
30075             return undefined;
30076         }
30077         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
30078         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
30079         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
30080             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
30081         }
30082         return path.slice(0, indexAfterPackageName);
30083     }
30084     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
30085         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
30086         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
30087     }
30088     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
30089         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
30090     }
30091     /**
30092      * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
30093      * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
30094      */
30095     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
30096         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
30097             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
30098             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
30099         }
30100         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
30101         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
30102         if (resolvedByAddingExtension) {
30103             return resolvedByAddingExtension;
30104         }
30105         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
30106         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
30107         if (ts.hasJSFileExtension(candidate)) {
30108             var extensionless = ts.removeFileExtension(candidate);
30109             if (state.traceEnabled) {
30110                 var extension = candidate.substring(extensionless.length);
30111                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
30112             }
30113             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
30114         }
30115     }
30116     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
30117     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
30118         if (!onlyRecordFailures) {
30119             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
30120             var directory = ts.getDirectoryPath(candidate);
30121             if (directory) {
30122                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
30123             }
30124         }
30125         switch (extensions) {
30126             case Extensions.DtsOnly:
30127                 return tryExtension(".d.ts" /* Dts */);
30128             case Extensions.TypeScript:
30129                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
30130             case Extensions.JavaScript:
30131                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
30132             case Extensions.TSConfig:
30133             case Extensions.Json:
30134                 return tryExtension(".json" /* Json */);
30135         }
30136         function tryExtension(ext) {
30137             var path = tryFile(candidate + ext, onlyRecordFailures, state);
30138             return path === undefined ? undefined : { path: path, ext: ext };
30139         }
30140     }
30141     /** Return the file if it exists. */
30142     function tryFile(fileName, onlyRecordFailures, state) {
30143         if (!onlyRecordFailures) {
30144             if (state.host.fileExists(fileName)) {
30145                 if (state.traceEnabled) {
30146                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
30147                 }
30148                 return fileName;
30149             }
30150             else {
30151                 if (state.traceEnabled) {
30152                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
30153                 }
30154             }
30155         }
30156         state.failedLookupLocations.push(fileName);
30157         return undefined;
30158     }
30159     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30160         if (considerPackageJson === void 0) { considerPackageJson = true; }
30161         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
30162         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
30163         var versionPaths = packageInfo && packageInfo.versionPaths;
30164         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
30165     }
30166     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
30167         var host = state.host, traceEnabled = state.traceEnabled;
30168         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
30169         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
30170         if (directoryExists && host.fileExists(packageJsonPath)) {
30171             var packageJsonContent = ts.readJson(packageJsonPath, host);
30172             if (traceEnabled) {
30173                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
30174             }
30175             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
30176             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
30177         }
30178         else {
30179             if (directoryExists && traceEnabled) {
30180                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
30181             }
30182             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
30183             state.failedLookupLocations.push(packageJsonPath);
30184         }
30185     }
30186     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
30187         var packageFile;
30188         if (jsonContent) {
30189             switch (extensions) {
30190                 case Extensions.JavaScript:
30191                 case Extensions.Json:
30192                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
30193                     break;
30194                 case Extensions.TypeScript:
30195                     // When resolving typescript modules, try resolving using main field as well
30196                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
30197                     break;
30198                 case Extensions.DtsOnly:
30199                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
30200                     break;
30201                 case Extensions.TSConfig:
30202                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
30203                     break;
30204                 default:
30205                     return ts.Debug.assertNever(extensions);
30206             }
30207         }
30208         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30209             var fromFile = tryFile(candidate, onlyRecordFailures, state);
30210             if (fromFile) {
30211                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
30212                 if (resolved) {
30213                     return noPackageId(resolved);
30214                 }
30215                 if (state.traceEnabled) {
30216                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
30217                 }
30218             }
30219             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
30220             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
30221             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
30222             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
30223         };
30224         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
30225         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
30226         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
30227         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
30228             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
30229             if (state.traceEnabled) {
30230                 trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName);
30231             }
30232             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
30233             if (result) {
30234                 return removeIgnoredPackageId(result.value);
30235             }
30236         }
30237         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
30238         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
30239         if (packageFileResult)
30240             return packageFileResult;
30241         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
30242     }
30243     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
30244     function resolvedIfExtensionMatches(extensions, path) {
30245         var ext = ts.tryGetExtensionFromPath(path);
30246         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
30247     }
30248     /** True if `extension` is one of the supported `extensions`. */
30249     function extensionIsOk(extensions, extension) {
30250         switch (extensions) {
30251             case Extensions.JavaScript:
30252                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
30253             case Extensions.TSConfig:
30254             case Extensions.Json:
30255                 return extension === ".json" /* Json */;
30256             case Extensions.TypeScript:
30257                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
30258             case Extensions.DtsOnly:
30259                 return extension === ".d.ts" /* Dts */;
30260         }
30261     }
30262     /* @internal */
30263     function parsePackageName(moduleName) {
30264         var idx = moduleName.indexOf(ts.directorySeparator);
30265         if (moduleName[0] === "@") {
30266             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
30267         }
30268         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
30269     }
30270     ts.parsePackageName = parsePackageName;
30271     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
30272         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
30273     }
30274     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
30275         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
30276         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
30277     }
30278     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
30279         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30280         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
30281             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
30282                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
30283                 if (resolutionFromCache) {
30284                     return resolutionFromCache;
30285                 }
30286                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
30287             }
30288         });
30289     }
30290     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
30291         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
30292         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
30293         if (!nodeModulesFolderExists && state.traceEnabled) {
30294             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
30295         }
30296         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
30297         if (packageResult) {
30298             return packageResult;
30299         }
30300         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
30301             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
30302             var nodeModulesAtTypesExists = nodeModulesFolderExists;
30303             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
30304                 if (state.traceEnabled) {
30305                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
30306                 }
30307                 nodeModulesAtTypesExists = false;
30308             }
30309             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
30310         }
30311     }
30312     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
30313         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
30314         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
30315         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
30316         if (packageInfo) {
30317             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
30318             if (fromFile) {
30319                 return noPackageId(fromFile);
30320             }
30321             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
30322             return withPackageId(packageInfo, fromDirectory);
30323         }
30324         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30325             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
30326                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
30327             return withPackageId(packageInfo, pathAndExtension);
30328         };
30329         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
30330         if (rest !== "") { // If "rest" is empty, we just did this search above.
30331             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
30332             // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
30333             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
30334             if (packageInfo && packageInfo.versionPaths) {
30335                 if (state.traceEnabled) {
30336                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
30337                 }
30338                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
30339                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
30340                 if (fromPaths) {
30341                     return fromPaths.value;
30342                 }
30343             }
30344         }
30345         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
30346     }
30347     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
30348         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
30349         if (matchedPattern) {
30350             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
30351             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
30352             if (state.traceEnabled) {
30353                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
30354             }
30355             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
30356                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
30357                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
30358                 if (state.traceEnabled) {
30359                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
30360                 }
30361                 // A path mapping may have an extension, in contrast to an import, which should omit it.
30362                 var extension = ts.tryGetExtensionFromPath(candidate);
30363                 if (extension !== undefined) {
30364                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
30365                     if (path_1 !== undefined) {
30366                         return noPackageId({ path: path_1, ext: extension });
30367                     }
30368                 }
30369                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
30370             });
30371             return { value: resolved };
30372         }
30373     }
30374     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
30375     var mangledScopedPackageSeparator = "__";
30376     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
30377     function mangleScopedPackageNameWithTrace(packageName, state) {
30378         var mangled = mangleScopedPackageName(packageName);
30379         if (state.traceEnabled && mangled !== packageName) {
30380             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
30381         }
30382         return mangled;
30383     }
30384     /* @internal */
30385     function getTypesPackageName(packageName) {
30386         return "@types/" + mangleScopedPackageName(packageName);
30387     }
30388     ts.getTypesPackageName = getTypesPackageName;
30389     /* @internal */
30390     function mangleScopedPackageName(packageName) {
30391         if (ts.startsWith(packageName, "@")) {
30392             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
30393             if (replaceSlash !== packageName) {
30394                 return replaceSlash.slice(1); // Take off the "@"
30395             }
30396         }
30397         return packageName;
30398     }
30399     ts.mangleScopedPackageName = mangleScopedPackageName;
30400     /* @internal */
30401     function getPackageNameFromTypesPackageName(mangledName) {
30402         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
30403         if (withoutAtTypePrefix !== mangledName) {
30404             return unmangleScopedPackageName(withoutAtTypePrefix);
30405         }
30406         return mangledName;
30407     }
30408     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
30409     /* @internal */
30410     function unmangleScopedPackageName(typesPackageName) {
30411         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
30412             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
30413             typesPackageName;
30414     }
30415     ts.unmangleScopedPackageName = unmangleScopedPackageName;
30416     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
30417         var result = cache && cache.get(containingDirectory);
30418         if (result) {
30419             if (state.traceEnabled) {
30420                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
30421             }
30422             state.resultFromCache = result;
30423             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
30424         }
30425     }
30426     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
30427         var traceEnabled = isTraceEnabled(compilerOptions, host);
30428         var failedLookupLocations = [];
30429         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30430         var containingDirectory = ts.getDirectoryPath(containingFile);
30431         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
30432         // No originalPath because classic resolution doesn't resolve realPath
30433         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
30434         function tryResolve(extensions) {
30435             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
30436             if (resolvedUsingSettings) {
30437                 return { value: resolvedUsingSettings };
30438             }
30439             if (!ts.isExternalModuleNameRelative(moduleName)) {
30440                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30441                 // Climb up parent directories looking for a module.
30442                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
30443                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
30444                     if (resolutionFromCache) {
30445                         return resolutionFromCache;
30446                     }
30447                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
30448                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
30449                 });
30450                 if (resolved_3) {
30451                     return resolved_3;
30452                 }
30453                 if (extensions === Extensions.TypeScript) {
30454                     // If we didn't find the file normally, look it up in @types.
30455                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
30456                 }
30457             }
30458             else {
30459                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
30460                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
30461             }
30462         }
30463     }
30464     ts.classicNameResolver = classicNameResolver;
30465     /**
30466      * A host may load a module from a global cache of typings.
30467      * This is the minumum code needed to expose that functionality; the rest is in the host.
30468      */
30469     /* @internal */
30470     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
30471         var traceEnabled = isTraceEnabled(compilerOptions, host);
30472         if (traceEnabled) {
30473             trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
30474         }
30475         var failedLookupLocations = [];
30476         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30477         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
30478         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
30479     }
30480     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
30481     /**
30482      * Wraps value to SearchResult.
30483      * @returns undefined if value is undefined or { value } otherwise
30484      */
30485     function toSearchResult(value) {
30486         return value !== undefined ? { value: value } : undefined;
30487     }
30488 })(ts || (ts = {}));
30489 /* @internal */
30490 var ts;
30491 (function (ts) {
30492     var ModuleInstanceState;
30493     (function (ModuleInstanceState) {
30494         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
30495         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
30496         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
30497     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
30498     function getModuleInstanceState(node, visited) {
30499         if (node.body && !node.body.parent) {
30500             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
30501             setParentPointers(node, node.body);
30502         }
30503         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
30504     }
30505     ts.getModuleInstanceState = getModuleInstanceState;
30506     function getModuleInstanceStateCached(node, visited) {
30507         if (visited === void 0) { visited = ts.createMap(); }
30508         var nodeId = "" + ts.getNodeId(node);
30509         if (visited.has(nodeId)) {
30510             return visited.get(nodeId) || 0 /* NonInstantiated */;
30511         }
30512         visited.set(nodeId, undefined);
30513         var result = getModuleInstanceStateWorker(node, visited);
30514         visited.set(nodeId, result);
30515         return result;
30516     }
30517     function getModuleInstanceStateWorker(node, visited) {
30518         // A module is uninstantiated if it contains only
30519         switch (node.kind) {
30520             // 1. interface declarations, type alias declarations
30521             case 246 /* InterfaceDeclaration */:
30522             case 247 /* TypeAliasDeclaration */:
30523                 return 0 /* NonInstantiated */;
30524             // 2. const enum declarations
30525             case 248 /* EnumDeclaration */:
30526                 if (ts.isEnumConst(node)) {
30527                     return 2 /* ConstEnumOnly */;
30528                 }
30529                 break;
30530             // 3. non-exported import declarations
30531             case 254 /* ImportDeclaration */:
30532             case 253 /* ImportEqualsDeclaration */:
30533                 if (!(ts.hasModifier(node, 1 /* Export */))) {
30534                     return 0 /* NonInstantiated */;
30535                 }
30536                 break;
30537             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
30538             case 260 /* ExportDeclaration */:
30539                 var exportDeclaration = node;
30540                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 261 /* NamedExports */) {
30541                     var state = 0 /* NonInstantiated */;
30542                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
30543                         var specifier = _a[_i];
30544                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
30545                         if (specifierState > state) {
30546                             state = specifierState;
30547                         }
30548                         if (state === 1 /* Instantiated */) {
30549                             return state;
30550                         }
30551                     }
30552                     return state;
30553                 }
30554                 break;
30555             // 5. other uninstantiated module declarations.
30556             case 250 /* ModuleBlock */: {
30557                 var state_1 = 0 /* NonInstantiated */;
30558                 ts.forEachChild(node, function (n) {
30559                     var childState = getModuleInstanceStateCached(n, visited);
30560                     switch (childState) {
30561                         case 0 /* NonInstantiated */:
30562                             // child is non-instantiated - continue searching
30563                             return;
30564                         case 2 /* ConstEnumOnly */:
30565                             // child is const enum only - record state and continue searching
30566                             state_1 = 2 /* ConstEnumOnly */;
30567                             return;
30568                         case 1 /* Instantiated */:
30569                             // child is instantiated - record state and stop
30570                             state_1 = 1 /* Instantiated */;
30571                             return true;
30572                         default:
30573                             ts.Debug.assertNever(childState);
30574                     }
30575                 });
30576                 return state_1;
30577             }
30578             case 249 /* ModuleDeclaration */:
30579                 return getModuleInstanceState(node, visited);
30580             case 75 /* Identifier */:
30581                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
30582                 // be considered the same as type alias
30583                 if (node.isInJSDocNamespace) {
30584                     return 0 /* NonInstantiated */;
30585                 }
30586         }
30587         return 1 /* Instantiated */;
30588     }
30589     function getModuleInstanceStateForAliasTarget(specifier, visited) {
30590         var name = specifier.propertyName || specifier.name;
30591         var p = specifier.parent;
30592         while (p) {
30593             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
30594                 var statements = p.statements;
30595                 var found = void 0;
30596                 for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
30597                     var statement = statements_1[_i];
30598                     if (ts.nodeHasName(statement, name)) {
30599                         if (!statement.parent) {
30600                             setParentPointers(p, statement);
30601                         }
30602                         var state = getModuleInstanceStateCached(statement, visited);
30603                         if (found === undefined || state > found) {
30604                             found = state;
30605                         }
30606                         if (found === 1 /* Instantiated */) {
30607                             return found;
30608                         }
30609                     }
30610                 }
30611                 if (found !== undefined) {
30612                     return found;
30613                 }
30614             }
30615             p = p.parent;
30616         }
30617         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
30618     }
30619     var ContainerFlags;
30620     (function (ContainerFlags) {
30621         // The current node is not a container, and no container manipulation should happen before
30622         // recursing into it.
30623         ContainerFlags[ContainerFlags["None"] = 0] = "None";
30624         // The current node is a container.  It should be set as the current container (and block-
30625         // container) before recursing into it.  The current node does not have locals.  Examples:
30626         //
30627         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
30628         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
30629         // The current node is a block-scoped-container.  It should be set as the current block-
30630         // container before recursing into it.  Examples:
30631         //
30632         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
30633         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
30634         // The current node is the container of a control flow path. The current control flow should
30635         // be saved and restored, and a new control flow initialized within the container.
30636         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
30637         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
30638         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
30639         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
30640         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
30641         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
30642     })(ContainerFlags || (ContainerFlags = {}));
30643     function initFlowNode(node) {
30644         ts.Debug.attachFlowNodeDebugInfo(node);
30645         return node;
30646     }
30647     var binder = createBinder();
30648     function bindSourceFile(file, options) {
30649         ts.performance.mark("beforeBind");
30650         ts.perfLogger.logStartBindFile("" + file.fileName);
30651         binder(file, options);
30652         ts.perfLogger.logStopBindFile();
30653         ts.performance.mark("afterBind");
30654         ts.performance.measure("Bind", "beforeBind", "afterBind");
30655     }
30656     ts.bindSourceFile = bindSourceFile;
30657     function createBinder() {
30658         var file;
30659         var options;
30660         var languageVersion;
30661         var parent;
30662         var container;
30663         var thisParentContainer; // Container one level up
30664         var blockScopeContainer;
30665         var lastContainer;
30666         var delayedTypeAliases;
30667         var seenThisKeyword;
30668         // state used by control flow analysis
30669         var currentFlow;
30670         var currentBreakTarget;
30671         var currentContinueTarget;
30672         var currentReturnTarget;
30673         var currentTrueTarget;
30674         var currentFalseTarget;
30675         var currentExceptionTarget;
30676         var preSwitchCaseFlow;
30677         var activeLabelList;
30678         var hasExplicitReturn;
30679         // state used for emit helpers
30680         var emitFlags;
30681         // If this file is an external module, then it is automatically in strict-mode according to
30682         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
30683         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
30684         // or if compiler options contain alwaysStrict.
30685         var inStrictMode;
30686         var symbolCount = 0;
30687         var Symbol;
30688         var classifiableNames;
30689         var unreachableFlow = { flags: 1 /* Unreachable */ };
30690         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
30691         // state used to aggregate transform flags during bind.
30692         var subtreeTransformFlags = 0 /* None */;
30693         var skipTransformFlagAggregation;
30694         /**
30695          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
30696          * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node)
30697          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
30698          */
30699         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
30700             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
30701         }
30702         function bindSourceFile(f, opts) {
30703             file = f;
30704             options = opts;
30705             languageVersion = ts.getEmitScriptTarget(options);
30706             inStrictMode = bindInStrictMode(file, opts);
30707             classifiableNames = ts.createUnderscoreEscapedMap();
30708             symbolCount = 0;
30709             skipTransformFlagAggregation = file.isDeclarationFile;
30710             Symbol = ts.objectAllocator.getSymbolConstructor();
30711             // Attach debugging information if necessary
30712             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
30713             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
30714             if (!file.locals) {
30715                 bind(file);
30716                 file.symbolCount = symbolCount;
30717                 file.classifiableNames = classifiableNames;
30718                 delayedBindJSDocTypedefTag();
30719             }
30720             file = undefined;
30721             options = undefined;
30722             languageVersion = undefined;
30723             parent = undefined;
30724             container = undefined;
30725             thisParentContainer = undefined;
30726             blockScopeContainer = undefined;
30727             lastContainer = undefined;
30728             delayedTypeAliases = undefined;
30729             seenThisKeyword = false;
30730             currentFlow = undefined;
30731             currentBreakTarget = undefined;
30732             currentContinueTarget = undefined;
30733             currentReturnTarget = undefined;
30734             currentTrueTarget = undefined;
30735             currentFalseTarget = undefined;
30736             currentExceptionTarget = undefined;
30737             activeLabelList = undefined;
30738             hasExplicitReturn = false;
30739             emitFlags = 0 /* None */;
30740             subtreeTransformFlags = 0 /* None */;
30741         }
30742         return bindSourceFile;
30743         function bindInStrictMode(file, opts) {
30744             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
30745                 // bind in strict mode source files with alwaysStrict option
30746                 return true;
30747             }
30748             else {
30749                 return !!file.externalModuleIndicator;
30750             }
30751         }
30752         function createSymbol(flags, name) {
30753             symbolCount++;
30754             return new Symbol(flags, name);
30755         }
30756         function addDeclarationToSymbol(symbol, node, symbolFlags) {
30757             symbol.flags |= symbolFlags;
30758             node.symbol = symbol;
30759             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
30760             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
30761                 symbol.exports = ts.createSymbolTable();
30762             }
30763             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
30764                 symbol.members = ts.createSymbolTable();
30765             }
30766             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
30767             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
30768                 symbol.constEnumOnlyModule = false;
30769             }
30770             if (symbolFlags & 111551 /* Value */) {
30771                 ts.setValueDeclaration(symbol, node);
30772             }
30773         }
30774         // Should not be called on a declaration with a computed property name,
30775         // unless it is a well known Symbol.
30776         function getDeclarationName(node) {
30777             if (node.kind === 259 /* ExportAssignment */) {
30778                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
30779             }
30780             var name = ts.getNameOfDeclaration(node);
30781             if (name) {
30782                 if (ts.isAmbientModule(node)) {
30783                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
30784                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
30785                 }
30786                 if (name.kind === 154 /* ComputedPropertyName */) {
30787                     var nameExpression = name.expression;
30788                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
30789                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
30790                         return ts.escapeLeadingUnderscores(nameExpression.text);
30791                     }
30792                     if (ts.isSignedNumericLiteral(nameExpression)) {
30793                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
30794                     }
30795                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
30796                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
30797                 }
30798                 if (ts.isWellKnownSymbolSyntactically(name)) {
30799                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
30800                 }
30801                 if (ts.isPrivateIdentifier(name)) {
30802                     // containingClass exists because private names only allowed inside classes
30803                     var containingClass = ts.getContainingClass(node);
30804                     if (!containingClass) {
30805                         // we can get here in cases where there is already a parse error.
30806                         return undefined;
30807                     }
30808                     var containingClassSymbol = containingClass.symbol;
30809                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
30810                 }
30811                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
30812             }
30813             switch (node.kind) {
30814                 case 162 /* Constructor */:
30815                     return "__constructor" /* Constructor */;
30816                 case 170 /* FunctionType */:
30817                 case 165 /* CallSignature */:
30818                 case 305 /* JSDocSignature */:
30819                     return "__call" /* Call */;
30820                 case 171 /* ConstructorType */:
30821                 case 166 /* ConstructSignature */:
30822                     return "__new" /* New */;
30823                 case 167 /* IndexSignature */:
30824                     return "__index" /* Index */;
30825                 case 260 /* ExportDeclaration */:
30826                     return "__export" /* ExportStar */;
30827                 case 290 /* SourceFile */:
30828                     // json file should behave as
30829                     // module.exports = ...
30830                     return "export=" /* ExportEquals */;
30831                 case 209 /* BinaryExpression */:
30832                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
30833                         // module.exports = ...
30834                         return "export=" /* ExportEquals */;
30835                     }
30836                     ts.Debug.fail("Unknown binary declaration kind");
30837                     break;
30838                 case 300 /* JSDocFunctionType */:
30839                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
30840                 case 156 /* Parameter */:
30841                     // Parameters with names are handled at the top of this function.  Parameters
30842                     // without names can only come from JSDocFunctionTypes.
30843                     ts.Debug.assert(node.parent.kind === 300 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
30844                     var functionType = node.parent;
30845                     var index = functionType.parameters.indexOf(node);
30846                     return "arg" + index;
30847             }
30848         }
30849         function getDisplayName(node) {
30850             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
30851         }
30852         /**
30853          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
30854          * @param symbolTable - The symbol table which node will be added to.
30855          * @param parent - node's parent declaration.
30856          * @param node - The declaration to be added to the symbol table
30857          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
30858          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
30859          */
30860         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
30861             ts.Debug.assert(!ts.hasDynamicName(node));
30862             var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
30863             // The exported symbol for an export default function/class node is always named "default"
30864             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
30865             var symbol;
30866             if (name === undefined) {
30867                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
30868             }
30869             else {
30870                 // Check and see if the symbol table already has a symbol with this name.  If not,
30871                 // create a new symbol with this name and add it to the table.  Note that we don't
30872                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
30873                 // with the 'excludes' flags we pass in.
30874                 //
30875                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
30876                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
30877                 // the same symbol table.  If we have a conflict, report the issue on each
30878                 // declaration we have for this symbol, and then create a new symbol for this
30879                 // declaration.
30880                 //
30881                 // Note that when properties declared in Javascript constructors
30882                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
30883                 // Always. This allows the common Javascript pattern of overwriting a prototype method
30884                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
30885                 //
30886                 // If we created a new symbol, either because we didn't have a symbol with this name
30887                 // in the symbol table, or we conflicted with an existing symbol, then just add this
30888                 // node as the sole declaration of the new symbol.
30889                 //
30890                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
30891                 // you have multiple 'vars' with the same name in the same container).  In this case
30892                 // just add this node into the declarations list of the symbol.
30893                 symbol = symbolTable.get(name);
30894                 if (includes & 2885600 /* Classifiable */) {
30895                     classifiableNames.set(name, true);
30896                 }
30897                 if (!symbol) {
30898                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30899                     if (isReplaceableByMethod)
30900                         symbol.isReplaceableByMethod = true;
30901                 }
30902                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
30903                     // A symbol already exists, so don't add this as a declaration.
30904                     return symbol;
30905                 }
30906                 else if (symbol.flags & excludes) {
30907                     if (symbol.isReplaceableByMethod) {
30908                         // Javascript constructor-declared symbols can be discarded in favor of
30909                         // prototype symbols like methods.
30910                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30911                     }
30912                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
30913                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
30914                         if (ts.isNamedDeclaration(node)) {
30915                             node.name.parent = node;
30916                         }
30917                         // Report errors every position with duplicate declaration
30918                         // Report errors on previous encountered declarations
30919                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
30920                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
30921                             : ts.Diagnostics.Duplicate_identifier_0;
30922                         var messageNeedsName_1 = true;
30923                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
30924                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
30925                             messageNeedsName_1 = false;
30926                         }
30927                         var multipleDefaultExports_1 = false;
30928                         if (ts.length(symbol.declarations)) {
30929                             // If the current node is a default export of some sort, then check if
30930                             // there are any other default exports that we need to error on.
30931                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
30932                             if (isDefaultExport) {
30933                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30934                                 messageNeedsName_1 = false;
30935                                 multipleDefaultExports_1 = true;
30936                             }
30937                             else {
30938                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
30939                                 // Error on multiple export default in the following case:
30940                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
30941                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
30942                                 if (symbol.declarations && symbol.declarations.length &&
30943                                     (node.kind === 259 /* ExportAssignment */ && !node.isExportEquals)) {
30944                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30945                                     messageNeedsName_1 = false;
30946                                     multipleDefaultExports_1 = true;
30947                                 }
30948                             }
30949                         }
30950                         var relatedInformation_1 = [];
30951                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
30952                             // export type T; - may have meant export type { T }?
30953                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
30954                         }
30955                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
30956                         ts.forEach(symbol.declarations, function (declaration, index) {
30957                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
30958                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
30959                             file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
30960                             if (multipleDefaultExports_1) {
30961                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
30962                             }
30963                         });
30964                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
30965                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
30966                         symbol = createSymbol(0 /* None */, name);
30967                     }
30968                 }
30969             }
30970             addDeclarationToSymbol(symbol, node, includes);
30971             if (symbol.parent) {
30972                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
30973             }
30974             else {
30975                 symbol.parent = parent;
30976             }
30977             return symbol;
30978         }
30979         function declareModuleMember(node, symbolFlags, symbolExcludes) {
30980             var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
30981             if (symbolFlags & 2097152 /* Alias */) {
30982                 if (node.kind === 263 /* ExportSpecifier */ || (node.kind === 253 /* ImportEqualsDeclaration */ && hasExportModifier)) {
30983                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
30984                 }
30985                 else {
30986                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
30987                 }
30988             }
30989             else {
30990                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
30991                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
30992                 //
30993                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
30994                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
30995                 //      with the same name in the same container.
30996                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
30997                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
30998                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
30999                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
31000                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
31001                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
31002                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
31003                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
31004                 if (ts.isJSDocTypeAlias(node))
31005                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
31006                 if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
31007                     if (!container.locals || (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
31008                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
31009                     }
31010                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
31011                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
31012                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
31013                     node.localSymbol = local;
31014                     return local;
31015                 }
31016                 else {
31017                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
31018                 }
31019             }
31020         }
31021         // All container nodes are kept on a linked list in declaration order. This list is used by
31022         // the getLocalNameOfContainer function in the type checker to validate that the local name
31023         // used for a container is unique.
31024         function bindContainer(node, containerFlags) {
31025             // Before we recurse into a node's children, we first save the existing parent, container
31026             // and block-container.  Then after we pop out of processing the children, we restore
31027             // these saved values.
31028             var saveContainer = container;
31029             var saveThisParentContainer = thisParentContainer;
31030             var savedBlockScopeContainer = blockScopeContainer;
31031             // Depending on what kind of node this is, we may have to adjust the current container
31032             // and block-container.   If the current node is a container, then it is automatically
31033             // considered the current block-container as well.  Also, for containers that we know
31034             // may contain locals, we eagerly initialize the .locals field. We do this because
31035             // it's highly likely that the .locals will be needed to place some child in (for example,
31036             // a parameter, or variable declaration).
31037             //
31038             // However, we do not proactively create the .locals for block-containers because it's
31039             // totally normal and common for block-containers to never actually have a block-scoped
31040             // variable in them.  We don't want to end up allocating an object for every 'block' we
31041             // run into when most of them won't be necessary.
31042             //
31043             // Finally, if this is a block-container, then we clear out any existing .locals object
31044             // it may contain within it.  This happens in incremental scenarios.  Because we can be
31045             // reusing a node from a previous compilation, that node may have had 'locals' created
31046             // for it.  We must clear this so we don't accidentally move any stale data forward from
31047             // a previous compilation.
31048             if (containerFlags & 1 /* IsContainer */) {
31049                 if (node.kind !== 202 /* ArrowFunction */) {
31050                     thisParentContainer = container;
31051                 }
31052                 container = blockScopeContainer = node;
31053                 if (containerFlags & 32 /* HasLocals */) {
31054                     container.locals = ts.createSymbolTable();
31055                 }
31056                 addToContainerChain(container);
31057             }
31058             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
31059                 blockScopeContainer = node;
31060                 blockScopeContainer.locals = undefined;
31061             }
31062             if (containerFlags & 4 /* IsControlFlowContainer */) {
31063                 var saveCurrentFlow = currentFlow;
31064                 var saveBreakTarget = currentBreakTarget;
31065                 var saveContinueTarget = currentContinueTarget;
31066                 var saveReturnTarget = currentReturnTarget;
31067                 var saveExceptionTarget = currentExceptionTarget;
31068                 var saveActiveLabelList = activeLabelList;
31069                 var saveHasExplicitReturn = hasExplicitReturn;
31070                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
31071                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
31072                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
31073                 // similarly to break statements that exit to a label just past the statement body.
31074                 if (!isIIFE) {
31075                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
31076                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
31077                         currentFlow.node = node;
31078                     }
31079                 }
31080                 // We create a return control flow graph for IIFEs and constructors. For constructors
31081                 // we use the return control flow graph in strict property initialization checks.
31082                 currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined;
31083                 currentExceptionTarget = undefined;
31084                 currentBreakTarget = undefined;
31085                 currentContinueTarget = undefined;
31086                 activeLabelList = undefined;
31087                 hasExplicitReturn = false;
31088                 bindChildren(node);
31089                 // Reset all reachability check related flags on node (for incremental scenarios)
31090                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
31091                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
31092                     node.flags |= 256 /* HasImplicitReturn */;
31093                     if (hasExplicitReturn)
31094                         node.flags |= 512 /* HasExplicitReturn */;
31095                     node.endFlowNode = currentFlow;
31096                 }
31097                 if (node.kind === 290 /* SourceFile */) {
31098                     node.flags |= emitFlags;
31099                 }
31100                 if (currentReturnTarget) {
31101                     addAntecedent(currentReturnTarget, currentFlow);
31102                     currentFlow = finishFlowLabel(currentReturnTarget);
31103                     if (node.kind === 162 /* Constructor */) {
31104                         node.returnFlowNode = currentFlow;
31105                     }
31106                 }
31107                 if (!isIIFE) {
31108                     currentFlow = saveCurrentFlow;
31109                 }
31110                 currentBreakTarget = saveBreakTarget;
31111                 currentContinueTarget = saveContinueTarget;
31112                 currentReturnTarget = saveReturnTarget;
31113                 currentExceptionTarget = saveExceptionTarget;
31114                 activeLabelList = saveActiveLabelList;
31115                 hasExplicitReturn = saveHasExplicitReturn;
31116             }
31117             else if (containerFlags & 64 /* IsInterface */) {
31118                 seenThisKeyword = false;
31119                 bindChildren(node);
31120                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
31121             }
31122             else {
31123                 bindChildren(node);
31124             }
31125             container = saveContainer;
31126             thisParentContainer = saveThisParentContainer;
31127             blockScopeContainer = savedBlockScopeContainer;
31128         }
31129         function bindChildren(node) {
31130             if (skipTransformFlagAggregation) {
31131                 bindChildrenWorker(node);
31132             }
31133             else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31134                 skipTransformFlagAggregation = true;
31135                 bindChildrenWorker(node);
31136                 skipTransformFlagAggregation = false;
31137                 subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31138             }
31139             else {
31140                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31141                 subtreeTransformFlags = 0;
31142                 bindChildrenWorker(node);
31143                 subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
31144             }
31145         }
31146         function bindEachFunctionsFirst(nodes) {
31147             bindEach(nodes, function (n) { return n.kind === 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31148             bindEach(nodes, function (n) { return n.kind !== 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31149         }
31150         function bindEach(nodes, bindFunction) {
31151             if (bindFunction === void 0) { bindFunction = bind; }
31152             if (nodes === undefined) {
31153                 return;
31154             }
31155             if (skipTransformFlagAggregation) {
31156                 ts.forEach(nodes, bindFunction);
31157             }
31158             else {
31159                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31160                 subtreeTransformFlags = 0 /* None */;
31161                 var nodeArrayFlags = 0 /* None */;
31162                 for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
31163                     var node = nodes_2[_i];
31164                     bindFunction(node);
31165                     nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
31166                 }
31167                 nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
31168                 subtreeTransformFlags |= savedSubtreeTransformFlags;
31169             }
31170         }
31171         function bindEachChild(node) {
31172             ts.forEachChild(node, bind, bindEach);
31173         }
31174         function bindChildrenWorker(node) {
31175             if (checkUnreachable(node)) {
31176                 bindEachChild(node);
31177                 bindJSDoc(node);
31178                 return;
31179             }
31180             if (node.kind >= 225 /* FirstStatement */ && node.kind <= 241 /* LastStatement */ && !options.allowUnreachableCode) {
31181                 node.flowNode = currentFlow;
31182             }
31183             switch (node.kind) {
31184                 case 229 /* WhileStatement */:
31185                     bindWhileStatement(node);
31186                     break;
31187                 case 228 /* DoStatement */:
31188                     bindDoStatement(node);
31189                     break;
31190                 case 230 /* ForStatement */:
31191                     bindForStatement(node);
31192                     break;
31193                 case 231 /* ForInStatement */:
31194                 case 232 /* ForOfStatement */:
31195                     bindForInOrForOfStatement(node);
31196                     break;
31197                 case 227 /* IfStatement */:
31198                     bindIfStatement(node);
31199                     break;
31200                 case 235 /* ReturnStatement */:
31201                 case 239 /* ThrowStatement */:
31202                     bindReturnOrThrow(node);
31203                     break;
31204                 case 234 /* BreakStatement */:
31205                 case 233 /* ContinueStatement */:
31206                     bindBreakOrContinueStatement(node);
31207                     break;
31208                 case 240 /* TryStatement */:
31209                     bindTryStatement(node);
31210                     break;
31211                 case 237 /* SwitchStatement */:
31212                     bindSwitchStatement(node);
31213                     break;
31214                 case 251 /* CaseBlock */:
31215                     bindCaseBlock(node);
31216                     break;
31217                 case 277 /* CaseClause */:
31218                     bindCaseClause(node);
31219                     break;
31220                 case 226 /* ExpressionStatement */:
31221                     bindExpressionStatement(node);
31222                     break;
31223                 case 238 /* LabeledStatement */:
31224                     bindLabeledStatement(node);
31225                     break;
31226                 case 207 /* PrefixUnaryExpression */:
31227                     bindPrefixUnaryExpressionFlow(node);
31228                     break;
31229                 case 208 /* PostfixUnaryExpression */:
31230                     bindPostfixUnaryExpressionFlow(node);
31231                     break;
31232                 case 209 /* BinaryExpression */:
31233                     bindBinaryExpressionFlow(node);
31234                     break;
31235                 case 203 /* DeleteExpression */:
31236                     bindDeleteExpressionFlow(node);
31237                     break;
31238                 case 210 /* ConditionalExpression */:
31239                     bindConditionalExpressionFlow(node);
31240                     break;
31241                 case 242 /* VariableDeclaration */:
31242                     bindVariableDeclarationFlow(node);
31243                     break;
31244                 case 194 /* PropertyAccessExpression */:
31245                 case 195 /* ElementAccessExpression */:
31246                     bindAccessExpressionFlow(node);
31247                     break;
31248                 case 196 /* CallExpression */:
31249                     bindCallExpressionFlow(node);
31250                     break;
31251                 case 218 /* NonNullExpression */:
31252                     bindNonNullExpressionFlow(node);
31253                     break;
31254                 case 322 /* JSDocTypedefTag */:
31255                 case 315 /* JSDocCallbackTag */:
31256                 case 316 /* JSDocEnumTag */:
31257                     bindJSDocTypeAlias(node);
31258                     break;
31259                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
31260                 case 290 /* SourceFile */: {
31261                     bindEachFunctionsFirst(node.statements);
31262                     bind(node.endOfFileToken);
31263                     break;
31264                 }
31265                 case 223 /* Block */:
31266                 case 250 /* ModuleBlock */:
31267                     bindEachFunctionsFirst(node.statements);
31268                     break;
31269                 default:
31270                     bindEachChild(node);
31271                     break;
31272             }
31273             bindJSDoc(node);
31274         }
31275         function isNarrowingExpression(expr) {
31276             switch (expr.kind) {
31277                 case 75 /* Identifier */:
31278                 case 104 /* ThisKeyword */:
31279                 case 194 /* PropertyAccessExpression */:
31280                 case 195 /* ElementAccessExpression */:
31281                     return containsNarrowableReference(expr);
31282                 case 196 /* CallExpression */:
31283                     return hasNarrowableArgument(expr);
31284                 case 200 /* ParenthesizedExpression */:
31285                     return isNarrowingExpression(expr.expression);
31286                 case 209 /* BinaryExpression */:
31287                     return isNarrowingBinaryExpression(expr);
31288                 case 207 /* PrefixUnaryExpression */:
31289                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
31290                 case 204 /* TypeOfExpression */:
31291                     return isNarrowingExpression(expr.expression);
31292             }
31293             return false;
31294         }
31295         function isNarrowableReference(expr) {
31296             return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ ||
31297                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
31298                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
31299         }
31300         function containsNarrowableReference(expr) {
31301             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
31302         }
31303         function hasNarrowableArgument(expr) {
31304             if (expr.arguments) {
31305                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
31306                     var argument = _a[_i];
31307                     if (containsNarrowableReference(argument)) {
31308                         return true;
31309                     }
31310                 }
31311             }
31312             if (expr.expression.kind === 194 /* PropertyAccessExpression */ &&
31313                 containsNarrowableReference(expr.expression.expression)) {
31314                 return true;
31315             }
31316             return false;
31317         }
31318         function isNarrowingTypeofOperands(expr1, expr2) {
31319             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
31320         }
31321         function isNarrowableInOperands(left, right) {
31322             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
31323         }
31324         function isNarrowingBinaryExpression(expr) {
31325             switch (expr.operatorToken.kind) {
31326                 case 62 /* EqualsToken */:
31327                     return containsNarrowableReference(expr.left);
31328                 case 34 /* EqualsEqualsToken */:
31329                 case 35 /* ExclamationEqualsToken */:
31330                 case 36 /* EqualsEqualsEqualsToken */:
31331                 case 37 /* ExclamationEqualsEqualsToken */:
31332                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
31333                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
31334                 case 98 /* InstanceOfKeyword */:
31335                     return isNarrowableOperand(expr.left);
31336                 case 97 /* InKeyword */:
31337                     return isNarrowableInOperands(expr.left, expr.right);
31338                 case 27 /* CommaToken */:
31339                     return isNarrowingExpression(expr.right);
31340             }
31341             return false;
31342         }
31343         function isNarrowableOperand(expr) {
31344             switch (expr.kind) {
31345                 case 200 /* ParenthesizedExpression */:
31346                     return isNarrowableOperand(expr.expression);
31347                 case 209 /* BinaryExpression */:
31348                     switch (expr.operatorToken.kind) {
31349                         case 62 /* EqualsToken */:
31350                             return isNarrowableOperand(expr.left);
31351                         case 27 /* CommaToken */:
31352                             return isNarrowableOperand(expr.right);
31353                     }
31354             }
31355             return containsNarrowableReference(expr);
31356         }
31357         function createBranchLabel() {
31358             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
31359         }
31360         function createLoopLabel() {
31361             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
31362         }
31363         function createReduceLabel(target, antecedents, antecedent) {
31364             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
31365         }
31366         function setFlowNodeReferenced(flow) {
31367             // On first reference we set the Referenced flag, thereafter we set the Shared flag
31368             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
31369         }
31370         function addAntecedent(label, antecedent) {
31371             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
31372                 (label.antecedents || (label.antecedents = [])).push(antecedent);
31373                 setFlowNodeReferenced(antecedent);
31374             }
31375         }
31376         function createFlowCondition(flags, antecedent, expression) {
31377             if (antecedent.flags & 1 /* Unreachable */) {
31378                 return antecedent;
31379             }
31380             if (!expression) {
31381                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
31382             }
31383             if ((expression.kind === 106 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
31384                 expression.kind === 91 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
31385                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
31386                 return unreachableFlow;
31387             }
31388             if (!isNarrowingExpression(expression)) {
31389                 return antecedent;
31390             }
31391             setFlowNodeReferenced(antecedent);
31392             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
31393         }
31394         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
31395             setFlowNodeReferenced(antecedent);
31396             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
31397         }
31398         function createFlowMutation(flags, antecedent, node) {
31399             setFlowNodeReferenced(antecedent);
31400             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
31401             if (currentExceptionTarget) {
31402                 addAntecedent(currentExceptionTarget, result);
31403             }
31404             return result;
31405         }
31406         function createFlowCall(antecedent, node) {
31407             setFlowNodeReferenced(antecedent);
31408             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
31409         }
31410         function finishFlowLabel(flow) {
31411             var antecedents = flow.antecedents;
31412             if (!antecedents) {
31413                 return unreachableFlow;
31414             }
31415             if (antecedents.length === 1) {
31416                 return antecedents[0];
31417             }
31418             return flow;
31419         }
31420         function isStatementCondition(node) {
31421             var parent = node.parent;
31422             switch (parent.kind) {
31423                 case 227 /* IfStatement */:
31424                 case 229 /* WhileStatement */:
31425                 case 228 /* DoStatement */:
31426                     return parent.expression === node;
31427                 case 230 /* ForStatement */:
31428                 case 210 /* ConditionalExpression */:
31429                     return parent.condition === node;
31430             }
31431             return false;
31432         }
31433         function isLogicalExpression(node) {
31434             while (true) {
31435                 if (node.kind === 200 /* ParenthesizedExpression */) {
31436                     node = node.expression;
31437                 }
31438                 else if (node.kind === 207 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
31439                     node = node.operand;
31440                 }
31441                 else {
31442                     return node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
31443                         node.operatorToken.kind === 56 /* BarBarToken */ ||
31444                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
31445                 }
31446             }
31447         }
31448         function isTopLevelLogicalExpression(node) {
31449             while (ts.isParenthesizedExpression(node.parent) ||
31450                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
31451                 node = node.parent;
31452             }
31453             return !isStatementCondition(node) &&
31454                 !isLogicalExpression(node.parent) &&
31455                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
31456         }
31457         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
31458             var savedTrueTarget = currentTrueTarget;
31459             var savedFalseTarget = currentFalseTarget;
31460             currentTrueTarget = trueTarget;
31461             currentFalseTarget = falseTarget;
31462             action(value);
31463             currentTrueTarget = savedTrueTarget;
31464             currentFalseTarget = savedFalseTarget;
31465         }
31466         function bindCondition(node, trueTarget, falseTarget) {
31467             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
31468             if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
31469                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
31470                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
31471             }
31472         }
31473         function bindIterativeStatement(node, breakTarget, continueTarget) {
31474             var saveBreakTarget = currentBreakTarget;
31475             var saveContinueTarget = currentContinueTarget;
31476             currentBreakTarget = breakTarget;
31477             currentContinueTarget = continueTarget;
31478             bind(node);
31479             currentBreakTarget = saveBreakTarget;
31480             currentContinueTarget = saveContinueTarget;
31481         }
31482         function setContinueTarget(node, target) {
31483             var label = activeLabelList;
31484             while (label && node.parent.kind === 238 /* LabeledStatement */) {
31485                 label.continueTarget = target;
31486                 label = label.next;
31487                 node = node.parent;
31488             }
31489             return target;
31490         }
31491         function bindWhileStatement(node) {
31492             var preWhileLabel = setContinueTarget(node, createLoopLabel());
31493             var preBodyLabel = createBranchLabel();
31494             var postWhileLabel = createBranchLabel();
31495             addAntecedent(preWhileLabel, currentFlow);
31496             currentFlow = preWhileLabel;
31497             bindCondition(node.expression, preBodyLabel, postWhileLabel);
31498             currentFlow = finishFlowLabel(preBodyLabel);
31499             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
31500             addAntecedent(preWhileLabel, currentFlow);
31501             currentFlow = finishFlowLabel(postWhileLabel);
31502         }
31503         function bindDoStatement(node) {
31504             var preDoLabel = createLoopLabel();
31505             var preConditionLabel = setContinueTarget(node, createBranchLabel());
31506             var postDoLabel = createBranchLabel();
31507             addAntecedent(preDoLabel, currentFlow);
31508             currentFlow = preDoLabel;
31509             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
31510             addAntecedent(preConditionLabel, currentFlow);
31511             currentFlow = finishFlowLabel(preConditionLabel);
31512             bindCondition(node.expression, preDoLabel, postDoLabel);
31513             currentFlow = finishFlowLabel(postDoLabel);
31514         }
31515         function bindForStatement(node) {
31516             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31517             var preBodyLabel = createBranchLabel();
31518             var postLoopLabel = createBranchLabel();
31519             bind(node.initializer);
31520             addAntecedent(preLoopLabel, currentFlow);
31521             currentFlow = preLoopLabel;
31522             bindCondition(node.condition, preBodyLabel, postLoopLabel);
31523             currentFlow = finishFlowLabel(preBodyLabel);
31524             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31525             bind(node.incrementor);
31526             addAntecedent(preLoopLabel, currentFlow);
31527             currentFlow = finishFlowLabel(postLoopLabel);
31528         }
31529         function bindForInOrForOfStatement(node) {
31530             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31531             var postLoopLabel = createBranchLabel();
31532             bind(node.expression);
31533             addAntecedent(preLoopLabel, currentFlow);
31534             currentFlow = preLoopLabel;
31535             if (node.kind === 232 /* ForOfStatement */) {
31536                 bind(node.awaitModifier);
31537             }
31538             addAntecedent(postLoopLabel, currentFlow);
31539             bind(node.initializer);
31540             if (node.initializer.kind !== 243 /* VariableDeclarationList */) {
31541                 bindAssignmentTargetFlow(node.initializer);
31542             }
31543             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31544             addAntecedent(preLoopLabel, currentFlow);
31545             currentFlow = finishFlowLabel(postLoopLabel);
31546         }
31547         function bindIfStatement(node) {
31548             var thenLabel = createBranchLabel();
31549             var elseLabel = createBranchLabel();
31550             var postIfLabel = createBranchLabel();
31551             bindCondition(node.expression, thenLabel, elseLabel);
31552             currentFlow = finishFlowLabel(thenLabel);
31553             bind(node.thenStatement);
31554             addAntecedent(postIfLabel, currentFlow);
31555             currentFlow = finishFlowLabel(elseLabel);
31556             bind(node.elseStatement);
31557             addAntecedent(postIfLabel, currentFlow);
31558             currentFlow = finishFlowLabel(postIfLabel);
31559         }
31560         function bindReturnOrThrow(node) {
31561             bind(node.expression);
31562             if (node.kind === 235 /* ReturnStatement */) {
31563                 hasExplicitReturn = true;
31564                 if (currentReturnTarget) {
31565                     addAntecedent(currentReturnTarget, currentFlow);
31566                 }
31567             }
31568             currentFlow = unreachableFlow;
31569         }
31570         function findActiveLabel(name) {
31571             for (var label = activeLabelList; label; label = label.next) {
31572                 if (label.name === name) {
31573                     return label;
31574                 }
31575             }
31576             return undefined;
31577         }
31578         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
31579             var flowLabel = node.kind === 234 /* BreakStatement */ ? breakTarget : continueTarget;
31580             if (flowLabel) {
31581                 addAntecedent(flowLabel, currentFlow);
31582                 currentFlow = unreachableFlow;
31583             }
31584         }
31585         function bindBreakOrContinueStatement(node) {
31586             bind(node.label);
31587             if (node.label) {
31588                 var activeLabel = findActiveLabel(node.label.escapedText);
31589                 if (activeLabel) {
31590                     activeLabel.referenced = true;
31591                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
31592                 }
31593             }
31594             else {
31595                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
31596             }
31597         }
31598         function bindTryStatement(node) {
31599             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
31600             // to track code that causes mutations (because only mutations widen the possible control flow type of
31601             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
31602             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
31603             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
31604             // represent exceptions that occur before any mutations.
31605             var saveReturnTarget = currentReturnTarget;
31606             var saveExceptionTarget = currentExceptionTarget;
31607             var normalExitLabel = createBranchLabel();
31608             var returnLabel = createBranchLabel();
31609             var exceptionLabel = createBranchLabel();
31610             if (node.finallyBlock) {
31611                 currentReturnTarget = returnLabel;
31612             }
31613             addAntecedent(exceptionLabel, currentFlow);
31614             currentExceptionTarget = exceptionLabel;
31615             bind(node.tryBlock);
31616             addAntecedent(normalExitLabel, currentFlow);
31617             if (node.catchClause) {
31618                 // Start of catch clause is the target of exceptions from try block.
31619                 currentFlow = finishFlowLabel(exceptionLabel);
31620                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
31621                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
31622                 // acts like a second try block.
31623                 exceptionLabel = createBranchLabel();
31624                 addAntecedent(exceptionLabel, currentFlow);
31625                 currentExceptionTarget = exceptionLabel;
31626                 bind(node.catchClause);
31627                 addAntecedent(normalExitLabel, currentFlow);
31628             }
31629             currentReturnTarget = saveReturnTarget;
31630             currentExceptionTarget = saveExceptionTarget;
31631             if (node.finallyBlock) {
31632                 // Possible ways control can reach the finally block:
31633                 // 1) Normal completion of try block of a try-finally or try-catch-finally
31634                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
31635                 // 3) Return in try or catch block of a try-finally or try-catch-finally
31636                 // 4) Exception in try block of a try-finally
31637                 // 5) Exception in catch block of a try-catch-finally
31638                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
31639                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
31640                 // the finally block, we only want to consider the first two (if we're past a finally block then it
31641                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
31642                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
31643                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
31644                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
31645                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
31646                 var finallyLabel = createBranchLabel();
31647                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
31648                 currentFlow = finallyLabel;
31649                 bind(node.finallyBlock);
31650                 if (currentFlow.flags & 1 /* Unreachable */) {
31651                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
31652                     currentFlow = unreachableFlow;
31653                 }
31654                 else {
31655                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
31656                     // flow that goes back through the finally block and back through only the return statements.
31657                     if (currentReturnTarget && returnLabel.antecedents) {
31658                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
31659                     }
31660                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
31661                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
31662                     // result in an unreachable current control flow.
31663                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
31664                 }
31665             }
31666             else {
31667                 currentFlow = finishFlowLabel(normalExitLabel);
31668             }
31669         }
31670         function bindSwitchStatement(node) {
31671             var postSwitchLabel = createBranchLabel();
31672             bind(node.expression);
31673             var saveBreakTarget = currentBreakTarget;
31674             var savePreSwitchCaseFlow = preSwitchCaseFlow;
31675             currentBreakTarget = postSwitchLabel;
31676             preSwitchCaseFlow = currentFlow;
31677             bind(node.caseBlock);
31678             addAntecedent(postSwitchLabel, currentFlow);
31679             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 278 /* DefaultClause */; });
31680             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
31681             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
31682             // this property in control flow analysis, it's there only for backwards compatibility.
31683             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
31684             if (!hasDefault) {
31685                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
31686             }
31687             currentBreakTarget = saveBreakTarget;
31688             preSwitchCaseFlow = savePreSwitchCaseFlow;
31689             currentFlow = finishFlowLabel(postSwitchLabel);
31690         }
31691         function bindCaseBlock(node) {
31692             var savedSubtreeTransformFlags = subtreeTransformFlags;
31693             subtreeTransformFlags = 0;
31694             var clauses = node.clauses;
31695             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
31696             var fallthroughFlow = unreachableFlow;
31697             for (var i = 0; i < clauses.length; i++) {
31698                 var clauseStart = i;
31699                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
31700                     bind(clauses[i]);
31701                     i++;
31702                 }
31703                 var preCaseLabel = createBranchLabel();
31704                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
31705                 addAntecedent(preCaseLabel, fallthroughFlow);
31706                 currentFlow = finishFlowLabel(preCaseLabel);
31707                 var clause = clauses[i];
31708                 bind(clause);
31709                 fallthroughFlow = currentFlow;
31710                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
31711                     clause.fallthroughFlowNode = currentFlow;
31712                 }
31713             }
31714             clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
31715             subtreeTransformFlags |= savedSubtreeTransformFlags;
31716         }
31717         function bindCaseClause(node) {
31718             var saveCurrentFlow = currentFlow;
31719             currentFlow = preSwitchCaseFlow;
31720             bind(node.expression);
31721             currentFlow = saveCurrentFlow;
31722             bindEach(node.statements);
31723         }
31724         function bindExpressionStatement(node) {
31725             bind(node.expression);
31726             // A top level call expression with a dotted function name and at least one argument
31727             // is potentially an assertion and is therefore included in the control flow.
31728             if (node.expression.kind === 196 /* CallExpression */) {
31729                 var call = node.expression;
31730                 if (ts.isDottedName(call.expression)) {
31731                     currentFlow = createFlowCall(currentFlow, call);
31732                 }
31733             }
31734         }
31735         function bindLabeledStatement(node) {
31736             var postStatementLabel = createBranchLabel();
31737             activeLabelList = {
31738                 next: activeLabelList,
31739                 name: node.label.escapedText,
31740                 breakTarget: postStatementLabel,
31741                 continueTarget: undefined,
31742                 referenced: false
31743             };
31744             bind(node.label);
31745             bind(node.statement);
31746             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
31747                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
31748             }
31749             activeLabelList = activeLabelList.next;
31750             addAntecedent(postStatementLabel, currentFlow);
31751             currentFlow = finishFlowLabel(postStatementLabel);
31752         }
31753         function bindDestructuringTargetFlow(node) {
31754             if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
31755                 bindAssignmentTargetFlow(node.left);
31756             }
31757             else {
31758                 bindAssignmentTargetFlow(node);
31759             }
31760         }
31761         function bindAssignmentTargetFlow(node) {
31762             if (isNarrowableReference(node)) {
31763                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31764             }
31765             else if (node.kind === 192 /* ArrayLiteralExpression */) {
31766                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
31767                     var e = _a[_i];
31768                     if (e.kind === 213 /* SpreadElement */) {
31769                         bindAssignmentTargetFlow(e.expression);
31770                     }
31771                     else {
31772                         bindDestructuringTargetFlow(e);
31773                     }
31774                 }
31775             }
31776             else if (node.kind === 193 /* ObjectLiteralExpression */) {
31777                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
31778                     var p = _c[_b];
31779                     if (p.kind === 281 /* PropertyAssignment */) {
31780                         bindDestructuringTargetFlow(p.initializer);
31781                     }
31782                     else if (p.kind === 282 /* ShorthandPropertyAssignment */) {
31783                         bindAssignmentTargetFlow(p.name);
31784                     }
31785                     else if (p.kind === 283 /* SpreadAssignment */) {
31786                         bindAssignmentTargetFlow(p.expression);
31787                     }
31788                 }
31789             }
31790         }
31791         function bindLogicalExpression(node, trueTarget, falseTarget) {
31792             var preRightLabel = createBranchLabel();
31793             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
31794                 bindCondition(node.left, preRightLabel, falseTarget);
31795             }
31796             else {
31797                 bindCondition(node.left, trueTarget, preRightLabel);
31798             }
31799             currentFlow = finishFlowLabel(preRightLabel);
31800             bind(node.operatorToken);
31801             bindCondition(node.right, trueTarget, falseTarget);
31802         }
31803         function bindPrefixUnaryExpressionFlow(node) {
31804             if (node.operator === 53 /* ExclamationToken */) {
31805                 var saveTrueTarget = currentTrueTarget;
31806                 currentTrueTarget = currentFalseTarget;
31807                 currentFalseTarget = saveTrueTarget;
31808                 bindEachChild(node);
31809                 currentFalseTarget = currentTrueTarget;
31810                 currentTrueTarget = saveTrueTarget;
31811             }
31812             else {
31813                 bindEachChild(node);
31814                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31815                     bindAssignmentTargetFlow(node.operand);
31816                 }
31817             }
31818         }
31819         function bindPostfixUnaryExpressionFlow(node) {
31820             bindEachChild(node);
31821             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31822                 bindAssignmentTargetFlow(node.operand);
31823             }
31824         }
31825         var BindBinaryExpressionFlowState;
31826         (function (BindBinaryExpressionFlowState) {
31827             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
31828             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
31829             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
31830             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
31831             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
31832         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
31833         function bindBinaryExpressionFlow(node) {
31834             var workStacks = {
31835                 expr: [node],
31836                 state: [1 /* MaybeBindLeft */],
31837                 inStrictMode: [undefined],
31838                 parent: [undefined],
31839                 subtreeFlags: [undefined]
31840             };
31841             var stackIndex = 0;
31842             while (stackIndex >= 0) {
31843                 node = workStacks.expr[stackIndex];
31844                 switch (workStacks.state[stackIndex]) {
31845                     case 0 /* BindThenBindChildren */: {
31846                         // This state is used only when recuring, to emulate the work that `bind` does before
31847                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
31848                         node.parent = parent;
31849                         var saveInStrictMode = inStrictMode;
31850                         bindWorker(node);
31851                         var saveParent = parent;
31852                         parent = node;
31853                         var subtreeFlagsState = void 0;
31854                         // While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
31855                         // and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
31856                         if (skipTransformFlagAggregation) {
31857                             // do nothing extra
31858                         }
31859                         else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31860                             skipTransformFlagAggregation = true;
31861                             subtreeFlagsState = -1;
31862                         }
31863                         else {
31864                             var savedSubtreeTransformFlags = subtreeTransformFlags;
31865                             subtreeTransformFlags = 0;
31866                             subtreeFlagsState = savedSubtreeTransformFlags;
31867                         }
31868                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent, subtreeFlagsState);
31869                         break;
31870                     }
31871                     case 1 /* MaybeBindLeft */: {
31872                         var operator = node.operatorToken.kind;
31873                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
31874                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
31875                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
31876                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
31877                             if (isTopLevelLogicalExpression(node)) {
31878                                 var postExpressionLabel = createBranchLabel();
31879                                 bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
31880                                 currentFlow = finishFlowLabel(postExpressionLabel);
31881                             }
31882                             else {
31883                                 bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
31884                             }
31885                             completeNode();
31886                         }
31887                         else {
31888                             advanceState(2 /* BindToken */);
31889                             maybeBind(node.left);
31890                         }
31891                         break;
31892                     }
31893                     case 2 /* BindToken */: {
31894                         advanceState(3 /* BindRight */);
31895                         maybeBind(node.operatorToken);
31896                         break;
31897                     }
31898                     case 3 /* BindRight */: {
31899                         advanceState(4 /* FinishBind */);
31900                         maybeBind(node.right);
31901                         break;
31902                     }
31903                     case 4 /* FinishBind */: {
31904                         var operator = node.operatorToken.kind;
31905                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
31906                             bindAssignmentTargetFlow(node.left);
31907                             if (operator === 62 /* EqualsToken */ && node.left.kind === 195 /* ElementAccessExpression */) {
31908                                 var elementAccess = node.left;
31909                                 if (isNarrowableOperand(elementAccess.expression)) {
31910                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
31911                                 }
31912                             }
31913                         }
31914                         completeNode();
31915                         break;
31916                     }
31917                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
31918                 }
31919             }
31920             /**
31921              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
31922              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
31923              */
31924             function advanceState(state, isInStrictMode, parent, subtreeFlags) {
31925                 workStacks.state[stackIndex] = state;
31926                 if (isInStrictMode !== undefined) {
31927                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
31928                 }
31929                 if (parent !== undefined) {
31930                     workStacks.parent[stackIndex] = parent;
31931                 }
31932                 if (subtreeFlags !== undefined) {
31933                     workStacks.subtreeFlags[stackIndex] = subtreeFlags;
31934                 }
31935             }
31936             function completeNode() {
31937                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
31938                     if (workStacks.subtreeFlags[stackIndex] === -1) {
31939                         skipTransformFlagAggregation = false;
31940                         subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31941                     }
31942                     else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
31943                         subtreeTransformFlags = workStacks.subtreeFlags[stackIndex] | computeTransformFlagsForNode(node, subtreeTransformFlags);
31944                     }
31945                     inStrictMode = workStacks.inStrictMode[stackIndex];
31946                     parent = workStacks.parent[stackIndex];
31947                 }
31948                 stackIndex--;
31949             }
31950             /**
31951              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
31952              */
31953             function maybeBind(node) {
31954                 if (node && ts.isBinaryExpression(node)) {
31955                     stackIndex++;
31956                     workStacks.expr[stackIndex] = node;
31957                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
31958                     workStacks.inStrictMode[stackIndex] = undefined;
31959                     workStacks.parent[stackIndex] = undefined;
31960                     workStacks.subtreeFlags[stackIndex] = undefined;
31961                 }
31962                 else {
31963                     bind(node);
31964                 }
31965             }
31966         }
31967         function bindDeleteExpressionFlow(node) {
31968             bindEachChild(node);
31969             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
31970                 bindAssignmentTargetFlow(node.expression);
31971             }
31972         }
31973         function bindConditionalExpressionFlow(node) {
31974             var trueLabel = createBranchLabel();
31975             var falseLabel = createBranchLabel();
31976             var postExpressionLabel = createBranchLabel();
31977             bindCondition(node.condition, trueLabel, falseLabel);
31978             currentFlow = finishFlowLabel(trueLabel);
31979             bind(node.questionToken);
31980             bind(node.whenTrue);
31981             addAntecedent(postExpressionLabel, currentFlow);
31982             currentFlow = finishFlowLabel(falseLabel);
31983             bind(node.colonToken);
31984             bind(node.whenFalse);
31985             addAntecedent(postExpressionLabel, currentFlow);
31986             currentFlow = finishFlowLabel(postExpressionLabel);
31987         }
31988         function bindInitializedVariableFlow(node) {
31989             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
31990             if (ts.isBindingPattern(name)) {
31991                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
31992                     var child = _a[_i];
31993                     bindInitializedVariableFlow(child);
31994                 }
31995             }
31996             else {
31997                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31998             }
31999         }
32000         function bindVariableDeclarationFlow(node) {
32001             bindEachChild(node);
32002             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
32003                 bindInitializedVariableFlow(node);
32004             }
32005         }
32006         function bindJSDocTypeAlias(node) {
32007             node.tagName.parent = node;
32008             if (node.kind !== 316 /* JSDocEnumTag */ && node.fullName) {
32009                 setParentPointers(node, node.fullName);
32010             }
32011         }
32012         function bindJSDocClassTag(node) {
32013             bindEachChild(node);
32014             var host = ts.getHostSignatureFromJSDoc(node);
32015             if (host && host.kind !== 161 /* MethodDeclaration */) {
32016                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
32017             }
32018         }
32019         function bindOptionalExpression(node, trueTarget, falseTarget) {
32020             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
32021             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
32022                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32023                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32024             }
32025         }
32026         function bindOptionalChainRest(node) {
32027             switch (node.kind) {
32028                 case 194 /* PropertyAccessExpression */:
32029                     bind(node.questionDotToken);
32030                     bind(node.name);
32031                     break;
32032                 case 195 /* ElementAccessExpression */:
32033                     bind(node.questionDotToken);
32034                     bind(node.argumentExpression);
32035                     break;
32036                 case 196 /* CallExpression */:
32037                     bind(node.questionDotToken);
32038                     bindEach(node.typeArguments);
32039                     bindEach(node.arguments);
32040                     break;
32041             }
32042         }
32043         function bindOptionalChain(node, trueTarget, falseTarget) {
32044             // For an optional chain, we emulate the behavior of a logical expression:
32045             //
32046             // a?.b         -> a && a.b
32047             // a?.b.c       -> a && a.b.c
32048             // a?.b?.c      -> a && a.b && a.b.c
32049             // a?.[x = 1]   -> a && a[x = 1]
32050             //
32051             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
32052             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
32053             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
32054             // chain node. We then treat the entire node as the right side of the expression.
32055             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
32056             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
32057             if (preChainLabel) {
32058                 currentFlow = finishFlowLabel(preChainLabel);
32059             }
32060             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
32061             if (ts.isOutermostOptionalChain(node)) {
32062                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32063                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32064             }
32065         }
32066         function bindOptionalChainFlow(node) {
32067             if (isTopLevelLogicalExpression(node)) {
32068                 var postExpressionLabel = createBranchLabel();
32069                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
32070                 currentFlow = finishFlowLabel(postExpressionLabel);
32071             }
32072             else {
32073                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
32074             }
32075         }
32076         function bindNonNullExpressionFlow(node) {
32077             if (ts.isOptionalChain(node)) {
32078                 bindOptionalChainFlow(node);
32079             }
32080             else {
32081                 bindEachChild(node);
32082             }
32083         }
32084         function bindAccessExpressionFlow(node) {
32085             if (ts.isOptionalChain(node)) {
32086                 bindOptionalChainFlow(node);
32087             }
32088             else {
32089                 bindEachChild(node);
32090             }
32091         }
32092         function bindCallExpressionFlow(node) {
32093             if (ts.isOptionalChain(node)) {
32094                 bindOptionalChainFlow(node);
32095             }
32096             else {
32097                 // If the target of the call expression is a function expression or arrow function we have
32098                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
32099                 // the current control flow (which includes evaluation of the IIFE arguments).
32100                 var expr = ts.skipParentheses(node.expression);
32101                 if (expr.kind === 201 /* FunctionExpression */ || expr.kind === 202 /* ArrowFunction */) {
32102                     bindEach(node.typeArguments);
32103                     bindEach(node.arguments);
32104                     bind(node.expression);
32105                 }
32106                 else {
32107                     bindEachChild(node);
32108                 }
32109             }
32110             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
32111                 var propertyAccess = node.expression;
32112                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
32113                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
32114                 }
32115             }
32116         }
32117         function getContainerFlags(node) {
32118             switch (node.kind) {
32119                 case 214 /* ClassExpression */:
32120                 case 245 /* ClassDeclaration */:
32121                 case 248 /* EnumDeclaration */:
32122                 case 193 /* ObjectLiteralExpression */:
32123                 case 173 /* TypeLiteral */:
32124                 case 304 /* JSDocTypeLiteral */:
32125                 case 274 /* JsxAttributes */:
32126                     return 1 /* IsContainer */;
32127                 case 246 /* InterfaceDeclaration */:
32128                     return 1 /* IsContainer */ | 64 /* IsInterface */;
32129                 case 249 /* ModuleDeclaration */:
32130                 case 247 /* TypeAliasDeclaration */:
32131                 case 186 /* MappedType */:
32132                     return 1 /* IsContainer */ | 32 /* HasLocals */;
32133                 case 290 /* SourceFile */:
32134                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
32135                 case 161 /* MethodDeclaration */:
32136                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
32137                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
32138                     }
32139                 // falls through
32140                 case 162 /* Constructor */:
32141                 case 244 /* FunctionDeclaration */:
32142                 case 160 /* MethodSignature */:
32143                 case 163 /* GetAccessor */:
32144                 case 164 /* SetAccessor */:
32145                 case 165 /* CallSignature */:
32146                 case 305 /* JSDocSignature */:
32147                 case 300 /* JSDocFunctionType */:
32148                 case 170 /* FunctionType */:
32149                 case 166 /* ConstructSignature */:
32150                 case 167 /* IndexSignature */:
32151                 case 171 /* ConstructorType */:
32152                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
32153                 case 201 /* FunctionExpression */:
32154                 case 202 /* ArrowFunction */:
32155                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
32156                 case 250 /* ModuleBlock */:
32157                     return 4 /* IsControlFlowContainer */;
32158                 case 159 /* PropertyDeclaration */:
32159                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
32160                 case 280 /* CatchClause */:
32161                 case 230 /* ForStatement */:
32162                 case 231 /* ForInStatement */:
32163                 case 232 /* ForOfStatement */:
32164                 case 251 /* CaseBlock */:
32165                     return 2 /* IsBlockScopedContainer */;
32166                 case 223 /* Block */:
32167                     // do not treat blocks directly inside a function as a block-scoped-container.
32168                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
32169                     // would not appear to be a redeclaration of a block scoped local in the following
32170                     // example:
32171                     //
32172                     //      function foo() {
32173                     //          var x;
32174                     //          let x;
32175                     //      }
32176                     //
32177                     // If we placed 'var x' into the function locals and 'let x' into the locals of
32178                     // the block, then there would be no collision.
32179                     //
32180                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
32181                     // and 'let x' go into the Function-container's locals, and we do get a collision
32182                     // conflict.
32183                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
32184             }
32185             return 0 /* None */;
32186         }
32187         function addToContainerChain(next) {
32188             if (lastContainer) {
32189                 lastContainer.nextContainer = next;
32190             }
32191             lastContainer = next;
32192         }
32193         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
32194             switch (container.kind) {
32195                 // Modules, source files, and classes need specialized handling for how their
32196                 // members are declared (for example, a member of a class will go into a specific
32197                 // symbol table depending on if it is static or not). We defer to specialized
32198                 // handlers to take care of declaring these child members.
32199                 case 249 /* ModuleDeclaration */:
32200                     return declareModuleMember(node, symbolFlags, symbolExcludes);
32201                 case 290 /* SourceFile */:
32202                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
32203                 case 214 /* ClassExpression */:
32204                 case 245 /* ClassDeclaration */:
32205                     return declareClassMember(node, symbolFlags, symbolExcludes);
32206                 case 248 /* EnumDeclaration */:
32207                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
32208                 case 173 /* TypeLiteral */:
32209                 case 304 /* JSDocTypeLiteral */:
32210                 case 193 /* ObjectLiteralExpression */:
32211                 case 246 /* InterfaceDeclaration */:
32212                 case 274 /* JsxAttributes */:
32213                     // Interface/Object-types always have their children added to the 'members' of
32214                     // their container. They are only accessible through an instance of their
32215                     // container, and are never in scope otherwise (even inside the body of the
32216                     // object / type / interface declaring them). An exception is type parameters,
32217                     // which are in scope without qualification (similar to 'locals').
32218                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32219                 case 170 /* FunctionType */:
32220                 case 171 /* ConstructorType */:
32221                 case 165 /* CallSignature */:
32222                 case 166 /* ConstructSignature */:
32223                 case 305 /* JSDocSignature */:
32224                 case 167 /* IndexSignature */:
32225                 case 161 /* MethodDeclaration */:
32226                 case 160 /* MethodSignature */:
32227                 case 162 /* Constructor */:
32228                 case 163 /* GetAccessor */:
32229                 case 164 /* SetAccessor */:
32230                 case 244 /* FunctionDeclaration */:
32231                 case 201 /* FunctionExpression */:
32232                 case 202 /* ArrowFunction */:
32233                 case 300 /* JSDocFunctionType */:
32234                 case 322 /* JSDocTypedefTag */:
32235                 case 315 /* JSDocCallbackTag */:
32236                 case 247 /* TypeAliasDeclaration */:
32237                 case 186 /* MappedType */:
32238                     // All the children of these container types are never visible through another
32239                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
32240                     // they're only accessed 'lexically' (i.e. from code that exists underneath
32241                     // their container in the tree). To accomplish this, we simply add their declared
32242                     // symbol to the 'locals' of the container.  These symbols can then be found as
32243                     // the type checker walks up the containers, checking them for matching names.
32244                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32245             }
32246         }
32247         function declareClassMember(node, symbolFlags, symbolExcludes) {
32248             return ts.hasModifier(node, 32 /* Static */)
32249                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
32250                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32251         }
32252         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
32253             return ts.isExternalModule(file)
32254                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
32255                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32256         }
32257         function hasExportDeclarations(node) {
32258             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
32259             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
32260         }
32261         function setExportContextFlag(node) {
32262             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
32263             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
32264             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
32265                 node.flags |= 64 /* ExportContext */;
32266             }
32267             else {
32268                 node.flags &= ~64 /* ExportContext */;
32269             }
32270         }
32271         function bindModuleDeclaration(node) {
32272             setExportContextFlag(node);
32273             if (ts.isAmbientModule(node)) {
32274                 if (ts.hasModifier(node, 1 /* Export */)) {
32275                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
32276                 }
32277                 if (ts.isModuleAugmentationExternal(node)) {
32278                     declareModuleSymbol(node);
32279                 }
32280                 else {
32281                     var pattern = void 0;
32282                     if (node.name.kind === 10 /* StringLiteral */) {
32283                         var text = node.name.text;
32284                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
32285                             pattern = ts.tryParsePattern(text);
32286                         }
32287                         else {
32288                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
32289                         }
32290                     }
32291                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
32292                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
32293                 }
32294             }
32295             else {
32296                 var state = declareModuleSymbol(node);
32297                 if (state !== 0 /* NonInstantiated */) {
32298                     var symbol = node.symbol;
32299                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
32300                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
32301                         // Current must be `const enum` only
32302                         && state === 2 /* ConstEnumOnly */
32303                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
32304                         && symbol.constEnumOnlyModule !== false;
32305                 }
32306             }
32307         }
32308         function declareModuleSymbol(node) {
32309             var state = getModuleInstanceState(node);
32310             var instantiated = state !== 0 /* NonInstantiated */;
32311             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
32312             return state;
32313         }
32314         function bindFunctionOrConstructorType(node) {
32315             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
32316             // to the one we would get for: { <...>(...): T }
32317             //
32318             // We do that by making an anonymous type literal symbol, and then setting the function
32319             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
32320             // from an actual type literal symbol you would have gotten had you used the long form.
32321             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
32322             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
32323             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
32324             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
32325             typeLiteralSymbol.members = ts.createSymbolTable();
32326             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
32327         }
32328         function bindObjectLiteralExpression(node) {
32329             var ElementKind;
32330             (function (ElementKind) {
32331                 ElementKind[ElementKind["Property"] = 1] = "Property";
32332                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
32333             })(ElementKind || (ElementKind = {}));
32334             if (inStrictMode && !ts.isAssignmentTarget(node)) {
32335                 var seen = ts.createUnderscoreEscapedMap();
32336                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
32337                     var prop = _a[_i];
32338                     if (prop.kind === 283 /* SpreadAssignment */ || prop.name.kind !== 75 /* Identifier */) {
32339                         continue;
32340                     }
32341                     var identifier = prop.name;
32342                     // ECMA-262 11.1.5 Object Initializer
32343                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
32344                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
32345                     // IsDataDescriptor(propId.descriptor) is true.
32346                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
32347                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
32348                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
32349                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
32350                     var currentKind = prop.kind === 281 /* PropertyAssignment */ || prop.kind === 282 /* ShorthandPropertyAssignment */ || prop.kind === 161 /* MethodDeclaration */
32351                         ? 1 /* Property */
32352                         : 2 /* Accessor */;
32353                     var existingKind = seen.get(identifier.escapedText);
32354                     if (!existingKind) {
32355                         seen.set(identifier.escapedText, currentKind);
32356                         continue;
32357                     }
32358                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
32359                         var span = ts.getErrorSpanForNode(file, identifier);
32360                         file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
32361                     }
32362                 }
32363             }
32364             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
32365         }
32366         function bindJsxAttributes(node) {
32367             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
32368         }
32369         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
32370             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
32371         }
32372         function bindAnonymousDeclaration(node, symbolFlags, name) {
32373             var symbol = createSymbol(symbolFlags, name);
32374             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
32375                 symbol.parent = container.symbol;
32376             }
32377             addDeclarationToSymbol(symbol, node, symbolFlags);
32378             return symbol;
32379         }
32380         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
32381             switch (blockScopeContainer.kind) {
32382                 case 249 /* ModuleDeclaration */:
32383                     declareModuleMember(node, symbolFlags, symbolExcludes);
32384                     break;
32385                 case 290 /* SourceFile */:
32386                     if (ts.isExternalOrCommonJsModule(container)) {
32387                         declareModuleMember(node, symbolFlags, symbolExcludes);
32388                         break;
32389                     }
32390                 // falls through
32391                 default:
32392                     if (!blockScopeContainer.locals) {
32393                         blockScopeContainer.locals = ts.createSymbolTable();
32394                         addToContainerChain(blockScopeContainer);
32395                     }
32396                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32397             }
32398         }
32399         function delayedBindJSDocTypedefTag() {
32400             if (!delayedTypeAliases) {
32401                 return;
32402             }
32403             var saveContainer = container;
32404             var saveLastContainer = lastContainer;
32405             var saveBlockScopeContainer = blockScopeContainer;
32406             var saveParent = parent;
32407             var saveCurrentFlow = currentFlow;
32408             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
32409                 var typeAlias = delayedTypeAliases_1[_i];
32410                 var host = ts.getJSDocHost(typeAlias);
32411                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
32412                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
32413                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
32414                 parent = typeAlias;
32415                 bind(typeAlias.typeExpression);
32416                 var declName = ts.getNameOfDeclaration(typeAlias);
32417                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
32418                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
32419                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
32420                     if (isTopLevel) {
32421                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
32422                         var oldContainer = container;
32423                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
32424                             case 1 /* ExportsProperty */:
32425                             case 2 /* ModuleExports */:
32426                                 if (!ts.isExternalOrCommonJsModule(file)) {
32427                                     container = undefined;
32428                                 }
32429                                 else {
32430                                     container = file;
32431                                 }
32432                                 break;
32433                             case 4 /* ThisProperty */:
32434                                 container = declName.parent.expression;
32435                                 break;
32436                             case 3 /* PrototypeProperty */:
32437                                 container = declName.parent.expression.name;
32438                                 break;
32439                             case 5 /* Property */:
32440                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
32441                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
32442                                         : declName.parent.expression;
32443                                 break;
32444                             case 0 /* None */:
32445                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
32446                         }
32447                         if (container) {
32448                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32449                         }
32450                         container = oldContainer;
32451                     }
32452                 }
32453                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 75 /* Identifier */) {
32454                     parent = typeAlias.parent;
32455                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32456                 }
32457                 else {
32458                     bind(typeAlias.fullName);
32459                 }
32460             }
32461             container = saveContainer;
32462             lastContainer = saveLastContainer;
32463             blockScopeContainer = saveBlockScopeContainer;
32464             parent = saveParent;
32465             currentFlow = saveCurrentFlow;
32466         }
32467         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
32468         // check for reserved words used as identifiers in strict mode code.
32469         function checkStrictModeIdentifier(node) {
32470             if (inStrictMode &&
32471                 node.originalKeywordKind >= 113 /* FirstFutureReservedWord */ &&
32472                 node.originalKeywordKind <= 121 /* LastFutureReservedWord */ &&
32473                 !ts.isIdentifierName(node) &&
32474                 !(node.flags & 8388608 /* Ambient */) &&
32475                 !(node.flags & 4194304 /* JSDoc */)) {
32476                 // Report error only if there are no parse errors in file
32477                 if (!file.parseDiagnostics.length) {
32478                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
32479                 }
32480             }
32481         }
32482         function getStrictModeIdentifierMessage(node) {
32483             // Provide specialized messages to help the user understand why we think they're in
32484             // strict mode.
32485             if (ts.getContainingClass(node)) {
32486                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
32487             }
32488             if (file.externalModuleIndicator) {
32489                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
32490             }
32491             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
32492         }
32493         // The binder visits every node, so this is a good place to check for
32494         // the reserved private name (there is only one)
32495         function checkPrivateIdentifier(node) {
32496             if (node.escapedText === "#constructor") {
32497                 // Report error only if there are no parse errors in file
32498                 if (!file.parseDiagnostics.length) {
32499                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
32500                 }
32501             }
32502         }
32503         function checkStrictModeBinaryExpression(node) {
32504             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
32505                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32506                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
32507                 checkStrictModeEvalOrArguments(node, node.left);
32508             }
32509         }
32510         function checkStrictModeCatchClause(node) {
32511             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
32512             // Catch production is eval or arguments
32513             if (inStrictMode && node.variableDeclaration) {
32514                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
32515             }
32516         }
32517         function checkStrictModeDeleteExpression(node) {
32518             // Grammar checking
32519             if (inStrictMode && node.expression.kind === 75 /* Identifier */) {
32520                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
32521                 // UnaryExpression is a direct reference to a variable, function argument, or function name
32522                 var span = ts.getErrorSpanForNode(file, node.expression);
32523                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
32524             }
32525         }
32526         function isEvalOrArgumentsIdentifier(node) {
32527             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
32528         }
32529         function checkStrictModeEvalOrArguments(contextNode, name) {
32530             if (name && name.kind === 75 /* Identifier */) {
32531                 var identifier = name;
32532                 if (isEvalOrArgumentsIdentifier(identifier)) {
32533                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32534                     // otherwise report generic error message.
32535                     var span = ts.getErrorSpanForNode(file, name);
32536                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
32537                 }
32538             }
32539         }
32540         function getStrictModeEvalOrArgumentsMessage(node) {
32541             // Provide specialized messages to help the user understand why we think they're in
32542             // strict mode.
32543             if (ts.getContainingClass(node)) {
32544                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
32545             }
32546             if (file.externalModuleIndicator) {
32547                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
32548             }
32549             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
32550         }
32551         function checkStrictModeFunctionName(node) {
32552             if (inStrictMode) {
32553                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
32554                 checkStrictModeEvalOrArguments(node, node.name);
32555             }
32556         }
32557         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
32558             // Provide specialized messages to help the user understand why we think they're in
32559             // strict mode.
32560             if (ts.getContainingClass(node)) {
32561                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode;
32562             }
32563             if (file.externalModuleIndicator) {
32564                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
32565             }
32566             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
32567         }
32568         function checkStrictModeFunctionDeclaration(node) {
32569             if (languageVersion < 2 /* ES2015 */) {
32570                 // Report error if function is not top level function declaration
32571                 if (blockScopeContainer.kind !== 290 /* SourceFile */ &&
32572                     blockScopeContainer.kind !== 249 /* ModuleDeclaration */ &&
32573                     !ts.isFunctionLike(blockScopeContainer)) {
32574                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32575                     // otherwise report generic error message.
32576                     var errorSpan = ts.getErrorSpanForNode(file, node);
32577                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
32578                 }
32579             }
32580         }
32581         function checkStrictModeNumericLiteral(node) {
32582             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
32583                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
32584             }
32585         }
32586         function checkStrictModePostfixUnaryExpression(node) {
32587             // Grammar checking
32588             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32589             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
32590             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
32591             if (inStrictMode) {
32592                 checkStrictModeEvalOrArguments(node, node.operand);
32593             }
32594         }
32595         function checkStrictModePrefixUnaryExpression(node) {
32596             // Grammar checking
32597             if (inStrictMode) {
32598                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
32599                     checkStrictModeEvalOrArguments(node, node.operand);
32600                 }
32601             }
32602         }
32603         function checkStrictModeWithStatement(node) {
32604             // Grammar checking for withStatement
32605             if (inStrictMode) {
32606                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
32607             }
32608         }
32609         function checkStrictModeLabeledStatement(node) {
32610             // Grammar checking for labeledStatement
32611             if (inStrictMode && options.target >= 2 /* ES2015 */) {
32612                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
32613                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
32614                 }
32615             }
32616         }
32617         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
32618             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
32619             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
32620         }
32621         function errorOrSuggestionOnNode(isError, node, message) {
32622             errorOrSuggestionOnRange(isError, node, node, message);
32623         }
32624         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
32625             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
32626         }
32627         function addErrorOrSuggestionDiagnostic(isError, range, message) {
32628             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
32629             if (isError) {
32630                 file.bindDiagnostics.push(diag);
32631             }
32632             else {
32633                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
32634             }
32635         }
32636         function bind(node) {
32637             if (!node) {
32638                 return;
32639             }
32640             node.parent = parent;
32641             var saveInStrictMode = inStrictMode;
32642             // Even though in the AST the jsdoc @typedef node belongs to the current node,
32643             // its symbol might be in the same scope with the current node's symbol. Consider:
32644             //
32645             //     /** @typedef {string | number} MyType */
32646             //     function foo();
32647             //
32648             // Here the current node is "foo", which is a container, but the scope of "MyType" should
32649             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
32650             // and skip binding this tag later when binding all the other jsdoc tags.
32651             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
32652             // and then potentially add the symbol to an appropriate symbol table. Possible
32653             // destination symbol tables are:
32654             //
32655             //  1) The 'exports' table of the current container's symbol.
32656             //  2) The 'members' table of the current container's symbol.
32657             //  3) The 'locals' table of the current container.
32658             //
32659             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
32660             // (like TypeLiterals for example) will not be put in any table.
32661             bindWorker(node);
32662             // Then we recurse into the children of the node to bind them as well. For certain
32663             // symbols we do specialized work when we recurse. For example, we'll keep track of
32664             // the current 'container' node when it changes. This helps us know which symbol table
32665             // a local should go into for example. Since terminal nodes are known not to have
32666             // children, as an optimization we don't process those.
32667             if (node.kind > 152 /* LastToken */) {
32668                 var saveParent = parent;
32669                 parent = node;
32670                 var containerFlags = getContainerFlags(node);
32671                 if (containerFlags === 0 /* None */) {
32672                     bindChildren(node);
32673                 }
32674                 else {
32675                     bindContainer(node, containerFlags);
32676                 }
32677                 parent = saveParent;
32678             }
32679             else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
32680                 subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
32681                 var saveParent = parent;
32682                 if (node.kind === 1 /* EndOfFileToken */)
32683                     parent = node;
32684                 bindJSDoc(node);
32685                 parent = saveParent;
32686             }
32687             inStrictMode = saveInStrictMode;
32688         }
32689         function bindJSDoc(node) {
32690             if (ts.hasJSDocNodes(node)) {
32691                 if (ts.isInJSFile(node)) {
32692                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
32693                         var j = _a[_i];
32694                         bind(j);
32695                     }
32696                 }
32697                 else {
32698                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
32699                         var j = _c[_b];
32700                         setParentPointers(node, j);
32701                     }
32702                 }
32703             }
32704         }
32705         function updateStrictModeStatementList(statements) {
32706             if (!inStrictMode) {
32707                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
32708                     var statement = statements_2[_i];
32709                     if (!ts.isPrologueDirective(statement)) {
32710                         return;
32711                     }
32712                     if (isUseStrictPrologueDirective(statement)) {
32713                         inStrictMode = true;
32714                         return;
32715                     }
32716                 }
32717             }
32718         }
32719         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
32720         function isUseStrictPrologueDirective(node) {
32721             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
32722             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
32723             // string to contain unicode escapes (as per ES5).
32724             return nodeText === '"use strict"' || nodeText === "'use strict'";
32725         }
32726         function bindWorker(node) {
32727             switch (node.kind) {
32728                 /* Strict mode checks */
32729                 case 75 /* Identifier */:
32730                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
32731                     // because it requires all containing namespaces to be in effect, namely the
32732                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
32733                     if (node.isInJSDocNamespace) {
32734                         var parentNode = node.parent;
32735                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
32736                             parentNode = parentNode.parent;
32737                         }
32738                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32739                         break;
32740                     }
32741                 // falls through
32742                 case 104 /* ThisKeyword */:
32743                     if (currentFlow && (ts.isExpression(node) || parent.kind === 282 /* ShorthandPropertyAssignment */)) {
32744                         node.flowNode = currentFlow;
32745                     }
32746                     return checkStrictModeIdentifier(node);
32747                 case 76 /* PrivateIdentifier */:
32748                     return checkPrivateIdentifier(node);
32749                 case 194 /* PropertyAccessExpression */:
32750                 case 195 /* ElementAccessExpression */:
32751                     var expr = node;
32752                     if (currentFlow && isNarrowableReference(expr)) {
32753                         expr.flowNode = currentFlow;
32754                     }
32755                     if (ts.isSpecialPropertyDeclaration(expr)) {
32756                         bindSpecialPropertyDeclaration(expr);
32757                     }
32758                     if (ts.isInJSFile(expr) &&
32759                         file.commonJsModuleIndicator &&
32760                         ts.isModuleExportsAccessExpression(expr) &&
32761                         !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
32762                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
32763                     }
32764                     break;
32765                 case 209 /* BinaryExpression */:
32766                     var specialKind = ts.getAssignmentDeclarationKind(node);
32767                     switch (specialKind) {
32768                         case 1 /* ExportsProperty */:
32769                             bindExportsPropertyAssignment(node);
32770                             break;
32771                         case 2 /* ModuleExports */:
32772                             bindModuleExportsAssignment(node);
32773                             break;
32774                         case 3 /* PrototypeProperty */:
32775                             bindPrototypePropertyAssignment(node.left, node);
32776                             break;
32777                         case 6 /* Prototype */:
32778                             bindPrototypeAssignment(node);
32779                             break;
32780                         case 4 /* ThisProperty */:
32781                             bindThisPropertyAssignment(node);
32782                             break;
32783                         case 5 /* Property */:
32784                             bindSpecialPropertyAssignment(node);
32785                             break;
32786                         case 0 /* None */:
32787                             // Nothing to do
32788                             break;
32789                         default:
32790                             ts.Debug.fail("Unknown binary expression special property assignment kind");
32791                     }
32792                     return checkStrictModeBinaryExpression(node);
32793                 case 280 /* CatchClause */:
32794                     return checkStrictModeCatchClause(node);
32795                 case 203 /* DeleteExpression */:
32796                     return checkStrictModeDeleteExpression(node);
32797                 case 8 /* NumericLiteral */:
32798                     return checkStrictModeNumericLiteral(node);
32799                 case 208 /* PostfixUnaryExpression */:
32800                     return checkStrictModePostfixUnaryExpression(node);
32801                 case 207 /* PrefixUnaryExpression */:
32802                     return checkStrictModePrefixUnaryExpression(node);
32803                 case 236 /* WithStatement */:
32804                     return checkStrictModeWithStatement(node);
32805                 case 238 /* LabeledStatement */:
32806                     return checkStrictModeLabeledStatement(node);
32807                 case 183 /* ThisType */:
32808                     seenThisKeyword = true;
32809                     return;
32810                 case 168 /* TypePredicate */:
32811                     break; // Binding the children will handle everything
32812                 case 155 /* TypeParameter */:
32813                     return bindTypeParameter(node);
32814                 case 156 /* Parameter */:
32815                     return bindParameter(node);
32816                 case 242 /* VariableDeclaration */:
32817                     return bindVariableDeclarationOrBindingElement(node);
32818                 case 191 /* BindingElement */:
32819                     node.flowNode = currentFlow;
32820                     return bindVariableDeclarationOrBindingElement(node);
32821                 case 159 /* PropertyDeclaration */:
32822                 case 158 /* PropertySignature */:
32823                     return bindPropertyWorker(node);
32824                 case 281 /* PropertyAssignment */:
32825                 case 282 /* ShorthandPropertyAssignment */:
32826                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
32827                 case 284 /* EnumMember */:
32828                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
32829                 case 165 /* CallSignature */:
32830                 case 166 /* ConstructSignature */:
32831                 case 167 /* IndexSignature */:
32832                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
32833                 case 161 /* MethodDeclaration */:
32834                 case 160 /* MethodSignature */:
32835                     // If this is an ObjectLiteralExpression method, then it sits in the same space
32836                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
32837                     // so that it will conflict with any other object literal members with the same
32838                     // name.
32839                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
32840                 case 244 /* FunctionDeclaration */:
32841                     return bindFunctionDeclaration(node);
32842                 case 162 /* Constructor */:
32843                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
32844                 case 163 /* GetAccessor */:
32845                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
32846                 case 164 /* SetAccessor */:
32847                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
32848                 case 170 /* FunctionType */:
32849                 case 300 /* JSDocFunctionType */:
32850                 case 305 /* JSDocSignature */:
32851                 case 171 /* ConstructorType */:
32852                     return bindFunctionOrConstructorType(node);
32853                 case 173 /* TypeLiteral */:
32854                 case 304 /* JSDocTypeLiteral */:
32855                 case 186 /* MappedType */:
32856                     return bindAnonymousTypeWorker(node);
32857                 case 310 /* JSDocClassTag */:
32858                     return bindJSDocClassTag(node);
32859                 case 193 /* ObjectLiteralExpression */:
32860                     return bindObjectLiteralExpression(node);
32861                 case 201 /* FunctionExpression */:
32862                 case 202 /* ArrowFunction */:
32863                     return bindFunctionExpression(node);
32864                 case 196 /* CallExpression */:
32865                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
32866                     switch (assignmentKind) {
32867                         case 7 /* ObjectDefinePropertyValue */:
32868                             return bindObjectDefinePropertyAssignment(node);
32869                         case 8 /* ObjectDefinePropertyExports */:
32870                             return bindObjectDefinePropertyExport(node);
32871                         case 9 /* ObjectDefinePrototypeProperty */:
32872                             return bindObjectDefinePrototypeProperty(node);
32873                         case 0 /* None */:
32874                             break; // Nothing to do
32875                         default:
32876                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
32877                     }
32878                     if (ts.isInJSFile(node)) {
32879                         bindCallExpression(node);
32880                     }
32881                     break;
32882                 // Members of classes, interfaces, and modules
32883                 case 214 /* ClassExpression */:
32884                 case 245 /* ClassDeclaration */:
32885                     // All classes are automatically in strict mode in ES6.
32886                     inStrictMode = true;
32887                     return bindClassLikeDeclaration(node);
32888                 case 246 /* InterfaceDeclaration */:
32889                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
32890                 case 247 /* TypeAliasDeclaration */:
32891                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32892                 case 248 /* EnumDeclaration */:
32893                     return bindEnumDeclaration(node);
32894                 case 249 /* ModuleDeclaration */:
32895                     return bindModuleDeclaration(node);
32896                 // Jsx-attributes
32897                 case 274 /* JsxAttributes */:
32898                     return bindJsxAttributes(node);
32899                 case 273 /* JsxAttribute */:
32900                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
32901                 // Imports and exports
32902                 case 253 /* ImportEqualsDeclaration */:
32903                 case 256 /* NamespaceImport */:
32904                 case 258 /* ImportSpecifier */:
32905                 case 263 /* ExportSpecifier */:
32906                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
32907                 case 252 /* NamespaceExportDeclaration */:
32908                     return bindNamespaceExportDeclaration(node);
32909                 case 255 /* ImportClause */:
32910                     return bindImportClause(node);
32911                 case 260 /* ExportDeclaration */:
32912                     return bindExportDeclaration(node);
32913                 case 259 /* ExportAssignment */:
32914                     return bindExportAssignment(node);
32915                 case 290 /* SourceFile */:
32916                     updateStrictModeStatementList(node.statements);
32917                     return bindSourceFileIfExternalModule();
32918                 case 223 /* Block */:
32919                     if (!ts.isFunctionLike(node.parent)) {
32920                         return;
32921                     }
32922                 // falls through
32923                 case 250 /* ModuleBlock */:
32924                     return updateStrictModeStatementList(node.statements);
32925                 case 317 /* JSDocParameterTag */:
32926                     if (node.parent.kind === 305 /* JSDocSignature */) {
32927                         return bindParameter(node);
32928                     }
32929                     if (node.parent.kind !== 304 /* JSDocTypeLiteral */) {
32930                         break;
32931                     }
32932                 // falls through
32933                 case 323 /* JSDocPropertyTag */:
32934                     var propTag = node;
32935                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ?
32936                         4 /* Property */ | 16777216 /* Optional */ :
32937                         4 /* Property */;
32938                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
32939                 case 322 /* JSDocTypedefTag */:
32940                 case 315 /* JSDocCallbackTag */:
32941                 case 316 /* JSDocEnumTag */:
32942                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
32943             }
32944         }
32945         function bindPropertyWorker(node) {
32946             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
32947         }
32948         function bindAnonymousTypeWorker(node) {
32949             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
32950         }
32951         function bindSourceFileIfExternalModule() {
32952             setExportContextFlag(file);
32953             if (ts.isExternalModule(file)) {
32954                 bindSourceFileAsExternalModule();
32955             }
32956             else if (ts.isJsonSourceFile(file)) {
32957                 bindSourceFileAsExternalModule();
32958                 // Create symbol equivalent for the module.exports = {}
32959                 var originalSymbol = file.symbol;
32960                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
32961                 file.symbol = originalSymbol;
32962             }
32963         }
32964         function bindSourceFileAsExternalModule() {
32965             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
32966         }
32967         function bindExportAssignment(node) {
32968             if (!container.symbol || !container.symbol.exports) {
32969                 // Export assignment in some sort of block construct
32970                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
32971             }
32972             else {
32973                 var flags = ts.exportAssignmentIsAlias(node)
32974                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
32975                     ? 2097152 /* Alias */
32976                     // An export default clause with any other expression exports a value
32977                     : 4 /* Property */;
32978                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
32979                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
32980                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
32981                 if (node.isExportEquals) {
32982                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
32983                     ts.setValueDeclaration(symbol, node);
32984                 }
32985             }
32986         }
32987         function bindNamespaceExportDeclaration(node) {
32988             if (node.modifiers && node.modifiers.length) {
32989                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
32990             }
32991             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
32992                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
32993                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
32994                         : undefined;
32995             if (diag) {
32996                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
32997             }
32998             else {
32999                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
33000                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33001             }
33002         }
33003         function bindExportDeclaration(node) {
33004             if (!container.symbol || !container.symbol.exports) {
33005                 // Export * in some sort of block construct
33006                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
33007             }
33008             else if (!node.exportClause) {
33009                 // All export * declarations are collected in an __export symbol
33010                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
33011             }
33012             else if (ts.isNamespaceExport(node.exportClause)) {
33013                 // declareSymbol walks up parents to find name text, parent _must_ be set
33014                 // but won't be set by the normal binder walk until `bindChildren` later on.
33015                 node.exportClause.parent = node;
33016                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33017             }
33018         }
33019         function bindImportClause(node) {
33020             if (node.name) {
33021                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33022             }
33023         }
33024         function setCommonJsModuleIndicator(node) {
33025             if (file.externalModuleIndicator) {
33026                 return false;
33027             }
33028             if (!file.commonJsModuleIndicator) {
33029                 file.commonJsModuleIndicator = node;
33030                 bindSourceFileAsExternalModule();
33031             }
33032             return true;
33033         }
33034         function bindObjectDefinePropertyExport(node) {
33035             if (!setCommonJsModuleIndicator(node)) {
33036                 return;
33037             }
33038             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
33039                 if (symbol) {
33040                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33041                 }
33042                 return symbol;
33043             });
33044             if (symbol) {
33045                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
33046                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
33047             }
33048         }
33049         function bindExportsPropertyAssignment(node) {
33050             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
33051             // expression is the declaration
33052             if (!setCommonJsModuleIndicator(node)) {
33053                 return;
33054             }
33055             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
33056                 if (symbol) {
33057                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33058                 }
33059                 return symbol;
33060             });
33061             if (symbol) {
33062                 var flags = ts.isClassExpression(node.right) ?
33063                     4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
33064                     4 /* Property */ | 1048576 /* ExportValue */;
33065                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
33066             }
33067         }
33068         function bindModuleExportsAssignment(node) {
33069             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
33070             // is still pointing to 'module.exports'.
33071             // We do not want to consider this as 'export=' since a module can have only one of these.
33072             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
33073             if (!setCommonJsModuleIndicator(node)) {
33074                 return;
33075             }
33076             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
33077             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
33078                 return;
33079             }
33080             // 'module.exports = expr' assignment
33081             var flags = ts.exportAssignmentIsAlias(node)
33082                 ? 2097152 /* Alias */
33083                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
33084             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
33085             ts.setValueDeclaration(symbol, node);
33086         }
33087         function bindThisPropertyAssignment(node) {
33088             ts.Debug.assert(ts.isInJSFile(node));
33089             // private identifiers *must* be declared (even in JS files)
33090             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
33091                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
33092             if (hasPrivateIdentifier) {
33093                 return;
33094             }
33095             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
33096             switch (thisContainer.kind) {
33097                 case 244 /* FunctionDeclaration */:
33098                 case 201 /* FunctionExpression */:
33099                     var constructorSymbol = thisContainer.symbol;
33100                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
33101                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
33102                         var l = thisContainer.parent.left;
33103                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
33104                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
33105                         }
33106                     }
33107                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
33108                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
33109                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
33110                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
33111                         if (ts.hasDynamicName(node)) {
33112                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
33113                         }
33114                         else {
33115                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
33116                         }
33117                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
33118                     }
33119                     break;
33120                 case 162 /* Constructor */:
33121                 case 159 /* PropertyDeclaration */:
33122                 case 161 /* MethodDeclaration */:
33123                 case 163 /* GetAccessor */:
33124                 case 164 /* SetAccessor */:
33125                     // this.foo assignment in a JavaScript class
33126                     // Bind this property to the containing class
33127                     var containingClass = thisContainer.parent;
33128                     var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
33129                     if (ts.hasDynamicName(node)) {
33130                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
33131                     }
33132                     else {
33133                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
33134                     }
33135                     break;
33136                 case 290 /* SourceFile */:
33137                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
33138                     if (ts.hasDynamicName(node)) {
33139                         break;
33140                     }
33141                     else if (thisContainer.commonJsModuleIndicator) {
33142                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
33143                     }
33144                     else {
33145                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33146                     }
33147                     break;
33148                 default:
33149                     ts.Debug.failBadSyntaxKind(thisContainer);
33150             }
33151         }
33152         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
33153             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
33154             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
33155         }
33156         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
33157             if (symbol) {
33158                 var members = symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = ts.createMap());
33159                 members.set("" + ts.getNodeId(node), node);
33160             }
33161         }
33162         function bindSpecialPropertyDeclaration(node) {
33163             if (node.expression.kind === 104 /* ThisKeyword */) {
33164                 bindThisPropertyAssignment(node);
33165             }
33166             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 290 /* SourceFile */) {
33167                 if (ts.isPrototypeAccess(node.expression)) {
33168                     bindPrototypePropertyAssignment(node, node.parent);
33169                 }
33170                 else {
33171                     bindStaticPropertyAssignment(node);
33172                 }
33173             }
33174         }
33175         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
33176         function bindPrototypeAssignment(node) {
33177             node.left.parent = node;
33178             node.right.parent = node;
33179             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
33180         }
33181         function bindObjectDefinePrototypeProperty(node) {
33182             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
33183             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
33184                 // Ensure the namespace symbol becomes class-like
33185                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33186             }
33187             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
33188         }
33189         /**
33190          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
33191          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
33192          */
33193         function bindPrototypePropertyAssignment(lhs, parent) {
33194             // Look up the function in the local scope, since prototype assignments should
33195             // follow the function declaration
33196             var classPrototype = lhs.expression;
33197             var constructorFunction = classPrototype.expression;
33198             // Fix up parent pointers since we're going to use these nodes before we bind into them
33199             lhs.parent = parent;
33200             constructorFunction.parent = classPrototype;
33201             classPrototype.parent = lhs;
33202             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
33203         }
33204         function bindObjectDefinePropertyAssignment(node) {
33205             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
33206             var isToplevel = node.parent.parent.kind === 290 /* SourceFile */;
33207             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33208             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
33209         }
33210         function bindSpecialPropertyAssignment(node) {
33211             // Class declarations in Typescript do not allow property declarations
33212             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression);
33213             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
33214                 return;
33215             }
33216             // Fix up parent pointers since we're going to use these nodes before we bind into them
33217             node.left.parent = node;
33218             node.right.parent = node;
33219             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
33220                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
33221                 //    var util = module.exports;
33222                 //    util.property = function ...
33223                 bindExportsPropertyAssignment(node);
33224             }
33225             else if (ts.hasDynamicName(node)) {
33226                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
33227                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
33228                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
33229             }
33230             else {
33231                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
33232             }
33233         }
33234         /**
33235          * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared.
33236          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
33237          */
33238         function bindStaticPropertyAssignment(node) {
33239             ts.Debug.assert(!ts.isIdentifier(node));
33240             node.expression.parent = node;
33241             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33242         }
33243         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
33244             if (isToplevel && !isPrototypeProperty) {
33245                 // make symbols or add declarations for intermediate containers
33246                 var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
33247                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
33248                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
33249                     if (symbol) {
33250                         addDeclarationToSymbol(symbol, id, flags_1);
33251                         return symbol;
33252                     }
33253                     else {
33254                         var table = parent ? parent.exports :
33255                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
33256                         return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
33257                     }
33258                 });
33259             }
33260             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
33261                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33262             }
33263             return namespaceSymbol;
33264         }
33265         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
33266             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
33267                 return;
33268             }
33269             // Set up the members collection if it doesn't exist already
33270             var symbolTable = isPrototypeProperty ?
33271                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
33272                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
33273             var includes = 0 /* None */;
33274             var excludes = 0 /* None */;
33275             // Method-like
33276             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
33277                 includes = 8192 /* Method */;
33278                 excludes = 103359 /* MethodExcludes */;
33279             }
33280             // Maybe accessor-like
33281             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
33282                 if (ts.some(declaration.arguments[2].properties, function (p) {
33283                     var id = ts.getNameOfDeclaration(p);
33284                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
33285                 })) {
33286                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
33287                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
33288                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
33289                     excludes |= 78783 /* SetAccessorExcludes */;
33290                 }
33291                 if (ts.some(declaration.arguments[2].properties, function (p) {
33292                     var id = ts.getNameOfDeclaration(p);
33293                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
33294                 })) {
33295                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
33296                     excludes |= 46015 /* GetAccessorExcludes */;
33297                 }
33298             }
33299             if (includes === 0 /* None */) {
33300                 includes = 4 /* Property */;
33301                 excludes = 0 /* PropertyExcludes */;
33302             }
33303             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
33304         }
33305         function isTopLevelNamespaceAssignment(propertyAccess) {
33306             return ts.isBinaryExpression(propertyAccess.parent)
33307                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 290 /* SourceFile */
33308                 : propertyAccess.parent.parent.kind === 290 /* SourceFile */;
33309         }
33310         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
33311             var namespaceSymbol = lookupSymbolForPropertyAccess(name);
33312             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
33313             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
33314             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
33315         }
33316         /**
33317          * Javascript expando values are:
33318          * - Functions
33319          * - classes
33320          * - namespaces
33321          * - variables initialized with function expressions
33322          * -                       with class expressions
33323          * -                       with empty object literals
33324          * -                       with non-empty object literals if assigned to the prototype property
33325          */
33326         function isExpandoSymbol(symbol) {
33327             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
33328                 return true;
33329             }
33330             var node = symbol.valueDeclaration;
33331             if (node && ts.isCallExpression(node)) {
33332                 return !!ts.getAssignedExpandoInitializer(node);
33333             }
33334             var init = !node ? undefined :
33335                 ts.isVariableDeclaration(node) ? node.initializer :
33336                     ts.isBinaryExpression(node) ? node.right :
33337                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
33338                             undefined;
33339             init = init && ts.getRightMostAssignedExpression(init);
33340             if (init) {
33341                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
33342                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
33343             }
33344             return false;
33345         }
33346         function getParentOfBinaryExpression(expr) {
33347             while (ts.isBinaryExpression(expr.parent)) {
33348                 expr = expr.parent;
33349             }
33350             return expr.parent;
33351         }
33352         function lookupSymbolForPropertyAccess(node, lookupContainer) {
33353             if (lookupContainer === void 0) { lookupContainer = container; }
33354             if (ts.isIdentifier(node)) {
33355                 return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
33356             }
33357             else {
33358                 var symbol = lookupSymbolForPropertyAccess(node.expression);
33359                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
33360             }
33361         }
33362         function forEachIdentifierInEntityName(e, parent, action) {
33363             if (isExportsOrModuleExportsOrAlias(file, e)) {
33364                 return file.symbol;
33365             }
33366             else if (ts.isIdentifier(e)) {
33367                 return action(e, lookupSymbolForPropertyAccess(e), parent);
33368             }
33369             else {
33370                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
33371                 var name = ts.getNameOrArgument(e);
33372                 // unreachable
33373                 if (ts.isPrivateIdentifier(name)) {
33374                     ts.Debug.fail("unexpected PrivateIdentifier");
33375                 }
33376                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
33377             }
33378         }
33379         function bindCallExpression(node) {
33380             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
33381             // this check if we've already seen the module indicator
33382             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
33383                 setCommonJsModuleIndicator(node);
33384             }
33385         }
33386         function bindClassLikeDeclaration(node) {
33387             if (node.kind === 245 /* ClassDeclaration */) {
33388                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
33389             }
33390             else {
33391                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
33392                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
33393                 // Add name of class expression into the map for semantic classifier
33394                 if (node.name) {
33395                     classifiableNames.set(node.name.escapedText, true);
33396                 }
33397             }
33398             var symbol = node.symbol;
33399             // TypeScript 1.0 spec (April 2014): 8.4
33400             // Every class automatically contains a static property member named 'prototype', the
33401             // type of which is an instantiation of the class type with type Any supplied as a type
33402             // argument for each type parameter. It is an error to explicitly declare a static
33403             // property member with the name 'prototype'.
33404             //
33405             // Note: we check for this here because this class may be merging into a module.  The
33406             // module might have an exported variable called 'prototype'.  We can't allow that as
33407             // that would clash with the built-in 'prototype' for the class.
33408             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
33409             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
33410             if (symbolExport) {
33411                 if (node.name) {
33412                     node.name.parent = node;
33413                 }
33414                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
33415             }
33416             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
33417             prototypeSymbol.parent = symbol;
33418         }
33419         function bindEnumDeclaration(node) {
33420             return ts.isEnumConst(node)
33421                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
33422                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
33423         }
33424         function bindVariableDeclarationOrBindingElement(node) {
33425             if (inStrictMode) {
33426                 checkStrictModeEvalOrArguments(node, node.name);
33427             }
33428             if (!ts.isBindingPattern(node.name)) {
33429                 if (ts.isBlockOrCatchScoped(node)) {
33430                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
33431                 }
33432                 else if (ts.isParameterDeclaration(node)) {
33433                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
33434                     // because its parent chain has already been set up, since parents are set before descending into children.
33435                     //
33436                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
33437                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
33438                     // For example:
33439                     //      function foo([a,a]) {} // Duplicate Identifier error
33440                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
33441                     //                             // which correctly set excluded symbols
33442                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33443                 }
33444                 else {
33445                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33446                 }
33447             }
33448         }
33449         function bindParameter(node) {
33450             if (node.kind === 317 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) {
33451                 return;
33452             }
33453             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
33454                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
33455                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
33456                 checkStrictModeEvalOrArguments(node, node.name);
33457             }
33458             if (ts.isBindingPattern(node.name)) {
33459                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
33460             }
33461             else {
33462                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33463             }
33464             // If this is a property-parameter, then also declare the property symbol into the
33465             // containing class.
33466             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
33467                 var classDeclaration = node.parent.parent;
33468                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
33469             }
33470         }
33471         function bindFunctionDeclaration(node) {
33472             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33473                 if (ts.isAsyncFunction(node)) {
33474                     emitFlags |= 2048 /* HasAsyncFunctions */;
33475                 }
33476             }
33477             checkStrictModeFunctionName(node);
33478             if (inStrictMode) {
33479                 checkStrictModeFunctionDeclaration(node);
33480                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33481             }
33482             else {
33483                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33484             }
33485         }
33486         function bindFunctionExpression(node) {
33487             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33488                 if (ts.isAsyncFunction(node)) {
33489                     emitFlags |= 2048 /* HasAsyncFunctions */;
33490                 }
33491             }
33492             if (currentFlow) {
33493                 node.flowNode = currentFlow;
33494             }
33495             checkStrictModeFunctionName(node);
33496             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
33497             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
33498         }
33499         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
33500             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
33501                 emitFlags |= 2048 /* HasAsyncFunctions */;
33502             }
33503             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
33504                 node.flowNode = currentFlow;
33505             }
33506             return ts.hasDynamicName(node)
33507                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
33508                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
33509         }
33510         function getInferTypeContainer(node) {
33511             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
33512             return extendsType && extendsType.parent;
33513         }
33514         function bindTypeParameter(node) {
33515             if (ts.isJSDocTemplateTag(node.parent)) {
33516                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
33517                 if (container_1) {
33518                     if (!container_1.locals) {
33519                         container_1.locals = ts.createSymbolTable();
33520                     }
33521                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33522                 }
33523                 else {
33524                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33525                 }
33526             }
33527             else if (node.parent.kind === 181 /* InferType */) {
33528                 var container_2 = getInferTypeContainer(node.parent);
33529                 if (container_2) {
33530                     if (!container_2.locals) {
33531                         container_2.locals = ts.createSymbolTable();
33532                     }
33533                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33534                 }
33535                 else {
33536                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
33537                 }
33538             }
33539             else {
33540                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33541             }
33542         }
33543         // reachability checks
33544         function shouldReportErrorOnModuleDeclaration(node) {
33545             var instanceState = getModuleInstanceState(node);
33546             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
33547         }
33548         function checkUnreachable(node) {
33549             if (!(currentFlow.flags & 1 /* Unreachable */)) {
33550                 return false;
33551             }
33552             if (currentFlow === unreachableFlow) {
33553                 var reportError = 
33554                 // report error on all statements except empty ones
33555                 (ts.isStatementButNotDeclaration(node) && node.kind !== 224 /* EmptyStatement */) ||
33556                     // report error on class declarations
33557                     node.kind === 245 /* ClassDeclaration */ ||
33558                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
33559                     (node.kind === 249 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
33560                 if (reportError) {
33561                     currentFlow = reportedUnreachableFlow;
33562                     if (!options.allowUnreachableCode) {
33563                         // unreachable code is reported if
33564                         // - user has explicitly asked about it AND
33565                         // - statement is in not ambient context (statements in ambient context is already an error
33566                         //   so we should not report extras) AND
33567                         //   - node is not variable statement OR
33568                         //   - node is block scoped variable statement OR
33569                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
33570                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
33571                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
33572                         var isError_1 = ts.unreachableCodeIsError(options) &&
33573                             !(node.flags & 8388608 /* Ambient */) &&
33574                             (!ts.isVariableStatement(node) ||
33575                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
33576                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
33577                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
33578                     }
33579                 }
33580             }
33581             return true;
33582         }
33583     }
33584     function eachUnreachableRange(node, cb) {
33585         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
33586             var statements = node.parent.statements;
33587             var slice_1 = ts.sliceAfter(statements, node);
33588             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
33589         }
33590         else {
33591             cb(node, node);
33592         }
33593     }
33594     // As opposed to a pure declaration like an `interface`
33595     function isExecutableStatement(s) {
33596         // Don't remove statements that can validly be used before they appear.
33597         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
33598             // `var x;` may declare a variable used above
33599             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
33600     }
33601     function isPurelyTypeDeclaration(s) {
33602         switch (s.kind) {
33603             case 246 /* InterfaceDeclaration */:
33604             case 247 /* TypeAliasDeclaration */:
33605                 return true;
33606             case 249 /* ModuleDeclaration */:
33607                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
33608             case 248 /* EnumDeclaration */:
33609                 return ts.hasModifier(s, 2048 /* Const */);
33610             default:
33611                 return false;
33612         }
33613     }
33614     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
33615         var i = 0;
33616         var q = [node];
33617         while (q.length && i < 100) {
33618             i++;
33619             node = q.shift();
33620             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
33621                 return true;
33622             }
33623             else if (ts.isIdentifier(node)) {
33624                 var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
33625                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
33626                     var init = symbol.valueDeclaration.initializer;
33627                     q.push(init);
33628                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
33629                         q.push(init.left);
33630                         q.push(init.right);
33631                     }
33632                 }
33633             }
33634         }
33635         return false;
33636     }
33637     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
33638     function lookupSymbolForNameWorker(container, name) {
33639         var local = container.locals && container.locals.get(name);
33640         if (local) {
33641             return local.exportSymbol || local;
33642         }
33643         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
33644             return container.jsGlobalAugmentations.get(name);
33645         }
33646         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
33647     }
33648     /**
33649      * Computes the transform flags for a node, given the transform flags of its subtree
33650      *
33651      * @param node The node to analyze
33652      * @param subtreeFlags Transform flags computed for this node's subtree
33653      */
33654     function computeTransformFlagsForNode(node, subtreeFlags) {
33655         var kind = node.kind;
33656         switch (kind) {
33657             case 196 /* CallExpression */:
33658                 return computeCallExpression(node, subtreeFlags);
33659             case 197 /* NewExpression */:
33660                 return computeNewExpression(node, subtreeFlags);
33661             case 249 /* ModuleDeclaration */:
33662                 return computeModuleDeclaration(node, subtreeFlags);
33663             case 200 /* ParenthesizedExpression */:
33664                 return computeParenthesizedExpression(node, subtreeFlags);
33665             case 209 /* BinaryExpression */:
33666                 return computeBinaryExpression(node, subtreeFlags);
33667             case 226 /* ExpressionStatement */:
33668                 return computeExpressionStatement(node, subtreeFlags);
33669             case 156 /* Parameter */:
33670                 return computeParameter(node, subtreeFlags);
33671             case 202 /* ArrowFunction */:
33672                 return computeArrowFunction(node, subtreeFlags);
33673             case 201 /* FunctionExpression */:
33674                 return computeFunctionExpression(node, subtreeFlags);
33675             case 244 /* FunctionDeclaration */:
33676                 return computeFunctionDeclaration(node, subtreeFlags);
33677             case 242 /* VariableDeclaration */:
33678                 return computeVariableDeclaration(node, subtreeFlags);
33679             case 243 /* VariableDeclarationList */:
33680                 return computeVariableDeclarationList(node, subtreeFlags);
33681             case 225 /* VariableStatement */:
33682                 return computeVariableStatement(node, subtreeFlags);
33683             case 238 /* LabeledStatement */:
33684                 return computeLabeledStatement(node, subtreeFlags);
33685             case 245 /* ClassDeclaration */:
33686                 return computeClassDeclaration(node, subtreeFlags);
33687             case 214 /* ClassExpression */:
33688                 return computeClassExpression(node, subtreeFlags);
33689             case 279 /* HeritageClause */:
33690                 return computeHeritageClause(node, subtreeFlags);
33691             case 280 /* CatchClause */:
33692                 return computeCatchClause(node, subtreeFlags);
33693             case 216 /* ExpressionWithTypeArguments */:
33694                 return computeExpressionWithTypeArguments(node, subtreeFlags);
33695             case 162 /* Constructor */:
33696                 return computeConstructor(node, subtreeFlags);
33697             case 159 /* PropertyDeclaration */:
33698                 return computePropertyDeclaration(node, subtreeFlags);
33699             case 161 /* MethodDeclaration */:
33700                 return computeMethod(node, subtreeFlags);
33701             case 163 /* GetAccessor */:
33702             case 164 /* SetAccessor */:
33703                 return computeAccessor(node, subtreeFlags);
33704             case 253 /* ImportEqualsDeclaration */:
33705                 return computeImportEquals(node, subtreeFlags);
33706             case 194 /* PropertyAccessExpression */:
33707                 return computePropertyAccess(node, subtreeFlags);
33708             case 195 /* ElementAccessExpression */:
33709                 return computeElementAccess(node, subtreeFlags);
33710             case 267 /* JsxSelfClosingElement */:
33711             case 268 /* JsxOpeningElement */:
33712                 return computeJsxOpeningLikeElement(node, subtreeFlags);
33713             default:
33714                 return computeOther(node, kind, subtreeFlags);
33715         }
33716     }
33717     ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
33718     function computeCallExpression(node, subtreeFlags) {
33719         var transformFlags = subtreeFlags;
33720         var callee = ts.skipOuterExpressions(node.expression);
33721         var expression = node.expression;
33722         if (node.flags & 32 /* OptionalChain */) {
33723             transformFlags |= 8 /* ContainsES2020 */;
33724         }
33725         if (node.typeArguments) {
33726             transformFlags |= 1 /* AssertTypeScript */;
33727         }
33728         if (subtreeFlags & 8192 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
33729             // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
33730             // node.
33731             transformFlags |= 256 /* AssertES2015 */;
33732             if (ts.isSuperProperty(callee)) {
33733                 transformFlags |= 4096 /* ContainsLexicalThis */;
33734             }
33735         }
33736         if (expression.kind === 96 /* ImportKeyword */) {
33737             transformFlags |= 2097152 /* ContainsDynamicImport */;
33738         }
33739         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33740         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33741     }
33742     function computeNewExpression(node, subtreeFlags) {
33743         var transformFlags = subtreeFlags;
33744         if (node.typeArguments) {
33745             transformFlags |= 1 /* AssertTypeScript */;
33746         }
33747         if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
33748             // If the this node contains a SpreadElementExpression then it is an ES6
33749             // node.
33750             transformFlags |= 256 /* AssertES2015 */;
33751         }
33752         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33753         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33754     }
33755     function computeJsxOpeningLikeElement(node, subtreeFlags) {
33756         var transformFlags = subtreeFlags | 2 /* AssertJsx */;
33757         if (node.typeArguments) {
33758             transformFlags |= 1 /* AssertTypeScript */;
33759         }
33760         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33761         return transformFlags & ~536870912 /* NodeExcludes */;
33762     }
33763     function computeBinaryExpression(node, subtreeFlags) {
33764         var transformFlags = subtreeFlags;
33765         var operatorTokenKind = node.operatorToken.kind;
33766         var leftKind = node.left.kind;
33767         if (operatorTokenKind === 60 /* QuestionQuestionToken */) {
33768             transformFlags |= 8 /* AssertES2020 */;
33769         }
33770         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 193 /* ObjectLiteralExpression */) {
33771             // Destructuring object assignments with are ES2015 syntax
33772             // and possibly ES2018 if they contain rest
33773             transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33774         }
33775         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 192 /* ArrayLiteralExpression */) {
33776             // Destructuring assignments are ES2015 syntax.
33777             transformFlags |= 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33778         }
33779         else if (operatorTokenKind === 42 /* AsteriskAsteriskToken */
33780             || operatorTokenKind === 66 /* AsteriskAsteriskEqualsToken */) {
33781             // Exponentiation is ES2016 syntax.
33782             transformFlags |= 128 /* AssertES2016 */;
33783         }
33784         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33785         return transformFlags & ~536870912 /* NodeExcludes */;
33786     }
33787     function computeParameter(node, subtreeFlags) {
33788         var transformFlags = subtreeFlags;
33789         var name = node.name;
33790         var initializer = node.initializer;
33791         var dotDotDotToken = node.dotDotDotToken;
33792         // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
33793         // syntax.
33794         if (node.questionToken
33795             || node.type
33796             || (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
33797             || ts.isThisIdentifier(name)) {
33798             transformFlags |= 1 /* AssertTypeScript */;
33799         }
33800         // If a parameter has an accessibility modifier, then it is TypeScript syntax.
33801         if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
33802             transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
33803         }
33804         // parameters with object rest destructuring are ES2018 syntax
33805         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33806             transformFlags |= 32 /* AssertES2018 */;
33807         }
33808         // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
33809         // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
33810         if (subtreeFlags & 131072 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
33811             transformFlags |= 256 /* AssertES2015 */;
33812         }
33813         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33814         return transformFlags & ~536870912 /* ParameterExcludes */;
33815     }
33816     function computeParenthesizedExpression(node, subtreeFlags) {
33817         var transformFlags = subtreeFlags;
33818         var expression = node.expression;
33819         var expressionKind = expression.kind;
33820         // If the node is synthesized, it means the emitter put the parentheses there,
33821         // not the user. If we didn't want them, the emitter would not have put them
33822         // there.
33823         if (expressionKind === 217 /* AsExpression */
33824             || expressionKind === 199 /* TypeAssertionExpression */) {
33825             transformFlags |= 1 /* AssertTypeScript */;
33826         }
33827         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33828         return transformFlags & ~536870912 /* OuterExpressionExcludes */;
33829     }
33830     function computeClassDeclaration(node, subtreeFlags) {
33831         var transformFlags;
33832         if (ts.hasModifier(node, 2 /* Ambient */)) {
33833             // An ambient declaration is TypeScript syntax.
33834             transformFlags = 1 /* AssertTypeScript */;
33835         }
33836         else {
33837             // A ClassDeclaration is ES6 syntax.
33838             transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33839             // A class with a parameter property assignment or decorator is TypeScript syntax.
33840             // An exported declaration may be TypeScript syntax, but is handled by the visitor
33841             // for a namespace declaration.
33842             if ((subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */)
33843                 || node.typeParameters) {
33844                 transformFlags |= 1 /* AssertTypeScript */;
33845             }
33846         }
33847         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33848         return transformFlags & ~536905728 /* ClassExcludes */;
33849     }
33850     function computeClassExpression(node, subtreeFlags) {
33851         // A ClassExpression is ES6 syntax.
33852         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33853         // A class with a parameter property assignment or decorator is TypeScript syntax.
33854         if (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */
33855             || node.typeParameters) {
33856             transformFlags |= 1 /* AssertTypeScript */;
33857         }
33858         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33859         return transformFlags & ~536905728 /* ClassExcludes */;
33860     }
33861     function computeHeritageClause(node, subtreeFlags) {
33862         var transformFlags = subtreeFlags;
33863         switch (node.token) {
33864             case 90 /* ExtendsKeyword */:
33865                 // An `extends` HeritageClause is ES6 syntax.
33866                 transformFlags |= 256 /* AssertES2015 */;
33867                 break;
33868             case 113 /* ImplementsKeyword */:
33869                 // An `implements` HeritageClause is TypeScript syntax.
33870                 transformFlags |= 1 /* AssertTypeScript */;
33871                 break;
33872             default:
33873                 ts.Debug.fail("Unexpected token for heritage clause");
33874                 break;
33875         }
33876         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33877         return transformFlags & ~536870912 /* NodeExcludes */;
33878     }
33879     function computeCatchClause(node, subtreeFlags) {
33880         var transformFlags = subtreeFlags;
33881         if (!node.variableDeclaration) {
33882             transformFlags |= 16 /* AssertES2019 */;
33883         }
33884         else if (ts.isBindingPattern(node.variableDeclaration.name)) {
33885             transformFlags |= 256 /* AssertES2015 */;
33886         }
33887         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33888         return transformFlags & ~536887296 /* CatchClauseExcludes */;
33889     }
33890     function computeExpressionWithTypeArguments(node, subtreeFlags) {
33891         // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
33892         // extends clause of a class.
33893         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33894         // If an ExpressionWithTypeArguments contains type arguments, then it
33895         // is TypeScript syntax.
33896         if (node.typeArguments) {
33897             transformFlags |= 1 /* AssertTypeScript */;
33898         }
33899         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33900         return transformFlags & ~536870912 /* NodeExcludes */;
33901     }
33902     function computeConstructor(node, subtreeFlags) {
33903         var transformFlags = subtreeFlags;
33904         // TypeScript-specific modifiers and overloads are TypeScript syntax
33905         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33906             || !node.body) {
33907             transformFlags |= 1 /* AssertTypeScript */;
33908         }
33909         // function declarations with object rest destructuring are ES2018 syntax
33910         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33911             transformFlags |= 32 /* AssertES2018 */;
33912         }
33913         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33914         return transformFlags & ~538923008 /* ConstructorExcludes */;
33915     }
33916     function computeMethod(node, subtreeFlags) {
33917         // A MethodDeclaration is ES6 syntax.
33918         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33919         // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
33920         // overloads are TypeScript syntax.
33921         if (node.decorators
33922             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33923             || node.typeParameters
33924             || node.type
33925             || !node.body
33926             || node.questionToken) {
33927             transformFlags |= 1 /* AssertTypeScript */;
33928         }
33929         // function declarations with object rest destructuring are ES2018 syntax
33930         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33931             transformFlags |= 32 /* AssertES2018 */;
33932         }
33933         // An async method declaration is ES2017 syntax.
33934         if (ts.hasModifier(node, 256 /* Async */)) {
33935             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33936         }
33937         if (node.asteriskToken) {
33938             transformFlags |= 512 /* AssertGenerator */;
33939         }
33940         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33941         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33942     }
33943     function computeAccessor(node, subtreeFlags) {
33944         var transformFlags = subtreeFlags;
33945         // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
33946         // TypeScript syntax.
33947         if (node.decorators
33948             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33949             || node.type
33950             || !node.body) {
33951             transformFlags |= 1 /* AssertTypeScript */;
33952         }
33953         // function declarations with object rest destructuring are ES2018 syntax
33954         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33955             transformFlags |= 32 /* AssertES2018 */;
33956         }
33957         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33958         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33959     }
33960     function computePropertyDeclaration(node, subtreeFlags) {
33961         var transformFlags = subtreeFlags | 4194304 /* ContainsClassFields */;
33962         // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax.
33963         if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken || node.exclamationToken) {
33964             transformFlags |= 1 /* AssertTypeScript */;
33965         }
33966         // Hoisted variables related to class properties should live within the TypeScript class wrapper.
33967         if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
33968             transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
33969         }
33970         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33971         return propagatePropertyNameFlags(node.name, transformFlags & ~536875008 /* PropertyExcludes */);
33972     }
33973     function computeFunctionDeclaration(node, subtreeFlags) {
33974         var transformFlags;
33975         var modifierFlags = ts.getModifierFlags(node);
33976         var body = node.body;
33977         if (!body || (modifierFlags & 2 /* Ambient */)) {
33978             // An ambient declaration is TypeScript syntax.
33979             // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
33980             transformFlags = 1 /* AssertTypeScript */;
33981         }
33982         else {
33983             transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
33984             // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
33985             // syntax.
33986             if (modifierFlags & 2270 /* TypeScriptModifier */
33987                 || node.typeParameters
33988                 || node.type) {
33989                 transformFlags |= 1 /* AssertTypeScript */;
33990             }
33991             // An async function declaration is ES2017 syntax.
33992             if (modifierFlags & 256 /* Async */) {
33993                 transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33994             }
33995             // function declarations with object rest destructuring are ES2018 syntax
33996             if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33997                 transformFlags |= 32 /* AssertES2018 */;
33998             }
33999             // If a FunctionDeclaration is generator function and is the body of a
34000             // transformed async function, then this node can be transformed to a
34001             // down-level generator.
34002             // Currently we do not support transforming any other generator functions
34003             // down level.
34004             if (node.asteriskToken) {
34005                 transformFlags |= 512 /* AssertGenerator */;
34006             }
34007         }
34008         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34009         return transformFlags & ~538925056 /* FunctionExcludes */;
34010     }
34011     function computeFunctionExpression(node, subtreeFlags) {
34012         var transformFlags = subtreeFlags;
34013         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34014         // syntax.
34015         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34016             || node.typeParameters
34017             || node.type) {
34018             transformFlags |= 1 /* AssertTypeScript */;
34019         }
34020         // An async function expression is ES2017 syntax.
34021         if (ts.hasModifier(node, 256 /* Async */)) {
34022             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34023         }
34024         // function expressions with object rest destructuring are ES2018 syntax
34025         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34026             transformFlags |= 32 /* AssertES2018 */;
34027         }
34028         // If a FunctionExpression is generator function and is the body of a
34029         // transformed async function, then this node can be transformed to a
34030         // down-level generator.
34031         if (node.asteriskToken) {
34032             transformFlags |= 512 /* AssertGenerator */;
34033         }
34034         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34035         return transformFlags & ~538925056 /* FunctionExcludes */;
34036     }
34037     function computeArrowFunction(node, subtreeFlags) {
34038         // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
34039         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34040         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34041         // syntax.
34042         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34043             || node.typeParameters
34044             || node.type) {
34045             transformFlags |= 1 /* AssertTypeScript */;
34046         }
34047         // An async arrow function is ES2017 syntax.
34048         if (ts.hasModifier(node, 256 /* Async */)) {
34049             transformFlags |= 64 /* AssertES2017 */;
34050         }
34051         // arrow functions with object rest destructuring are ES2018 syntax
34052         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34053             transformFlags |= 32 /* AssertES2018 */;
34054         }
34055         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34056         return transformFlags & ~538920960 /* ArrowFunctionExcludes */;
34057     }
34058     function computePropertyAccess(node, subtreeFlags) {
34059         var transformFlags = subtreeFlags;
34060         if (node.flags & 32 /* OptionalChain */) {
34061             transformFlags |= 8 /* ContainsES2020 */;
34062         }
34063         // If a PropertyAccessExpression starts with a super keyword, then it is
34064         // ES6 syntax, and requires a lexical `this` binding.
34065         if (node.expression.kind === 102 /* SuperKeyword */) {
34066             // super inside of an async function requires hoisting the super access (ES2017).
34067             // same for super inside of an async generator, which is ES2018.
34068             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34069         }
34070         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34071         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34072     }
34073     function computeElementAccess(node, subtreeFlags) {
34074         var transformFlags = subtreeFlags;
34075         if (node.flags & 32 /* OptionalChain */) {
34076             transformFlags |= 8 /* ContainsES2020 */;
34077         }
34078         // If an ElementAccessExpression starts with a super keyword, then it is
34079         // ES6 syntax, and requires a lexical `this` binding.
34080         if (node.expression.kind === 102 /* SuperKeyword */) {
34081             // super inside of an async function requires hoisting the super access (ES2017).
34082             // same for super inside of an async generator, which is ES2018.
34083             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34084         }
34085         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34086         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34087     }
34088     function computeVariableDeclaration(node, subtreeFlags) {
34089         var transformFlags = subtreeFlags;
34090         transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
34091         // A VariableDeclaration containing ObjectRest is ES2018 syntax
34092         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34093             transformFlags |= 32 /* AssertES2018 */;
34094         }
34095         // Type annotations are TypeScript syntax.
34096         if (node.type || node.exclamationToken) {
34097             transformFlags |= 1 /* AssertTypeScript */;
34098         }
34099         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34100         return transformFlags & ~536870912 /* NodeExcludes */;
34101     }
34102     function computeVariableStatement(node, subtreeFlags) {
34103         var transformFlags;
34104         var declarationListTransformFlags = node.declarationList.transformFlags;
34105         // An ambient declaration is TypeScript syntax.
34106         if (ts.hasModifier(node, 2 /* Ambient */)) {
34107             transformFlags = 1 /* AssertTypeScript */;
34108         }
34109         else {
34110             transformFlags = subtreeFlags;
34111             if (declarationListTransformFlags & 131072 /* ContainsBindingPattern */) {
34112                 transformFlags |= 256 /* AssertES2015 */;
34113             }
34114         }
34115         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34116         return transformFlags & ~536870912 /* NodeExcludes */;
34117     }
34118     function computeLabeledStatement(node, subtreeFlags) {
34119         var transformFlags = subtreeFlags;
34120         // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
34121         if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */
34122             && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
34123             transformFlags |= 256 /* AssertES2015 */;
34124         }
34125         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34126         return transformFlags & ~536870912 /* NodeExcludes */;
34127     }
34128     function computeImportEquals(node, subtreeFlags) {
34129         var transformFlags = subtreeFlags;
34130         // An ImportEqualsDeclaration with a namespace reference is TypeScript.
34131         if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
34132             transformFlags |= 1 /* AssertTypeScript */;
34133         }
34134         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34135         return transformFlags & ~536870912 /* NodeExcludes */;
34136     }
34137     function computeExpressionStatement(node, subtreeFlags) {
34138         var transformFlags = subtreeFlags;
34139         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34140         return transformFlags & ~536870912 /* NodeExcludes */;
34141     }
34142     function computeModuleDeclaration(node, subtreeFlags) {
34143         var transformFlags = 1 /* AssertTypeScript */;
34144         var modifierFlags = ts.getModifierFlags(node);
34145         if ((modifierFlags & 2 /* Ambient */) === 0) {
34146             transformFlags |= subtreeFlags;
34147         }
34148         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34149         return transformFlags & ~537991168 /* ModuleExcludes */;
34150     }
34151     function computeVariableDeclarationList(node, subtreeFlags) {
34152         var transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34153         if (subtreeFlags & 131072 /* ContainsBindingPattern */) {
34154             transformFlags |= 256 /* AssertES2015 */;
34155         }
34156         // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
34157         if (node.flags & 3 /* BlockScoped */) {
34158             transformFlags |= 256 /* AssertES2015 */ | 65536 /* ContainsBlockScopedBinding */;
34159         }
34160         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34161         return transformFlags & ~537018368 /* VariableDeclarationListExcludes */;
34162     }
34163     function computeOther(node, kind, subtreeFlags) {
34164         // Mark transformations needed for each node
34165         var transformFlags = subtreeFlags;
34166         var excludeFlags = 536870912 /* NodeExcludes */;
34167         switch (kind) {
34168             case 126 /* AsyncKeyword */:
34169                 // async is ES2017 syntax, but may be ES2018 syntax (for async generators)
34170                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */;
34171                 break;
34172             case 206 /* AwaitExpression */:
34173                 // await is ES2017 syntax, but may be ES2018 syntax (for async generators)
34174                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */ | 524288 /* ContainsAwait */;
34175                 break;
34176             case 199 /* TypeAssertionExpression */:
34177             case 217 /* AsExpression */:
34178             case 326 /* PartiallyEmittedExpression */:
34179                 // These nodes are TypeScript syntax.
34180                 transformFlags |= 1 /* AssertTypeScript */;
34181                 excludeFlags = 536870912 /* OuterExpressionExcludes */;
34182                 break;
34183             case 119 /* PublicKeyword */:
34184             case 117 /* PrivateKeyword */:
34185             case 118 /* ProtectedKeyword */:
34186             case 122 /* AbstractKeyword */:
34187             case 130 /* DeclareKeyword */:
34188             case 81 /* ConstKeyword */:
34189             case 248 /* EnumDeclaration */:
34190             case 284 /* EnumMember */:
34191             case 218 /* NonNullExpression */:
34192             case 138 /* ReadonlyKeyword */:
34193                 // These nodes are TypeScript syntax.
34194                 transformFlags |= 1 /* AssertTypeScript */;
34195                 break;
34196             case 266 /* JsxElement */:
34197             case 11 /* JsxText */:
34198             case 269 /* JsxClosingElement */:
34199             case 270 /* JsxFragment */:
34200             case 271 /* JsxOpeningFragment */:
34201             case 272 /* JsxClosingFragment */:
34202             case 273 /* JsxAttribute */:
34203             case 274 /* JsxAttributes */:
34204             case 275 /* JsxSpreadAttribute */:
34205             case 276 /* JsxExpression */:
34206                 // These nodes are Jsx syntax.
34207                 transformFlags |= 2 /* AssertJsx */;
34208                 break;
34209             case 14 /* NoSubstitutionTemplateLiteral */:
34210             case 15 /* TemplateHead */:
34211             case 16 /* TemplateMiddle */:
34212             case 17 /* TemplateTail */:
34213                 if (node.templateFlags) {
34214                     transformFlags |= 32 /* AssertES2018 */;
34215                     break;
34216                 }
34217             // falls through
34218             case 198 /* TaggedTemplateExpression */:
34219                 if (ts.hasInvalidEscape(node.template)) {
34220                     transformFlags |= 32 /* AssertES2018 */;
34221                     break;
34222                 }
34223             // falls through
34224             case 211 /* TemplateExpression */:
34225             case 282 /* ShorthandPropertyAssignment */:
34226             case 120 /* StaticKeyword */:
34227             case 219 /* MetaProperty */:
34228                 // These nodes are ES6 syntax.
34229                 transformFlags |= 256 /* AssertES2015 */;
34230                 break;
34231             case 10 /* StringLiteral */:
34232                 if (node.hasExtendedUnicodeEscape) {
34233                     transformFlags |= 256 /* AssertES2015 */;
34234                 }
34235                 break;
34236             case 8 /* NumericLiteral */:
34237                 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
34238                     transformFlags |= 256 /* AssertES2015 */;
34239                 }
34240                 break;
34241             case 9 /* BigIntLiteral */:
34242                 transformFlags |= 4 /* AssertESNext */;
34243                 break;
34244             case 232 /* ForOfStatement */:
34245                 // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
34246                 if (node.awaitModifier) {
34247                     transformFlags |= 32 /* AssertES2018 */;
34248                 }
34249                 transformFlags |= 256 /* AssertES2015 */;
34250                 break;
34251             case 212 /* YieldExpression */:
34252                 // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
34253                 // generator).
34254                 transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 262144 /* ContainsYield */;
34255                 break;
34256             case 125 /* AnyKeyword */:
34257             case 140 /* NumberKeyword */:
34258             case 151 /* BigIntKeyword */:
34259             case 137 /* NeverKeyword */:
34260             case 141 /* ObjectKeyword */:
34261             case 143 /* StringKeyword */:
34262             case 128 /* BooleanKeyword */:
34263             case 144 /* SymbolKeyword */:
34264             case 110 /* VoidKeyword */:
34265             case 155 /* TypeParameter */:
34266             case 158 /* PropertySignature */:
34267             case 160 /* MethodSignature */:
34268             case 165 /* CallSignature */:
34269             case 166 /* ConstructSignature */:
34270             case 167 /* IndexSignature */:
34271             case 168 /* TypePredicate */:
34272             case 169 /* TypeReference */:
34273             case 170 /* FunctionType */:
34274             case 171 /* ConstructorType */:
34275             case 172 /* TypeQuery */:
34276             case 173 /* TypeLiteral */:
34277             case 174 /* ArrayType */:
34278             case 175 /* TupleType */:
34279             case 176 /* OptionalType */:
34280             case 177 /* RestType */:
34281             case 178 /* UnionType */:
34282             case 179 /* IntersectionType */:
34283             case 180 /* ConditionalType */:
34284             case 181 /* InferType */:
34285             case 182 /* ParenthesizedType */:
34286             case 246 /* InterfaceDeclaration */:
34287             case 247 /* TypeAliasDeclaration */:
34288             case 183 /* ThisType */:
34289             case 184 /* TypeOperator */:
34290             case 185 /* IndexedAccessType */:
34291             case 186 /* MappedType */:
34292             case 187 /* LiteralType */:
34293             case 252 /* NamespaceExportDeclaration */:
34294                 // Types and signatures are TypeScript syntax, and exclude all other facts.
34295                 transformFlags = 1 /* AssertTypeScript */;
34296                 excludeFlags = -2 /* TypeExcludes */;
34297                 break;
34298             case 154 /* ComputedPropertyName */:
34299                 // Even though computed property names are ES6, we don't treat them as such.
34300                 // This is so that they can flow through PropertyName transforms unaffected.
34301                 // Instead, we mark the container as ES6, so that it can properly handle the transform.
34302                 transformFlags |= 32768 /* ContainsComputedPropertyName */;
34303                 break;
34304             case 213 /* SpreadElement */:
34305                 transformFlags |= 256 /* AssertES2015 */ | 8192 /* ContainsRestOrSpread */;
34306                 break;
34307             case 283 /* SpreadAssignment */:
34308                 transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34309                 break;
34310             case 102 /* SuperKeyword */:
34311                 // This node is ES6 syntax.
34312                 transformFlags |= 256 /* AssertES2015 */;
34313                 excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
34314                 break;
34315             case 104 /* ThisKeyword */:
34316                 // Mark this node and its ancestors as containing a lexical `this` keyword.
34317                 transformFlags |= 4096 /* ContainsLexicalThis */;
34318                 break;
34319             case 189 /* ObjectBindingPattern */:
34320                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34321                 if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
34322                     transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34323                 }
34324                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34325                 break;
34326             case 190 /* ArrayBindingPattern */:
34327                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34328                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34329                 break;
34330             case 191 /* BindingElement */:
34331                 transformFlags |= 256 /* AssertES2015 */;
34332                 if (node.dotDotDotToken) {
34333                     transformFlags |= 8192 /* ContainsRestOrSpread */;
34334                 }
34335                 break;
34336             case 157 /* Decorator */:
34337                 // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
34338                 transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
34339                 break;
34340             case 193 /* ObjectLiteralExpression */:
34341                 excludeFlags = 536922112 /* ObjectLiteralExcludes */;
34342                 if (subtreeFlags & 32768 /* ContainsComputedPropertyName */) {
34343                     // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
34344                     // is an ES6 node.
34345                     transformFlags |= 256 /* AssertES2015 */;
34346                 }
34347                 if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34348                     // If an ObjectLiteralExpression contains a spread element, then it
34349                     // is an ES2018 node.
34350                     transformFlags |= 32 /* AssertES2018 */;
34351                 }
34352                 break;
34353             case 192 /* ArrayLiteralExpression */:
34354                 excludeFlags = 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34355                 break;
34356             case 228 /* DoStatement */:
34357             case 229 /* WhileStatement */:
34358             case 230 /* ForStatement */:
34359             case 231 /* ForInStatement */:
34360                 // A loop containing a block scoped binding *may* need to be transformed from ES6.
34361                 if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */) {
34362                     transformFlags |= 256 /* AssertES2015 */;
34363                 }
34364                 break;
34365             case 290 /* SourceFile */:
34366                 break;
34367             case 262 /* NamespaceExport */:
34368                 transformFlags |= 4 /* AssertESNext */;
34369                 break;
34370             case 235 /* ReturnStatement */:
34371                 // Return statements may require an `await` in ES2018.
34372                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */ | 32 /* AssertES2018 */;
34373                 break;
34374             case 233 /* ContinueStatement */:
34375             case 234 /* BreakStatement */:
34376                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34377                 break;
34378             case 76 /* PrivateIdentifier */:
34379                 transformFlags |= 4194304 /* ContainsClassFields */;
34380                 break;
34381         }
34382         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34383         return transformFlags & ~excludeFlags;
34384     }
34385     function propagatePropertyNameFlags(node, transformFlags) {
34386         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
34387     }
34388     /**
34389      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
34390      *
34391      * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
34392      *       For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
34393      *       than calling this function.
34394      */
34395     function getTransformFlagsSubtreeExclusions(kind) {
34396         if (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */) {
34397             return -2 /* TypeExcludes */;
34398         }
34399         switch (kind) {
34400             case 196 /* CallExpression */:
34401             case 197 /* NewExpression */:
34402             case 192 /* ArrayLiteralExpression */:
34403                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34404             case 249 /* ModuleDeclaration */:
34405                 return 537991168 /* ModuleExcludes */;
34406             case 156 /* Parameter */:
34407                 return 536870912 /* ParameterExcludes */;
34408             case 202 /* ArrowFunction */:
34409                 return 538920960 /* ArrowFunctionExcludes */;
34410             case 201 /* FunctionExpression */:
34411             case 244 /* FunctionDeclaration */:
34412                 return 538925056 /* FunctionExcludes */;
34413             case 243 /* VariableDeclarationList */:
34414                 return 537018368 /* VariableDeclarationListExcludes */;
34415             case 245 /* ClassDeclaration */:
34416             case 214 /* ClassExpression */:
34417                 return 536905728 /* ClassExcludes */;
34418             case 162 /* Constructor */:
34419                 return 538923008 /* ConstructorExcludes */;
34420             case 161 /* MethodDeclaration */:
34421             case 163 /* GetAccessor */:
34422             case 164 /* SetAccessor */:
34423                 return 538923008 /* MethodOrAccessorExcludes */;
34424             case 125 /* AnyKeyword */:
34425             case 140 /* NumberKeyword */:
34426             case 151 /* BigIntKeyword */:
34427             case 137 /* NeverKeyword */:
34428             case 143 /* StringKeyword */:
34429             case 141 /* ObjectKeyword */:
34430             case 128 /* BooleanKeyword */:
34431             case 144 /* SymbolKeyword */:
34432             case 110 /* VoidKeyword */:
34433             case 155 /* TypeParameter */:
34434             case 158 /* PropertySignature */:
34435             case 160 /* MethodSignature */:
34436             case 165 /* CallSignature */:
34437             case 166 /* ConstructSignature */:
34438             case 167 /* IndexSignature */:
34439             case 246 /* InterfaceDeclaration */:
34440             case 247 /* TypeAliasDeclaration */:
34441                 return -2 /* TypeExcludes */;
34442             case 193 /* ObjectLiteralExpression */:
34443                 return 536922112 /* ObjectLiteralExcludes */;
34444             case 280 /* CatchClause */:
34445                 return 536887296 /* CatchClauseExcludes */;
34446             case 189 /* ObjectBindingPattern */:
34447             case 190 /* ArrayBindingPattern */:
34448                 return 536879104 /* BindingPatternExcludes */;
34449             case 199 /* TypeAssertionExpression */:
34450             case 217 /* AsExpression */:
34451             case 326 /* PartiallyEmittedExpression */:
34452             case 200 /* ParenthesizedExpression */:
34453             case 102 /* SuperKeyword */:
34454                 return 536870912 /* OuterExpressionExcludes */;
34455             case 194 /* PropertyAccessExpression */:
34456             case 195 /* ElementAccessExpression */:
34457                 return 536870912 /* PropertyAccessExcludes */;
34458             default:
34459                 return 536870912 /* NodeExcludes */;
34460         }
34461     }
34462     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
34463     /**
34464      * "Binds" JSDoc nodes in TypeScript code.
34465      * Since we will never create symbols for JSDoc, we just set parent pointers instead.
34466      */
34467     function setParentPointers(parent, child) {
34468         child.parent = parent;
34469         ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
34470     }
34471 })(ts || (ts = {}));
34472 /** @internal */
34473 var ts;
34474 (function (ts) {
34475     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
34476         return getSymbolWalker;
34477         function getSymbolWalker(accept) {
34478             if (accept === void 0) { accept = function () { return true; }; }
34479             var visitedTypes = []; // Sparse array from id to type
34480             var visitedSymbols = []; // Sparse array from id to symbol
34481             return {
34482                 walkType: function (type) {
34483                     try {
34484                         visitType(type);
34485                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34486                     }
34487                     finally {
34488                         ts.clear(visitedTypes);
34489                         ts.clear(visitedSymbols);
34490                     }
34491                 },
34492                 walkSymbol: function (symbol) {
34493                     try {
34494                         visitSymbol(symbol);
34495                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34496                     }
34497                     finally {
34498                         ts.clear(visitedTypes);
34499                         ts.clear(visitedSymbols);
34500                     }
34501                 },
34502             };
34503             function visitType(type) {
34504                 if (!type) {
34505                     return;
34506                 }
34507                 if (visitedTypes[type.id]) {
34508                     return;
34509                 }
34510                 visitedTypes[type.id] = type;
34511                 // Reuse visitSymbol to visit the type's symbol,
34512                 //  but be sure to bail on recuring into the type if accept declines the symbol.
34513                 var shouldBail = visitSymbol(type.symbol);
34514                 if (shouldBail)
34515                     return;
34516                 // Visit the type's related types, if any
34517                 if (type.flags & 524288 /* Object */) {
34518                     var objectType = type;
34519                     var objectFlags = objectType.objectFlags;
34520                     if (objectFlags & 4 /* Reference */) {
34521                         visitTypeReference(type);
34522                     }
34523                     if (objectFlags & 32 /* Mapped */) {
34524                         visitMappedType(type);
34525                     }
34526                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
34527                         visitInterfaceType(type);
34528                     }
34529                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
34530                         visitObjectType(objectType);
34531                     }
34532                 }
34533                 if (type.flags & 262144 /* TypeParameter */) {
34534                     visitTypeParameter(type);
34535                 }
34536                 if (type.flags & 3145728 /* UnionOrIntersection */) {
34537                     visitUnionOrIntersectionType(type);
34538                 }
34539                 if (type.flags & 4194304 /* Index */) {
34540                     visitIndexType(type);
34541                 }
34542                 if (type.flags & 8388608 /* IndexedAccess */) {
34543                     visitIndexedAccessType(type);
34544                 }
34545             }
34546             function visitTypeReference(type) {
34547                 visitType(type.target);
34548                 ts.forEach(getTypeArguments(type), visitType);
34549             }
34550             function visitTypeParameter(type) {
34551                 visitType(getConstraintOfTypeParameter(type));
34552             }
34553             function visitUnionOrIntersectionType(type) {
34554                 ts.forEach(type.types, visitType);
34555             }
34556             function visitIndexType(type) {
34557                 visitType(type.type);
34558             }
34559             function visitIndexedAccessType(type) {
34560                 visitType(type.objectType);
34561                 visitType(type.indexType);
34562                 visitType(type.constraint);
34563             }
34564             function visitMappedType(type) {
34565                 visitType(type.typeParameter);
34566                 visitType(type.constraintType);
34567                 visitType(type.templateType);
34568                 visitType(type.modifiersType);
34569             }
34570             function visitSignature(signature) {
34571                 var typePredicate = getTypePredicateOfSignature(signature);
34572                 if (typePredicate) {
34573                     visitType(typePredicate.type);
34574                 }
34575                 ts.forEach(signature.typeParameters, visitType);
34576                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
34577                     var parameter = _a[_i];
34578                     visitSymbol(parameter);
34579                 }
34580                 visitType(getRestTypeOfSignature(signature));
34581                 visitType(getReturnTypeOfSignature(signature));
34582             }
34583             function visitInterfaceType(interfaceT) {
34584                 visitObjectType(interfaceT);
34585                 ts.forEach(interfaceT.typeParameters, visitType);
34586                 ts.forEach(getBaseTypes(interfaceT), visitType);
34587                 visitType(interfaceT.thisType);
34588             }
34589             function visitObjectType(type) {
34590                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
34591                 visitType(stringIndexType);
34592                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
34593                 visitType(numberIndexType);
34594                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
34595                 var resolved = resolveStructuredTypeMembers(type);
34596                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
34597                     var signature = _a[_i];
34598                     visitSignature(signature);
34599                 }
34600                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
34601                     var signature = _c[_b];
34602                     visitSignature(signature);
34603                 }
34604                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
34605                     var p = _e[_d];
34606                     visitSymbol(p);
34607                 }
34608             }
34609             function visitSymbol(symbol) {
34610                 if (!symbol) {
34611                     return false;
34612                 }
34613                 var symbolId = ts.getSymbolId(symbol);
34614                 if (visitedSymbols[symbolId]) {
34615                     return false;
34616                 }
34617                 visitedSymbols[symbolId] = symbol;
34618                 if (!accept(symbol)) {
34619                     return true;
34620                 }
34621                 var t = getTypeOfSymbol(symbol);
34622                 visitType(t); // Should handle members on classes and such
34623                 if (symbol.exports) {
34624                     symbol.exports.forEach(visitSymbol);
34625                 }
34626                 ts.forEach(symbol.declarations, function (d) {
34627                     // Type queries are too far resolved when we just visit the symbol's type
34628                     //  (their type resolved directly to the member deeply referenced)
34629                     // So to get the intervening symbols, we need to check if there's a type
34630                     // query node on any of the symbol's declarations and get symbols there
34631                     if (d.type && d.type.kind === 172 /* TypeQuery */) {
34632                         var query = d.type;
34633                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
34634                         visitSymbol(entity);
34635                     }
34636                 });
34637                 return false;
34638             }
34639         }
34640     }
34641     ts.createGetSymbolWalker = createGetSymbolWalker;
34642 })(ts || (ts = {}));
34643 /* @internal */
34644 var ts;
34645 (function (ts) {
34646     var ambientModuleSymbolRegex = /^".+"$/;
34647     var anon = "(anonymous)";
34648     var nextSymbolId = 1;
34649     var nextNodeId = 1;
34650     var nextMergeId = 1;
34651     var nextFlowId = 1;
34652     var IterationUse;
34653     (function (IterationUse) {
34654         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
34655         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
34656         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
34657         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
34658         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
34659         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
34660         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
34661         // Spread, Destructuring, Array element assignment
34662         IterationUse[IterationUse["Element"] = 1] = "Element";
34663         IterationUse[IterationUse["Spread"] = 33] = "Spread";
34664         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
34665         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
34666         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
34667         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
34668         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
34669         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
34670         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
34671     })(IterationUse || (IterationUse = {}));
34672     var IterationTypeKind;
34673     (function (IterationTypeKind) {
34674         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
34675         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
34676         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
34677     })(IterationTypeKind || (IterationTypeKind = {}));
34678     var WideningKind;
34679     (function (WideningKind) {
34680         WideningKind[WideningKind["Normal"] = 0] = "Normal";
34681         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
34682         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
34683         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
34684     })(WideningKind || (WideningKind = {}));
34685     var TypeFacts;
34686     (function (TypeFacts) {
34687         TypeFacts[TypeFacts["None"] = 0] = "None";
34688         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
34689         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
34690         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
34691         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
34692         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
34693         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
34694         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
34695         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
34696         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
34697         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
34698         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
34699         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
34700         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
34701         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
34702         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
34703         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
34704         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
34705         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
34706         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
34707         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
34708         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
34709         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
34710         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
34711         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
34712         TypeFacts[TypeFacts["All"] = 16777215] = "All";
34713         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
34714         // The presence of a particular fact means that the given test is true for some (and possibly all) values
34715         // of that kind of type.
34716         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
34717         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
34718         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
34719         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
34720         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
34721         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
34722         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
34723         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
34724         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
34725         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
34726         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
34727         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
34728         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
34729         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
34730         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
34731         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
34732         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
34733         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
34734         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
34735         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
34736         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
34737         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
34738         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
34739         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
34740         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
34741         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
34742         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
34743         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
34744         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
34745         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
34746         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
34747         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
34748         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
34749         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
34750         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
34751         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
34752         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
34753         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
34754         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
34755         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
34756         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
34757         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
34758     })(TypeFacts || (TypeFacts = {}));
34759     var typeofEQFacts = ts.createMapFromTemplate({
34760         string: 1 /* TypeofEQString */,
34761         number: 2 /* TypeofEQNumber */,
34762         bigint: 4 /* TypeofEQBigInt */,
34763         boolean: 8 /* TypeofEQBoolean */,
34764         symbol: 16 /* TypeofEQSymbol */,
34765         undefined: 65536 /* EQUndefined */,
34766         object: 32 /* TypeofEQObject */,
34767         function: 64 /* TypeofEQFunction */
34768     });
34769     var typeofNEFacts = ts.createMapFromTemplate({
34770         string: 256 /* TypeofNEString */,
34771         number: 512 /* TypeofNENumber */,
34772         bigint: 1024 /* TypeofNEBigInt */,
34773         boolean: 2048 /* TypeofNEBoolean */,
34774         symbol: 4096 /* TypeofNESymbol */,
34775         undefined: 524288 /* NEUndefined */,
34776         object: 8192 /* TypeofNEObject */,
34777         function: 16384 /* TypeofNEFunction */
34778     });
34779     var TypeSystemPropertyName;
34780     (function (TypeSystemPropertyName) {
34781         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
34782         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
34783         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
34784         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
34785         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
34786         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
34787         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
34788     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
34789     var CheckMode;
34790     (function (CheckMode) {
34791         CheckMode[CheckMode["Normal"] = 0] = "Normal";
34792         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
34793         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
34794         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
34795         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
34796         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
34797     })(CheckMode || (CheckMode = {}));
34798     var AccessFlags;
34799     (function (AccessFlags) {
34800         AccessFlags[AccessFlags["None"] = 0] = "None";
34801         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
34802         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
34803         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
34804         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
34805     })(AccessFlags || (AccessFlags = {}));
34806     var SignatureCheckMode;
34807     (function (SignatureCheckMode) {
34808         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
34809         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
34810         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
34811         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
34812         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
34813     })(SignatureCheckMode || (SignatureCheckMode = {}));
34814     var IntersectionState;
34815     (function (IntersectionState) {
34816         IntersectionState[IntersectionState["None"] = 0] = "None";
34817         IntersectionState[IntersectionState["Source"] = 1] = "Source";
34818         IntersectionState[IntersectionState["Target"] = 2] = "Target";
34819         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
34820         IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
34821     })(IntersectionState || (IntersectionState = {}));
34822     var MappedTypeModifiers;
34823     (function (MappedTypeModifiers) {
34824         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
34825         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
34826         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
34827         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
34828     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
34829     var ExpandingFlags;
34830     (function (ExpandingFlags) {
34831         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
34832         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
34833         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
34834         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
34835     })(ExpandingFlags || (ExpandingFlags = {}));
34836     var MembersOrExportsResolutionKind;
34837     (function (MembersOrExportsResolutionKind) {
34838         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
34839         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
34840     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
34841     var UnusedKind;
34842     (function (UnusedKind) {
34843         UnusedKind[UnusedKind["Local"] = 0] = "Local";
34844         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
34845     })(UnusedKind || (UnusedKind = {}));
34846     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
34847     var DeclarationMeaning;
34848     (function (DeclarationMeaning) {
34849         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
34850         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
34851         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
34852         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
34853         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
34854         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
34855     })(DeclarationMeaning || (DeclarationMeaning = {}));
34856     var DeclarationSpaces;
34857     (function (DeclarationSpaces) {
34858         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
34859         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
34860         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
34861         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
34862     })(DeclarationSpaces || (DeclarationSpaces = {}));
34863     function SymbolLinks() {
34864     }
34865     function NodeLinks() {
34866         this.flags = 0;
34867     }
34868     function getNodeId(node) {
34869         if (!node.id) {
34870             node.id = nextNodeId;
34871             nextNodeId++;
34872         }
34873         return node.id;
34874     }
34875     ts.getNodeId = getNodeId;
34876     function getSymbolId(symbol) {
34877         if (!symbol.id) {
34878             symbol.id = nextSymbolId;
34879             nextSymbolId++;
34880         }
34881         return symbol.id;
34882     }
34883     ts.getSymbolId = getSymbolId;
34884     function isInstantiatedModule(node, preserveConstEnums) {
34885         var moduleState = ts.getModuleInstanceState(node);
34886         return moduleState === 1 /* Instantiated */ ||
34887             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
34888     }
34889     ts.isInstantiatedModule = isInstantiatedModule;
34890     function createTypeChecker(host, produceDiagnostics) {
34891         var getPackagesSet = ts.memoize(function () {
34892             var set = ts.createMap();
34893             host.getSourceFiles().forEach(function (sf) {
34894                 if (!sf.resolvedModules)
34895                     return;
34896                 ts.forEachEntry(sf.resolvedModules, function (r) {
34897                     if (r && r.packageId)
34898                         set.set(r.packageId.name, true);
34899                 });
34900             });
34901             return set;
34902         });
34903         // Cancellation that controls whether or not we can cancel in the middle of type checking.
34904         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
34905         // computing something, and we will leave our internals in an inconsistent state.  Callers
34906         // who set the cancellation token should catch if a cancellation exception occurs, and
34907         // should throw away and create a new TypeChecker.
34908         //
34909         // Currently we only support setting the cancellation token when getting diagnostics.  This
34910         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
34911         // they no longer need the information (for example, if the user started editing again).
34912         var cancellationToken;
34913         var requestedExternalEmitHelpers;
34914         var externalHelpersModule;
34915         var Symbol = ts.objectAllocator.getSymbolConstructor();
34916         var Type = ts.objectAllocator.getTypeConstructor();
34917         var Signature = ts.objectAllocator.getSignatureConstructor();
34918         var typeCount = 0;
34919         var symbolCount = 0;
34920         var enumCount = 0;
34921         var totalInstantiationCount = 0;
34922         var instantiationCount = 0;
34923         var instantiationDepth = 0;
34924         var constraintDepth = 0;
34925         var currentNode;
34926         var emptySymbols = ts.createSymbolTable();
34927         var arrayVariances = [1 /* Covariant */];
34928         var compilerOptions = host.getCompilerOptions();
34929         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
34930         var moduleKind = ts.getEmitModuleKind(compilerOptions);
34931         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
34932         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
34933         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
34934         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
34935         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
34936         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
34937         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
34938         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
34939         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
34940         var emitResolver = createResolver();
34941         var nodeBuilder = createNodeBuilder();
34942         var globals = ts.createSymbolTable();
34943         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
34944         undefinedSymbol.declarations = [];
34945         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
34946         globalThisSymbol.exports = globals;
34947         globalThisSymbol.declarations = [];
34948         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
34949         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
34950         var requireSymbol = createSymbol(4 /* Property */, "require");
34951         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
34952         var apparentArgumentCount;
34953         // for public members that accept a Node or one of its subtypes, we must guard against
34954         // synthetic nodes created during transformations by calling `getParseTreeNode`.
34955         // for most of these, we perform the guard only on `checker` to avoid any possible
34956         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
34957         // checker.
34958         var checker = {
34959             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
34960             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
34961             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
34962             getTypeCount: function () { return typeCount; },
34963             getInstantiationCount: function () { return totalInstantiationCount; },
34964             getRelationCacheSizes: function () { return ({
34965                 assignable: assignableRelation.size,
34966                 identity: identityRelation.size,
34967                 subtype: subtypeRelation.size,
34968                 strictSubtype: strictSubtypeRelation.size,
34969             }); },
34970             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
34971             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
34972             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
34973             getMergedSymbol: getMergedSymbol,
34974             getDiagnostics: getDiagnostics,
34975             getGlobalDiagnostics: getGlobalDiagnostics,
34976             getTypeOfSymbolAtLocation: function (symbol, location) {
34977                 location = ts.getParseTreeNode(location);
34978                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
34979             },
34980             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
34981                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
34982                 if (parameter === undefined)
34983                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
34984                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
34985             },
34986             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
34987             getPropertiesOfType: getPropertiesOfType,
34988             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34989             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
34990                 var node = ts.getParseTreeNode(location);
34991                 if (!node) {
34992                     return undefined;
34993                 }
34994                 var propName = ts.escapeLeadingUnderscores(name);
34995                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
34996                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
34997             },
34998             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34999             getIndexInfoOfType: getIndexInfoOfType,
35000             getSignaturesOfType: getSignaturesOfType,
35001             getIndexTypeOfType: getIndexTypeOfType,
35002             getBaseTypes: getBaseTypes,
35003             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
35004             getWidenedType: getWidenedType,
35005             getTypeFromTypeNode: function (nodeIn) {
35006                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35007                 return node ? getTypeFromTypeNode(node) : errorType;
35008             },
35009             getParameterType: getTypeAtPosition,
35010             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
35011             getReturnTypeOfSignature: getReturnTypeOfSignature,
35012             isNullableType: isNullableType,
35013             getNullableType: getNullableType,
35014             getNonNullableType: getNonNullableType,
35015             getNonOptionalType: removeOptionalTypeMarker,
35016             getTypeArguments: getTypeArguments,
35017             typeToTypeNode: nodeBuilder.typeToTypeNode,
35018             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
35019             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
35020             symbolToEntityName: nodeBuilder.symbolToEntityName,
35021             symbolToExpression: nodeBuilder.symbolToExpression,
35022             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
35023             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
35024             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
35025             getSymbolsInScope: function (location, meaning) {
35026                 location = ts.getParseTreeNode(location);
35027                 return location ? getSymbolsInScope(location, meaning) : [];
35028             },
35029             getSymbolAtLocation: function (node) {
35030                 node = ts.getParseTreeNode(node);
35031                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
35032                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
35033             },
35034             getShorthandAssignmentValueSymbol: function (node) {
35035                 node = ts.getParseTreeNode(node);
35036                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
35037             },
35038             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
35039                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
35040                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
35041             },
35042             getExportSymbolOfSymbol: function (symbol) {
35043                 return getMergedSymbol(symbol.exportSymbol || symbol);
35044             },
35045             getTypeAtLocation: function (node) {
35046                 node = ts.getParseTreeNode(node);
35047                 return node ? getTypeOfNode(node) : errorType;
35048             },
35049             getTypeOfAssignmentPattern: function (nodeIn) {
35050                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
35051                 return node && getTypeOfAssignmentPattern(node) || errorType;
35052             },
35053             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
35054                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
35055                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
35056             },
35057             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
35058                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
35059             },
35060             typeToString: function (type, enclosingDeclaration, flags) {
35061                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
35062             },
35063             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
35064                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
35065             },
35066             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
35067                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
35068             },
35069             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
35070                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
35071             },
35072             writeType: function (type, enclosingDeclaration, flags, writer) {
35073                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35074             },
35075             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
35076                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
35077             },
35078             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
35079                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35080             },
35081             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
35082             getRootSymbols: getRootSymbols,
35083             getContextualType: function (nodeIn, contextFlags) {
35084                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
35085                 if (!node) {
35086                     return undefined;
35087                 }
35088                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
35089                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
35090                 if (contextFlags & 4 /* Completions */ && containingCall) {
35091                     var toMarkSkip = node;
35092                     do {
35093                         getNodeLinks(toMarkSkip).skipDirectInference = true;
35094                         toMarkSkip = toMarkSkip.parent;
35095                     } while (toMarkSkip && toMarkSkip !== containingCall);
35096                     getNodeLinks(containingCall).resolvedSignature = undefined;
35097                 }
35098                 var result = getContextualType(node, contextFlags);
35099                 if (contextFlags & 4 /* Completions */ && containingCall) {
35100                     var toMarkSkip = node;
35101                     do {
35102                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
35103                         toMarkSkip = toMarkSkip.parent;
35104                     } while (toMarkSkip && toMarkSkip !== containingCall);
35105                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
35106                 }
35107                 return result;
35108             },
35109             getContextualTypeForObjectLiteralElement: function (nodeIn) {
35110                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
35111                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
35112             },
35113             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
35114                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35115                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
35116             },
35117             getContextualTypeForJsxAttribute: function (nodeIn) {
35118                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
35119                 return node && getContextualTypeForJsxAttribute(node);
35120             },
35121             isContextSensitive: isContextSensitive,
35122             getFullyQualifiedName: getFullyQualifiedName,
35123             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
35124                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
35125             },
35126             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
35127                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
35128             },
35129             getExpandedParameters: getExpandedParameters,
35130             hasEffectiveRestParameter: hasEffectiveRestParameter,
35131             getConstantValue: function (nodeIn) {
35132                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
35133                 return node ? getConstantValue(node) : undefined;
35134             },
35135             isValidPropertyAccess: function (nodeIn, propertyName) {
35136                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
35137                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
35138             },
35139             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
35140                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
35141                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
35142             },
35143             getSignatureFromDeclaration: function (declarationIn) {
35144                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
35145                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
35146             },
35147             isImplementationOfOverload: function (node) {
35148                 var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
35149                 return parsed ? isImplementationOfOverload(parsed) : undefined;
35150             },
35151             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
35152             getAliasedSymbol: resolveAlias,
35153             getEmitResolver: getEmitResolver,
35154             getExportsOfModule: getExportsOfModuleAsArray,
35155             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
35156             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
35157             getAmbientModules: getAmbientModules,
35158             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
35159             isOptionalParameter: function (nodeIn) {
35160                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
35161                 return node ? isOptionalParameter(node) : false;
35162             },
35163             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
35164             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
35165             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
35166                 // we deliberately exclude augmentations
35167                 // since we are only interested in declarations of the module itself
35168                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
35169             },
35170             getApparentType: getApparentType,
35171             getUnionType: getUnionType,
35172             isTypeAssignableTo: isTypeAssignableTo,
35173             createAnonymousType: createAnonymousType,
35174             createSignature: createSignature,
35175             createSymbol: createSymbol,
35176             createIndexInfo: createIndexInfo,
35177             getAnyType: function () { return anyType; },
35178             getStringType: function () { return stringType; },
35179             getNumberType: function () { return numberType; },
35180             createPromiseType: createPromiseType,
35181             createArrayType: createArrayType,
35182             getElementTypeOfArrayType: getElementTypeOfArrayType,
35183             getBooleanType: function () { return booleanType; },
35184             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
35185             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
35186             getVoidType: function () { return voidType; },
35187             getUndefinedType: function () { return undefinedType; },
35188             getNullType: function () { return nullType; },
35189             getESSymbolType: function () { return esSymbolType; },
35190             getNeverType: function () { return neverType; },
35191             getOptionalType: function () { return optionalType; },
35192             isSymbolAccessible: isSymbolAccessible,
35193             isArrayType: isArrayType,
35194             isTupleType: isTupleType,
35195             isArrayLikeType: isArrayLikeType,
35196             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
35197             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
35198             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
35199             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
35200             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35201             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35202             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
35203             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
35204             getBaseConstraintOfType: getBaseConstraintOfType,
35205             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
35206             resolveName: function (name, location, meaning, excludeGlobals) {
35207                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
35208             },
35209             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
35210             getAccessibleSymbolChain: getAccessibleSymbolChain,
35211             getTypePredicateOfSignature: getTypePredicateOfSignature,
35212             resolveExternalModuleName: function (moduleSpecifier) {
35213                 return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
35214             },
35215             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
35216             tryGetThisTypeAt: function (node, includeGlobalThis) {
35217                 node = ts.getParseTreeNode(node);
35218                 return node && tryGetThisTypeAt(node, includeGlobalThis);
35219             },
35220             getTypeArgumentConstraint: function (nodeIn) {
35221                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35222                 return node && getTypeArgumentConstraint(node);
35223             },
35224             getSuggestionDiagnostics: function (file, ct) {
35225                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
35226                     return ts.emptyArray;
35227                 }
35228                 var diagnostics;
35229                 try {
35230                     // Record the cancellation token so it can be checked later on during checkSourceElement.
35231                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
35232                     // this call is done.
35233                     cancellationToken = ct;
35234                     // Ensure file is type checked
35235                     checkSourceFile(file);
35236                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
35237                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
35238                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
35239                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
35240                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
35241                         }
35242                     });
35243                     return diagnostics || ts.emptyArray;
35244                 }
35245                 finally {
35246                     cancellationToken = undefined;
35247                 }
35248             },
35249             runWithCancellationToken: function (token, callback) {
35250                 try {
35251                     cancellationToken = token;
35252                     return callback(checker);
35253                 }
35254                 finally {
35255                     cancellationToken = undefined;
35256                 }
35257             },
35258             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
35259             isDeclarationVisible: isDeclarationVisible,
35260         };
35261         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
35262             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35263             apparentArgumentCount = argumentCount;
35264             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
35265             apparentArgumentCount = undefined;
35266             return res;
35267         }
35268         var tupleTypes = ts.createMap();
35269         var unionTypes = ts.createMap();
35270         var intersectionTypes = ts.createMap();
35271         var literalTypes = ts.createMap();
35272         var indexedAccessTypes = ts.createMap();
35273         var substitutionTypes = ts.createMap();
35274         var evolvingArrayTypes = [];
35275         var undefinedProperties = ts.createMap();
35276         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
35277         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
35278         var anyType = createIntrinsicType(1 /* Any */, "any");
35279         var autoType = createIntrinsicType(1 /* Any */, "any");
35280         var wildcardType = createIntrinsicType(1 /* Any */, "any");
35281         var errorType = createIntrinsicType(1 /* Any */, "error");
35282         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
35283         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
35284         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
35285         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
35286         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
35287         var nullType = createIntrinsicType(65536 /* Null */, "null");
35288         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
35289         var stringType = createIntrinsicType(4 /* String */, "string");
35290         var numberType = createIntrinsicType(8 /* Number */, "number");
35291         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
35292         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35293         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35294         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35295         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35296         trueType.regularType = regularTrueType;
35297         trueType.freshType = trueType;
35298         regularTrueType.regularType = regularTrueType;
35299         regularTrueType.freshType = trueType;
35300         falseType.regularType = regularFalseType;
35301         falseType.freshType = falseType;
35302         regularFalseType.regularType = regularFalseType;
35303         regularFalseType.freshType = falseType;
35304         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
35305         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
35306         // (The union is cached, so simply doing the marking here is sufficient)
35307         createBooleanType([regularFalseType, trueType]);
35308         createBooleanType([falseType, regularTrueType]);
35309         createBooleanType([falseType, trueType]);
35310         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
35311         var voidType = createIntrinsicType(16384 /* Void */, "void");
35312         var neverType = createIntrinsicType(131072 /* Never */, "never");
35313         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
35314         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
35315         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
35316         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
35317         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
35318         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
35319         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
35320         var numberOrBigIntType = getUnionType([numberType, bigintType]);
35321         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
35322         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
35323         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35324         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35325         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
35326         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
35327         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
35328         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35329         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35330         emptyGenericType.instantiations = ts.createMap();
35331         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35332         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
35333         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
35334         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
35335         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35336         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35337         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35338         var markerSuperType = createTypeParameter();
35339         var markerSubType = createTypeParameter();
35340         markerSubType.constraint = markerSuperType;
35341         var markerOtherType = createTypeParameter();
35342         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
35343         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35344         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35345         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35346         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35347         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
35348         var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances
35349         var noIterationTypes = {
35350             get yieldType() { return ts.Debug.fail("Not supported"); },
35351             get returnType() { return ts.Debug.fail("Not supported"); },
35352             get nextType() { return ts.Debug.fail("Not supported"); },
35353         };
35354         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
35355         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
35356         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
35357         var asyncIterationTypesResolver = {
35358             iterableCacheKey: "iterationTypesOfAsyncIterable",
35359             iteratorCacheKey: "iterationTypesOfAsyncIterator",
35360             iteratorSymbolName: "asyncIterator",
35361             getGlobalIteratorType: getGlobalAsyncIteratorType,
35362             getGlobalIterableType: getGlobalAsyncIterableType,
35363             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
35364             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
35365             resolveIterationType: getAwaitedType,
35366             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
35367             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
35368             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property,
35369         };
35370         var syncIterationTypesResolver = {
35371             iterableCacheKey: "iterationTypesOfIterable",
35372             iteratorCacheKey: "iterationTypesOfIterator",
35373             iteratorSymbolName: "iterator",
35374             getGlobalIteratorType: getGlobalIteratorType,
35375             getGlobalIterableType: getGlobalIterableType,
35376             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
35377             getGlobalGeneratorType: getGlobalGeneratorType,
35378             resolveIterationType: function (type, _errorNode) { return type; },
35379             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
35380             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
35381             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
35382         };
35383         /** Key is "/path/to/a.ts|/path/to/b.ts". */
35384         var amalgamatedDuplicates;
35385         var reverseMappedCache = ts.createMap();
35386         var ambientModulesCache;
35387         /**
35388          * List of every ambient module with a "*" wildcard.
35389          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
35390          * This is only used if there is no exact match.
35391          */
35392         var patternAmbientModules;
35393         var patternAmbientModuleAugmentations;
35394         var globalObjectType;
35395         var globalFunctionType;
35396         var globalCallableFunctionType;
35397         var globalNewableFunctionType;
35398         var globalArrayType;
35399         var globalReadonlyArrayType;
35400         var globalStringType;
35401         var globalNumberType;
35402         var globalBooleanType;
35403         var globalRegExpType;
35404         var globalThisType;
35405         var anyArrayType;
35406         var autoArrayType;
35407         var anyReadonlyArrayType;
35408         var deferredGlobalNonNullableTypeAlias;
35409         // The library files are only loaded when the feature is used.
35410         // This allows users to just specify library files they want to used through --lib
35411         // and they will not get an error from not having unrelated library files
35412         var deferredGlobalESSymbolConstructorSymbol;
35413         var deferredGlobalESSymbolType;
35414         var deferredGlobalTypedPropertyDescriptorType;
35415         var deferredGlobalPromiseType;
35416         var deferredGlobalPromiseLikeType;
35417         var deferredGlobalPromiseConstructorSymbol;
35418         var deferredGlobalPromiseConstructorLikeType;
35419         var deferredGlobalIterableType;
35420         var deferredGlobalIteratorType;
35421         var deferredGlobalIterableIteratorType;
35422         var deferredGlobalGeneratorType;
35423         var deferredGlobalIteratorYieldResultType;
35424         var deferredGlobalIteratorReturnResultType;
35425         var deferredGlobalAsyncIterableType;
35426         var deferredGlobalAsyncIteratorType;
35427         var deferredGlobalAsyncIterableIteratorType;
35428         var deferredGlobalAsyncGeneratorType;
35429         var deferredGlobalTemplateStringsArrayType;
35430         var deferredGlobalImportMetaType;
35431         var deferredGlobalExtractSymbol;
35432         var deferredGlobalOmitSymbol;
35433         var deferredGlobalBigIntType;
35434         var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
35435         var flowLoopStart = 0;
35436         var flowLoopCount = 0;
35437         var sharedFlowCount = 0;
35438         var flowAnalysisDisabled = false;
35439         var flowInvocationCount = 0;
35440         var lastFlowNode;
35441         var lastFlowNodeReachable;
35442         var flowTypeCache;
35443         var emptyStringType = getLiteralType("");
35444         var zeroType = getLiteralType(0);
35445         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
35446         var resolutionTargets = [];
35447         var resolutionResults = [];
35448         var resolutionPropertyNames = [];
35449         var suggestionCount = 0;
35450         var maximumSuggestionCount = 10;
35451         var mergedSymbols = [];
35452         var symbolLinks = [];
35453         var nodeLinks = [];
35454         var flowLoopCaches = [];
35455         var flowLoopNodes = [];
35456         var flowLoopKeys = [];
35457         var flowLoopTypes = [];
35458         var sharedFlowNodes = [];
35459         var sharedFlowTypes = [];
35460         var flowNodeReachable = [];
35461         var potentialThisCollisions = [];
35462         var potentialNewTargetCollisions = [];
35463         var potentialWeakMapCollisions = [];
35464         var awaitedTypeStack = [];
35465         var diagnostics = ts.createDiagnosticCollection();
35466         var suggestionDiagnostics = ts.createDiagnosticCollection();
35467         var typeofTypesByName = ts.createMapFromTemplate({
35468             string: stringType,
35469             number: numberType,
35470             bigint: bigintType,
35471             boolean: booleanType,
35472             symbol: esSymbolType,
35473             undefined: undefinedType
35474         });
35475         var typeofType = createTypeofType();
35476         var _jsxNamespace;
35477         var _jsxFactoryEntity;
35478         var outofbandVarianceMarkerHandler;
35479         var subtypeRelation = ts.createMap();
35480         var strictSubtypeRelation = ts.createMap();
35481         var assignableRelation = ts.createMap();
35482         var comparableRelation = ts.createMap();
35483         var identityRelation = ts.createMap();
35484         var enumRelation = ts.createMap();
35485         var builtinGlobals = ts.createSymbolTable();
35486         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
35487         initializeTypeChecker();
35488         return checker;
35489         function getJsxNamespace(location) {
35490             if (location) {
35491                 var file = ts.getSourceFileOfNode(location);
35492                 if (file) {
35493                     if (file.localJsxNamespace) {
35494                         return file.localJsxNamespace;
35495                     }
35496                     var jsxPragma = file.pragmas.get("jsx");
35497                     if (jsxPragma) {
35498                         var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
35499                         file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
35500                         ts.visitNode(file.localJsxFactory, markAsSynthetic);
35501                         if (file.localJsxFactory) {
35502                             return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
35503                         }
35504                     }
35505                 }
35506             }
35507             if (!_jsxNamespace) {
35508                 _jsxNamespace = "React";
35509                 if (compilerOptions.jsxFactory) {
35510                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
35511                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
35512                     if (_jsxFactoryEntity) {
35513                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
35514                     }
35515                 }
35516                 else if (compilerOptions.reactNamespace) {
35517                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
35518                 }
35519             }
35520             if (!_jsxFactoryEntity) {
35521                 _jsxFactoryEntity = ts.createQualifiedName(ts.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
35522             }
35523             return _jsxNamespace;
35524             function markAsSynthetic(node) {
35525                 node.pos = -1;
35526                 node.end = -1;
35527                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
35528             }
35529         }
35530         function getEmitResolver(sourceFile, cancellationToken) {
35531             // Ensure we have all the type information in place for this file so that all the
35532             // emitter questions of this resolver will return the right information.
35533             getDiagnostics(sourceFile, cancellationToken);
35534             return emitResolver;
35535         }
35536         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
35537             var diagnostic = location
35538                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35539                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35540             var existing = diagnostics.lookup(diagnostic);
35541             if (existing) {
35542                 return existing;
35543             }
35544             else {
35545                 diagnostics.add(diagnostic);
35546                 return diagnostic;
35547             }
35548         }
35549         function error(location, message, arg0, arg1, arg2, arg3) {
35550             var diagnostic = location
35551                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35552                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35553             diagnostics.add(diagnostic);
35554             return diagnostic;
35555         }
35556         function addErrorOrSuggestion(isError, diagnostic) {
35557             if (isError) {
35558                 diagnostics.add(diagnostic);
35559             }
35560             else {
35561                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
35562             }
35563         }
35564         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
35565             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
35566         }
35567         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
35568             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
35569             if (maybeMissingAwait) {
35570                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
35571                 ts.addRelatedInfo(diagnostic, related);
35572             }
35573             return diagnostic;
35574         }
35575         function createSymbol(flags, name, checkFlags) {
35576             symbolCount++;
35577             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
35578             symbol.checkFlags = checkFlags || 0;
35579             return symbol;
35580         }
35581         function getExcludedSymbolFlags(flags) {
35582             var result = 0;
35583             if (flags & 2 /* BlockScopedVariable */)
35584                 result |= 111551 /* BlockScopedVariableExcludes */;
35585             if (flags & 1 /* FunctionScopedVariable */)
35586                 result |= 111550 /* FunctionScopedVariableExcludes */;
35587             if (flags & 4 /* Property */)
35588                 result |= 0 /* PropertyExcludes */;
35589             if (flags & 8 /* EnumMember */)
35590                 result |= 900095 /* EnumMemberExcludes */;
35591             if (flags & 16 /* Function */)
35592                 result |= 110991 /* FunctionExcludes */;
35593             if (flags & 32 /* Class */)
35594                 result |= 899503 /* ClassExcludes */;
35595             if (flags & 64 /* Interface */)
35596                 result |= 788872 /* InterfaceExcludes */;
35597             if (flags & 256 /* RegularEnum */)
35598                 result |= 899327 /* RegularEnumExcludes */;
35599             if (flags & 128 /* ConstEnum */)
35600                 result |= 899967 /* ConstEnumExcludes */;
35601             if (flags & 512 /* ValueModule */)
35602                 result |= 110735 /* ValueModuleExcludes */;
35603             if (flags & 8192 /* Method */)
35604                 result |= 103359 /* MethodExcludes */;
35605             if (flags & 32768 /* GetAccessor */)
35606                 result |= 46015 /* GetAccessorExcludes */;
35607             if (flags & 65536 /* SetAccessor */)
35608                 result |= 78783 /* SetAccessorExcludes */;
35609             if (flags & 262144 /* TypeParameter */)
35610                 result |= 526824 /* TypeParameterExcludes */;
35611             if (flags & 524288 /* TypeAlias */)
35612                 result |= 788968 /* TypeAliasExcludes */;
35613             if (flags & 2097152 /* Alias */)
35614                 result |= 2097152 /* AliasExcludes */;
35615             return result;
35616         }
35617         function recordMergedSymbol(target, source) {
35618             if (!source.mergeId) {
35619                 source.mergeId = nextMergeId;
35620                 nextMergeId++;
35621             }
35622             mergedSymbols[source.mergeId] = target;
35623         }
35624         function cloneSymbol(symbol) {
35625             var result = createSymbol(symbol.flags, symbol.escapedName);
35626             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
35627             result.parent = symbol.parent;
35628             if (symbol.valueDeclaration)
35629                 result.valueDeclaration = symbol.valueDeclaration;
35630             if (symbol.constEnumOnlyModule)
35631                 result.constEnumOnlyModule = true;
35632             if (symbol.members)
35633                 result.members = ts.cloneMap(symbol.members);
35634             if (symbol.exports)
35635                 result.exports = ts.cloneMap(symbol.exports);
35636             recordMergedSymbol(result, symbol);
35637             return result;
35638         }
35639         /**
35640          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
35641          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
35642          */
35643         function mergeSymbol(target, source, unidirectional) {
35644             if (unidirectional === void 0) { unidirectional = false; }
35645             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
35646                 (source.flags | target.flags) & 67108864 /* Assignment */) {
35647                 if (source === target) {
35648                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
35649                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
35650                     return target;
35651                 }
35652                 if (!(target.flags & 33554432 /* Transient */)) {
35653                     var resolvedTarget = resolveSymbol(target);
35654                     if (resolvedTarget === unknownSymbol) {
35655                         return source;
35656                     }
35657                     target = cloneSymbol(resolvedTarget);
35658                 }
35659                 // Javascript static-property-assignment declarations always merge, even though they are also values
35660                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
35661                     // reset flag when merging instantiated module into value module that has only const enums
35662                     target.constEnumOnlyModule = false;
35663                 }
35664                 target.flags |= source.flags;
35665                 if (source.valueDeclaration) {
35666                     ts.setValueDeclaration(target, source.valueDeclaration);
35667                 }
35668                 ts.addRange(target.declarations, source.declarations);
35669                 if (source.members) {
35670                     if (!target.members)
35671                         target.members = ts.createSymbolTable();
35672                     mergeSymbolTable(target.members, source.members, unidirectional);
35673                 }
35674                 if (source.exports) {
35675                     if (!target.exports)
35676                         target.exports = ts.createSymbolTable();
35677                     mergeSymbolTable(target.exports, source.exports, unidirectional);
35678                 }
35679                 if (!unidirectional) {
35680                     recordMergedSymbol(target, source);
35681                 }
35682             }
35683             else if (target.flags & 1024 /* NamespaceModule */) {
35684                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
35685                 // as we will already report a "Declaration name conflicts..." error, and this error
35686                 // won't make much sense.
35687                 if (target !== globalThisSymbol) {
35688                     error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target));
35689                 }
35690             }
35691             else { // error
35692                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
35693                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
35694                 var message = isEitherEnum
35695                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
35696                     : isEitherBlockScoped_1
35697                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
35698                         : ts.Diagnostics.Duplicate_identifier_0;
35699                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
35700                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
35701                 var symbolName_1 = symbolToString(source);
35702                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
35703                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
35704                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
35705                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
35706                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
35707                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
35708                     });
35709                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
35710                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
35711                     });
35712                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
35713                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
35714                 }
35715                 else {
35716                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
35717                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
35718                 }
35719             }
35720             return target;
35721             function addDuplicateLocations(locs, symbol) {
35722                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
35723                     var decl = _a[_i];
35724                     ts.pushIfUnique(locs, decl);
35725                 }
35726             }
35727         }
35728         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
35729             ts.forEach(target.declarations, function (node) {
35730                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
35731             });
35732         }
35733         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
35734             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
35735             var err = lookupOrIssueError(errorNode, message, symbolName);
35736             var _loop_6 = function (relatedNode) {
35737                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
35738                 if (adjustedNode === errorNode)
35739                     return "continue";
35740                 err.relatedInformation = err.relatedInformation || [];
35741                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
35742                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
35743                 if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; }))
35744                     return "continue";
35745                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
35746             };
35747             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
35748                 var relatedNode = _a[_i];
35749                 _loop_6(relatedNode);
35750             }
35751         }
35752         function combineSymbolTables(first, second) {
35753             if (!ts.hasEntries(first))
35754                 return second;
35755             if (!ts.hasEntries(second))
35756                 return first;
35757             var combined = ts.createSymbolTable();
35758             mergeSymbolTable(combined, first);
35759             mergeSymbolTable(combined, second);
35760             return combined;
35761         }
35762         function mergeSymbolTable(target, source, unidirectional) {
35763             if (unidirectional === void 0) { unidirectional = false; }
35764             source.forEach(function (sourceSymbol, id) {
35765                 var targetSymbol = target.get(id);
35766                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
35767             });
35768         }
35769         function mergeModuleAugmentation(moduleName) {
35770             var _a, _b;
35771             var moduleAugmentation = moduleName.parent;
35772             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
35773                 // this is a combined symbol for multiple augmentations within the same file.
35774                 // its symbol already has accumulated information for all declarations
35775                 // so we need to add it just once - do the work only for first declaration
35776                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
35777                 return;
35778             }
35779             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
35780                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
35781             }
35782             else {
35783                 // find a module that about to be augmented
35784                 // do not validate names of augmentations that are defined in ambient context
35785                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
35786                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
35787                     : undefined;
35788                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
35789                 if (!mainModule_1) {
35790                     return;
35791                 }
35792                 // obtain item referenced by 'export='
35793                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
35794                 if (mainModule_1.flags & 1920 /* Namespace */) {
35795                     // If we're merging an augmentation to a pattern ambient module, we want to
35796                     // perform the merge unidirectionally from the augmentation ('a.foo') to
35797                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
35798                     // all the exports both from the pattern and from the augmentation, but
35799                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
35800                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
35801                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
35802                         if (!patternAmbientModuleAugmentations) {
35803                             patternAmbientModuleAugmentations = ts.createMap();
35804                         }
35805                         // moduleName will be a StringLiteral since this is not `declare global`.
35806                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
35807                     }
35808                     else {
35809                         if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) {
35810                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
35811                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
35812                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
35813                                 var _d = _c[_i], key = _d[0], value = _d[1];
35814                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
35815                                     mergeSymbol(resolvedExports.get(key), value);
35816                                 }
35817                             }
35818                         }
35819                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
35820                     }
35821                 }
35822                 else {
35823                     // moduleName will be a StringLiteral since this is not `declare global`.
35824                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
35825                 }
35826             }
35827         }
35828         function addToSymbolTable(target, source, message) {
35829             source.forEach(function (sourceSymbol, id) {
35830                 var targetSymbol = target.get(id);
35831                 if (targetSymbol) {
35832                     // Error on redeclarations
35833                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
35834                 }
35835                 else {
35836                     target.set(id, sourceSymbol);
35837                 }
35838             });
35839             function addDeclarationDiagnostic(id, message) {
35840                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
35841             }
35842         }
35843         function getSymbolLinks(symbol) {
35844             if (symbol.flags & 33554432 /* Transient */)
35845                 return symbol;
35846             var id = getSymbolId(symbol);
35847             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
35848         }
35849         function getNodeLinks(node) {
35850             var nodeId = getNodeId(node);
35851             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
35852         }
35853         function isGlobalSourceFile(node) {
35854             return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
35855         }
35856         function getSymbol(symbols, name, meaning) {
35857             if (meaning) {
35858                 var symbol = getMergedSymbol(symbols.get(name));
35859                 if (symbol) {
35860                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
35861                     if (symbol.flags & meaning) {
35862                         return symbol;
35863                     }
35864                     if (symbol.flags & 2097152 /* Alias */) {
35865                         var target = resolveAlias(symbol);
35866                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
35867                         if (target === unknownSymbol || target.flags & meaning) {
35868                             return symbol;
35869                         }
35870                     }
35871                 }
35872             }
35873             // return undefined if we can't find a symbol.
35874         }
35875         /**
35876          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
35877          * @param parameter a parameterDeclaration node
35878          * @param parameterName a name of the parameter to get the symbols for.
35879          * @return a tuple of two symbols
35880          */
35881         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
35882             var constructorDeclaration = parameter.parent;
35883             var classDeclaration = parameter.parent.parent;
35884             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
35885             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
35886             if (parameterSymbol && propertySymbol) {
35887                 return [parameterSymbol, propertySymbol];
35888             }
35889             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
35890         }
35891         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
35892             var declarationFile = ts.getSourceFileOfNode(declaration);
35893             var useFile = ts.getSourceFileOfNode(usage);
35894             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
35895             if (declarationFile !== useFile) {
35896                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
35897                     (!compilerOptions.outFile && !compilerOptions.out) ||
35898                     isInTypeQuery(usage) ||
35899                     declaration.flags & 8388608 /* Ambient */) {
35900                     // nodes are in different files and order cannot be determined
35901                     return true;
35902                 }
35903                 // declaration is after usage
35904                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
35905                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35906                     return true;
35907                 }
35908                 var sourceFiles = host.getSourceFiles();
35909                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
35910             }
35911             if (declaration.pos <= usage.pos) {
35912                 // declaration is before usage
35913                 if (declaration.kind === 191 /* BindingElement */) {
35914                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
35915                     var errorBindingElement = ts.getAncestor(usage, 191 /* BindingElement */);
35916                     if (errorBindingElement) {
35917                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
35918                             declaration.pos < errorBindingElement.pos;
35919                     }
35920                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
35921                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 242 /* VariableDeclaration */), usage);
35922                 }
35923                 else if (declaration.kind === 242 /* VariableDeclaration */) {
35924                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
35925                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
35926                 }
35927                 else if (ts.isClassDeclaration(declaration)) {
35928                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
35929                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
35930                 }
35931                 else if (ts.isPropertyDeclaration(declaration)) {
35932                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
35933                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
35934                 }
35935                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
35936                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
35937                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35938                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
35939                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
35940                 }
35941                 return true;
35942             }
35943             // declaration is after usage, but it can still be legal if usage is deferred:
35944             // 1. inside an export specifier
35945             // 2. inside a function
35946             // 3. inside an instance property initializer, a reference to a non-instance property
35947             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
35948             // 4. inside a static property initializer, a reference to a static method in the same class
35949             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
35950             // or if usage is in a type context:
35951             // 1. inside a type query (typeof in type position)
35952             // 2. inside a jsdoc comment
35953             if (usage.parent.kind === 263 /* ExportSpecifier */ || (usage.parent.kind === 259 /* ExportAssignment */ && usage.parent.isExportEquals)) {
35954                 // export specifiers do not use the variable, they only make it available for use
35955                 return true;
35956             }
35957             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
35958             if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) {
35959                 return true;
35960             }
35961             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
35962                 return true;
35963             }
35964             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35965                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35966                     && ts.getContainingClass(declaration)
35967                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
35968                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
35969                 }
35970                 else {
35971                     return true;
35972                 }
35973             }
35974             return false;
35975             function usageInTypeDeclaration() {
35976                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
35977             }
35978             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
35979                 switch (declaration.parent.parent.kind) {
35980                     case 225 /* VariableStatement */:
35981                     case 230 /* ForStatement */:
35982                     case 232 /* ForOfStatement */:
35983                         // variable statement/for/for-of statement case,
35984                         // use site should not be inside variable declaration (initializer of declaration or binding element)
35985                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
35986                             return true;
35987                         }
35988                         break;
35989                 }
35990                 // ForIn/ForOf case - use site should not be used in expression part
35991                 var grandparent = declaration.parent.parent;
35992                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
35993             }
35994             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
35995                 return !!ts.findAncestor(usage, function (current) {
35996                     if (current === declContainer) {
35997                         return "quit";
35998                     }
35999                     if (ts.isFunctionLike(current)) {
36000                         return true;
36001                     }
36002                     var initializerOfProperty = current.parent &&
36003                         current.parent.kind === 159 /* PropertyDeclaration */ &&
36004                         current.parent.initializer === current;
36005                     if (initializerOfProperty) {
36006                         if (ts.hasModifier(current.parent, 32 /* Static */)) {
36007                             if (declaration.kind === 161 /* MethodDeclaration */) {
36008                                 return true;
36009                             }
36010                         }
36011                         else {
36012                             var isDeclarationInstanceProperty = declaration.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
36013                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
36014                                 return true;
36015                             }
36016                         }
36017                     }
36018                     return false;
36019                 });
36020             }
36021             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
36022             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
36023                 // always legal if usage is after declaration
36024                 if (usage.end > declaration.end) {
36025                     return false;
36026                 }
36027                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
36028                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
36029                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
36030                     if (node === declaration) {
36031                         return "quit";
36032                     }
36033                     switch (node.kind) {
36034                         case 202 /* ArrowFunction */:
36035                             return true;
36036                         case 159 /* PropertyDeclaration */:
36037                             // even when stopping at any property declaration, they need to come from the same class
36038                             return stopAtAnyPropertyDeclaration &&
36039                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
36040                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
36041                                 ? "quit" : true;
36042                         case 223 /* Block */:
36043                             switch (node.parent.kind) {
36044                                 case 163 /* GetAccessor */:
36045                                 case 161 /* MethodDeclaration */:
36046                                 case 164 /* SetAccessor */:
36047                                     return true;
36048                                 default:
36049                                     return false;
36050                             }
36051                         default:
36052                             return false;
36053                     }
36054                 });
36055                 return ancestorChangingReferenceScope === undefined;
36056             }
36057         }
36058         function useOuterVariableScopeInParameter(result, location, lastLocation) {
36059             var target = ts.getEmitScriptTarget(compilerOptions);
36060             var functionLocation = location;
36061             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
36062                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
36063                 // - static field in a class expression
36064                 // - optional chaining pre-es2020
36065                 // - nullish coalesce pre-es2020
36066                 // - spread assignment in binding pattern pre-es2017
36067                 if (target >= 2 /* ES2015 */) {
36068                     var links = getNodeLinks(functionLocation);
36069                     if (links.declarationRequiresScopeChange === undefined) {
36070                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
36071                     }
36072                     return !links.declarationRequiresScopeChange;
36073                 }
36074             }
36075             return false;
36076             function requiresScopeChange(node) {
36077                 return requiresScopeChangeWorker(node.name)
36078                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
36079             }
36080             function requiresScopeChangeWorker(node) {
36081                 switch (node.kind) {
36082                     case 202 /* ArrowFunction */:
36083                     case 201 /* FunctionExpression */:
36084                     case 244 /* FunctionDeclaration */:
36085                     case 162 /* Constructor */:
36086                         // do not descend into these
36087                         return false;
36088                     case 161 /* MethodDeclaration */:
36089                     case 163 /* GetAccessor */:
36090                     case 164 /* SetAccessor */:
36091                     case 281 /* PropertyAssignment */:
36092                         return requiresScopeChangeWorker(node.name);
36093                     case 159 /* PropertyDeclaration */:
36094                         // static properties in classes introduce temporary variables
36095                         if (ts.hasStaticModifier(node)) {
36096                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
36097                         }
36098                         return requiresScopeChangeWorker(node.name);
36099                     default:
36100                         // null coalesce and optional chain pre-es2020 produce temporary variables
36101                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
36102                             return target < 7 /* ES2020 */;
36103                         }
36104                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
36105                             return target < 4 /* ES2017 */;
36106                         }
36107                         if (ts.isTypeNode(node))
36108                             return false;
36109                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
36110                 }
36111             }
36112         }
36113         /**
36114          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
36115          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
36116          * the given name can be found.
36117          *
36118          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
36119          */
36120         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
36121             if (excludeGlobals === void 0) { excludeGlobals = false; }
36122             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
36123         }
36124         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
36125             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
36126             var result;
36127             var lastLocation;
36128             var lastSelfReferenceLocation;
36129             var propertyWithInvalidInitializer;
36130             var associatedDeclarationForContainingInitializerOrBindingName;
36131             var withinDeferredContext = false;
36132             var errorLocation = location;
36133             var grandparent;
36134             var isInExternalModule = false;
36135             loop: while (location) {
36136                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
36137                 if (location.locals && !isGlobalSourceFile(location)) {
36138                     if (result = lookup(location.locals, name, meaning)) {
36139                         var useResult = true;
36140                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
36141                             // symbol lookup restrictions for function-like declarations
36142                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
36143                             //   list and return type. However, local types are only in scope in the function body.
36144                             // - parameters are only in the scope of function body
36145                             // This restriction does not apply to JSDoc comment types because they are parented
36146                             // at a higher level than type parameters would normally be
36147                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 303 /* JSDocComment */) {
36148                                 useResult = result.flags & 262144 /* TypeParameter */
36149                                     // type parameters are visible in parameter list, return type and type parameter list
36150                                     ? lastLocation === location.type ||
36151                                         lastLocation.kind === 156 /* Parameter */ ||
36152                                         lastLocation.kind === 155 /* TypeParameter */
36153                                     // local types not visible outside the function body
36154                                     : false;
36155                             }
36156                             if (meaning & result.flags & 3 /* Variable */) {
36157                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
36158                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
36159                                     useResult = false;
36160                                 }
36161                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
36162                                     // parameters are visible only inside function body, parameter list and return type
36163                                     // technically for parameter list case here we might mix parameters and variables declared in function,
36164                                     // however it is detected separately when checking initializers of parameters
36165                                     // to make sure that they reference no variables declared after them.
36166                                     useResult =
36167                                         lastLocation.kind === 156 /* Parameter */ ||
36168                                             (lastLocation === location.type &&
36169                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
36170                                 }
36171                             }
36172                         }
36173                         else if (location.kind === 180 /* ConditionalType */) {
36174                             // A type parameter declared using 'infer T' in a conditional type is visible only in
36175                             // the true branch of the conditional type.
36176                             useResult = lastLocation === location.trueType;
36177                         }
36178                         if (useResult) {
36179                             break loop;
36180                         }
36181                         else {
36182                             result = undefined;
36183                         }
36184                     }
36185                 }
36186                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
36187                 switch (location.kind) {
36188                     case 290 /* SourceFile */:
36189                         if (!ts.isExternalOrCommonJsModule(location))
36190                             break;
36191                         isInExternalModule = true;
36192                     // falls through
36193                     case 249 /* ModuleDeclaration */:
36194                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
36195                         if (location.kind === 290 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
36196                             // It's an external module. First see if the module has an export default and if the local
36197                             // name of that export default matches.
36198                             if (result = moduleExports.get("default" /* Default */)) {
36199                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
36200                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
36201                                     break loop;
36202                                 }
36203                                 result = undefined;
36204                             }
36205                             // Because of module/namespace merging, a module's exports are in scope,
36206                             // yet we never want to treat an export specifier as putting a member in scope.
36207                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
36208                             // Two things to note about this:
36209                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
36210                             //        on an export specifier is that it might find the export specifier itself, and try to
36211                             //        resolve it as an alias. This will cause the checker to consider the export specifier
36212                             //        a circular alias reference when it might not be.
36213                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
36214                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
36215                             //        which is not the desired behavior.
36216                             var moduleExport = moduleExports.get(name);
36217                             if (moduleExport &&
36218                                 moduleExport.flags === 2097152 /* Alias */ &&
36219                                 (ts.getDeclarationOfKind(moduleExport, 263 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 262 /* NamespaceExport */))) {
36220                                 break;
36221                             }
36222                         }
36223                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
36224                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
36225                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
36226                                 result = undefined;
36227                             }
36228                             else {
36229                                 break loop;
36230                             }
36231                         }
36232                         break;
36233                     case 248 /* EnumDeclaration */:
36234                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
36235                             break loop;
36236                         }
36237                         break;
36238                     case 159 /* PropertyDeclaration */:
36239                         // TypeScript 1.0 spec (April 2014): 8.4.1
36240                         // Initializer expressions for instance member variables are evaluated in the scope
36241                         // of the class constructor body but are not permitted to reference parameters or
36242                         // local variables of the constructor. This effectively means that entities from outer scopes
36243                         // by the same name as a constructor parameter or local variable are inaccessible
36244                         // in initializer expressions for instance member variables.
36245                         if (!ts.hasModifier(location, 32 /* Static */)) {
36246                             var ctor = findConstructorDeclaration(location.parent);
36247                             if (ctor && ctor.locals) {
36248                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
36249                                     // Remember the property node, it will be used later to report appropriate error
36250                                     propertyWithInvalidInitializer = location;
36251                                 }
36252                             }
36253                         }
36254                         break;
36255                     case 245 /* ClassDeclaration */:
36256                     case 214 /* ClassExpression */:
36257                     case 246 /* InterfaceDeclaration */:
36258                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
36259                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
36260                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
36261                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
36262                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
36263                                 // ignore type parameters not declared in this container
36264                                 result = undefined;
36265                                 break;
36266                             }
36267                             if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
36268                                 // TypeScript 1.0 spec (April 2014): 3.4.1
36269                                 // The scope of a type parameter extends over the entire declaration with which the type
36270                                 // parameter list is associated, with the exception of static member declarations in classes.
36271                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
36272                                 return undefined;
36273                             }
36274                             break loop;
36275                         }
36276                         if (location.kind === 214 /* ClassExpression */ && meaning & 32 /* Class */) {
36277                             var className = location.name;
36278                             if (className && name === className.escapedText) {
36279                                 result = location.symbol;
36280                                 break loop;
36281                             }
36282                         }
36283                         break;
36284                     case 216 /* ExpressionWithTypeArguments */:
36285                         // The type parameters of a class are not in scope in the base class expression.
36286                         if (lastLocation === location.expression && location.parent.token === 90 /* ExtendsKeyword */) {
36287                             var container = location.parent.parent;
36288                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
36289                                 if (nameNotFoundMessage) {
36290                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
36291                                 }
36292                                 return undefined;
36293                             }
36294                         }
36295                         break;
36296                     // It is not legal to reference a class's own type parameters from a computed property name that
36297                     // belongs to the class. For example:
36298                     //
36299                     //   function foo<T>() { return '' }
36300                     //   class C<T> { // <-- Class's own type parameter T
36301                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
36302                     //   }
36303                     //
36304                     case 154 /* ComputedPropertyName */:
36305                         grandparent = location.parent.parent;
36306                         if (ts.isClassLike(grandparent) || grandparent.kind === 246 /* InterfaceDeclaration */) {
36307                             // A reference to this grandparent's type parameters would be an error
36308                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
36309                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
36310                                 return undefined;
36311                             }
36312                         }
36313                         break;
36314                     case 202 /* ArrowFunction */:
36315                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
36316                         // for lower compile targets the resolved symbol is used to emit an error
36317                         if (compilerOptions.target >= 2 /* ES2015 */) {
36318                             break;
36319                         }
36320                     // falls through
36321                     case 161 /* MethodDeclaration */:
36322                     case 162 /* Constructor */:
36323                     case 163 /* GetAccessor */:
36324                     case 164 /* SetAccessor */:
36325                     case 244 /* FunctionDeclaration */:
36326                         if (meaning & 3 /* Variable */ && name === "arguments") {
36327                             result = argumentsSymbol;
36328                             break loop;
36329                         }
36330                         break;
36331                     case 201 /* FunctionExpression */:
36332                         if (meaning & 3 /* Variable */ && name === "arguments") {
36333                             result = argumentsSymbol;
36334                             break loop;
36335                         }
36336                         if (meaning & 16 /* Function */) {
36337                             var functionName = location.name;
36338                             if (functionName && name === functionName.escapedText) {
36339                                 result = location.symbol;
36340                                 break loop;
36341                             }
36342                         }
36343                         break;
36344                     case 157 /* Decorator */:
36345                         // Decorators are resolved at the class declaration. Resolving at the parameter
36346                         // or member would result in looking up locals in the method.
36347                         //
36348                         //   function y() {}
36349                         //   class C {
36350                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
36351                         //   }
36352                         //
36353                         if (location.parent && location.parent.kind === 156 /* Parameter */) {
36354                             location = location.parent;
36355                         }
36356                         //
36357                         //   function y() {}
36358                         //   class C {
36359                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
36360                         //   }
36361                         //
36362                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
36363                         //
36364                         //   type T = number;
36365                         //   declare function y(x: T): any;
36366                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
36367                         //   class C<T> {}
36368                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 245 /* ClassDeclaration */)) {
36369                             location = location.parent;
36370                         }
36371                         break;
36372                     case 322 /* JSDocTypedefTag */:
36373                     case 315 /* JSDocCallbackTag */:
36374                     case 316 /* JSDocEnumTag */:
36375                         // js type aliases do not resolve names from their host, so skip past it
36376                         location = ts.getJSDocHost(location);
36377                         break;
36378                     case 156 /* Parameter */:
36379                         if (lastLocation && (lastLocation === location.initializer ||
36380                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36381                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
36382                                 associatedDeclarationForContainingInitializerOrBindingName = location;
36383                             }
36384                         }
36385                         break;
36386                     case 191 /* BindingElement */:
36387                         if (lastLocation && (lastLocation === location.initializer ||
36388                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36389                             var root = ts.getRootDeclaration(location);
36390                             if (root.kind === 156 /* Parameter */) {
36391                                 if (!associatedDeclarationForContainingInitializerOrBindingName) {
36392                                     associatedDeclarationForContainingInitializerOrBindingName = location;
36393                                 }
36394                             }
36395                         }
36396                         break;
36397                 }
36398                 if (isSelfReferenceLocation(location)) {
36399                     lastSelfReferenceLocation = location;
36400                 }
36401                 lastLocation = location;
36402                 location = location.parent;
36403             }
36404             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
36405             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
36406             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
36407             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
36408                 result.isReferenced |= meaning;
36409             }
36410             if (!result) {
36411                 if (lastLocation) {
36412                     ts.Debug.assert(lastLocation.kind === 290 /* SourceFile */);
36413                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
36414                         return lastLocation.symbol;
36415                     }
36416                 }
36417                 if (!excludeGlobals) {
36418                     result = lookup(globals, name, meaning);
36419                 }
36420             }
36421             if (!result) {
36422                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
36423                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
36424                         return requireSymbol;
36425                     }
36426                 }
36427             }
36428             if (!result) {
36429                 if (nameNotFoundMessage) {
36430                     if (!errorLocation ||
36431                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
36432                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
36433                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
36434                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
36435                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
36436                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
36437                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
36438                         var suggestion = void 0;
36439                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
36440                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
36441                             if (suggestion) {
36442                                 var suggestionName = symbolToString(suggestion);
36443                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
36444                                 if (suggestion.valueDeclaration) {
36445                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
36446                                 }
36447                             }
36448                         }
36449                         if (!suggestion) {
36450                             error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
36451                         }
36452                         suggestionCount++;
36453                     }
36454                 }
36455                 return undefined;
36456             }
36457             // Perform extra checks only if error reporting was requested
36458             if (nameNotFoundMessage) {
36459                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
36460                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
36461                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
36462                     // with ESNext+useDefineForClassFields because the scope semantics are different.
36463                     var propertyName = propertyWithInvalidInitializer.name;
36464                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
36465                     return undefined;
36466                 }
36467                 // Only check for block-scoped variable if we have an error location and are looking for the
36468                 // name with variable meaning
36469                 //      For example,
36470                 //          declare module foo {
36471                 //              interface bar {}
36472                 //          }
36473                 //      const foo/*1*/: foo/*2*/.bar;
36474                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
36475                 // block-scoped variable and namespace module. However, only when we
36476                 // try to resolve name in /*1*/ which is used in variable position,
36477                 // we want to check for block-scoped
36478                 if (errorLocation &&
36479                     (meaning & 2 /* BlockScopedVariable */ ||
36480                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
36481                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
36482                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
36483                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
36484                     }
36485                 }
36486                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
36487                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
36488                     var merged = getMergedSymbol(result);
36489                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
36490                         errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name));
36491                     }
36492                 }
36493                 // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right
36494                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
36495                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
36496                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
36497                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
36498                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
36499                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
36500                     }
36501                     // And it cannot refer to any declarations which come after it
36502                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
36503                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
36504                     }
36505                 }
36506                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
36507                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
36508                 }
36509             }
36510             return result;
36511         }
36512         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
36513             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
36514                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
36515                 if (typeOnlyDeclaration) {
36516                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36517                     var message = isExport
36518                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
36519                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
36520                     var relatedMessage = isExport
36521                         ? ts.Diagnostics._0_was_exported_here
36522                         : ts.Diagnostics._0_was_imported_here;
36523                     var unescapedName = ts.unescapeLeadingUnderscores(name);
36524                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
36525                 }
36526             }
36527         }
36528         function getIsDeferredContext(location, lastLocation) {
36529             if (location.kind !== 202 /* ArrowFunction */ && location.kind !== 201 /* FunctionExpression */) {
36530                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
36531                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
36532                     (location.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
36533             }
36534             if (lastLocation && lastLocation === location.name) {
36535                 return false;
36536             }
36537             // generator functions and async functions are not inlined in control flow when immediately invoked
36538             if (location.asteriskToken || ts.hasModifier(location, 256 /* Async */)) {
36539                 return true;
36540             }
36541             return !ts.getImmediatelyInvokedFunctionExpression(location);
36542         }
36543         function isSelfReferenceLocation(node) {
36544             switch (node.kind) {
36545                 case 244 /* FunctionDeclaration */:
36546                 case 245 /* ClassDeclaration */:
36547                 case 246 /* InterfaceDeclaration */:
36548                 case 248 /* EnumDeclaration */:
36549                 case 247 /* TypeAliasDeclaration */:
36550                 case 249 /* ModuleDeclaration */: // For `namespace N { N; }`
36551                     return true;
36552                 default:
36553                     return false;
36554             }
36555         }
36556         function diagnosticName(nameArg) {
36557             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
36558         }
36559         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
36560             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36561                 var decl = _a[_i];
36562                 if (decl.kind === 155 /* TypeParameter */) {
36563                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
36564                     if (parent === container) {
36565                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
36566                     }
36567                 }
36568             }
36569             return false;
36570         }
36571         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
36572             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
36573                 return false;
36574             }
36575             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
36576             var location = container;
36577             while (location) {
36578                 if (ts.isClassLike(location.parent)) {
36579                     var classSymbol = getSymbolOfNode(location.parent);
36580                     if (!classSymbol) {
36581                         break;
36582                     }
36583                     // Check to see if a static member exists.
36584                     var constructorType = getTypeOfSymbol(classSymbol);
36585                     if (getPropertyOfType(constructorType, name)) {
36586                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
36587                         return true;
36588                     }
36589                     // No static member is present.
36590                     // Check if we're in an instance method and look for a relevant instance member.
36591                     if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
36592                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
36593                         if (getPropertyOfType(instanceType, name)) {
36594                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
36595                             return true;
36596                         }
36597                     }
36598                 }
36599                 location = location.parent;
36600             }
36601             return false;
36602         }
36603         function checkAndReportErrorForExtendingInterface(errorLocation) {
36604             var expression = getEntityNameForExtendingInterface(errorLocation);
36605             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
36606                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
36607                 return true;
36608             }
36609             return false;
36610         }
36611         /**
36612          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
36613          * but returns undefined if that expression is not an EntityNameExpression.
36614          */
36615         function getEntityNameForExtendingInterface(node) {
36616             switch (node.kind) {
36617                 case 75 /* Identifier */:
36618                 case 194 /* PropertyAccessExpression */:
36619                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
36620                 case 216 /* ExpressionWithTypeArguments */:
36621                     if (ts.isEntityNameExpression(node.expression)) {
36622                         return node.expression;
36623                     }
36624                 // falls through
36625                 default:
36626                     return undefined;
36627             }
36628         }
36629         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
36630             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
36631             if (meaning === namespaceMeaning) {
36632                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36633                 var parent = errorLocation.parent;
36634                 if (symbol) {
36635                     if (ts.isQualifiedName(parent)) {
36636                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
36637                         var propName = parent.right.escapedText;
36638                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
36639                         if (propType) {
36640                             error(parent, ts.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, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName));
36641                             return true;
36642                         }
36643                     }
36644                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
36645                     return true;
36646                 }
36647             }
36648             return false;
36649         }
36650         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
36651             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
36652                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36653                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
36654                     error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.unescapeLeadingUnderscores(name));
36655                     return true;
36656                 }
36657             }
36658             return false;
36659         }
36660         function isPrimitiveTypeName(name) {
36661             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
36662         }
36663         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
36664             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 263 /* ExportSpecifier */) {
36665                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
36666                 return true;
36667             }
36668             return false;
36669         }
36670         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
36671             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
36672                 if (isPrimitiveTypeName(name)) {
36673                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
36674                     return true;
36675                 }
36676                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36677                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
36678                     var message = isES2015OrLaterConstructorName(name)
36679                         ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
36680                         : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
36681                     error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
36682                     return true;
36683                 }
36684             }
36685             return false;
36686         }
36687         function isES2015OrLaterConstructorName(n) {
36688             switch (n) {
36689                 case "Promise":
36690                 case "Symbol":
36691                 case "Map":
36692                 case "WeakMap":
36693                 case "Set":
36694                 case "WeakSet":
36695                     return true;
36696             }
36697             return false;
36698         }
36699         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
36700             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
36701                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36702                 if (symbol) {
36703                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
36704                     return true;
36705                 }
36706             }
36707             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
36708                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36709                 if (symbol) {
36710                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
36711                     return true;
36712                 }
36713             }
36714             return false;
36715         }
36716         function checkResolvedBlockScopedVariable(result, errorLocation) {
36717             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
36718             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
36719                 // constructor functions aren't block scoped
36720                 return;
36721             }
36722             // Block-scoped variables cannot be used before their definition
36723             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 248 /* EnumDeclaration */); });
36724             if (declaration === undefined)
36725                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
36726             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
36727                 var diagnosticMessage = void 0;
36728                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
36729                 if (result.flags & 2 /* BlockScopedVariable */) {
36730                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
36731                 }
36732                 else if (result.flags & 32 /* Class */) {
36733                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36734                 }
36735                 else if (result.flags & 256 /* RegularEnum */) {
36736                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
36737                 }
36738                 else {
36739                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
36740                     if (compilerOptions.preserveConstEnums) {
36741                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36742                     }
36743                 }
36744                 if (diagnosticMessage) {
36745                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
36746                 }
36747             }
36748         }
36749         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
36750          * If at any point current node is equal to 'parent' node - return true.
36751          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
36752          */
36753         function isSameScopeDescendentOf(initial, parent, stopAt) {
36754             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
36755         }
36756         function getAnyImportSyntax(node) {
36757             switch (node.kind) {
36758                 case 253 /* ImportEqualsDeclaration */:
36759                     return node;
36760                 case 255 /* ImportClause */:
36761                     return node.parent;
36762                 case 256 /* NamespaceImport */:
36763                     return node.parent.parent;
36764                 case 258 /* ImportSpecifier */:
36765                     return node.parent.parent.parent;
36766                 default:
36767                     return undefined;
36768             }
36769         }
36770         function getDeclarationOfAliasSymbol(symbol) {
36771             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
36772         }
36773         /**
36774          * An alias symbol is created by one of the following declarations:
36775          * import <symbol> = ...
36776          * import <symbol> from ...
36777          * import * as <symbol> from ...
36778          * import { x as <symbol> } from ...
36779          * export { x as <symbol> } from ...
36780          * export * as ns <symbol> from ...
36781          * export = <EntityNameExpression>
36782          * export default <EntityNameExpression>
36783          * module.exports = <EntityNameExpression>
36784          * {<Identifier>}
36785          * {name: <EntityNameExpression>}
36786          */
36787         function isAliasSymbolDeclaration(node) {
36788             return node.kind === 253 /* ImportEqualsDeclaration */ ||
36789                 node.kind === 252 /* NamespaceExportDeclaration */ ||
36790                 node.kind === 255 /* ImportClause */ && !!node.name ||
36791                 node.kind === 256 /* NamespaceImport */ ||
36792                 node.kind === 262 /* NamespaceExport */ ||
36793                 node.kind === 258 /* ImportSpecifier */ ||
36794                 node.kind === 263 /* ExportSpecifier */ ||
36795                 node.kind === 259 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
36796                 ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
36797                 ts.isPropertyAccessExpression(node)
36798                     && ts.isBinaryExpression(node.parent)
36799                     && node.parent.left === node
36800                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
36801                     && isAliasableOrJsExpression(node.parent.right) ||
36802                 node.kind === 282 /* ShorthandPropertyAssignment */ ||
36803                 node.kind === 281 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
36804         }
36805         function isAliasableOrJsExpression(e) {
36806             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
36807         }
36808         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
36809             if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
36810                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
36811                 var resolved_4 = resolveExternalModuleSymbol(immediate);
36812                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
36813                 return resolved_4;
36814             }
36815             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
36816             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
36817             return resolved;
36818         }
36819         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
36820             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
36821                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
36822                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36823                 var message = isExport
36824                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
36825                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
36826                 var relatedMessage = isExport
36827                     ? ts.Diagnostics._0_was_exported_here
36828                     : ts.Diagnostics._0_was_imported_here;
36829                 // Non-null assertion is safe because the optionality comes from ImportClause,
36830                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
36831                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
36832                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
36833             }
36834         }
36835         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
36836             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
36837             if (exportValue) {
36838                 return getPropertyOfType(getTypeOfSymbol(exportValue), name);
36839             }
36840             var exportSymbol = moduleSymbol.exports.get(name);
36841             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36842             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
36843             return resolved;
36844         }
36845         function isSyntacticDefault(node) {
36846             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
36847         }
36848         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
36849             if (!allowSyntheticDefaultImports) {
36850                 return false;
36851             }
36852             // Declaration files (and ambient modules)
36853             if (!file || file.isDeclarationFile) {
36854                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
36855                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
36856                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
36857                     return false;
36858                 }
36859                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
36860                 // So we check a bit more,
36861                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
36862                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
36863                     // it definitely is a module and does not have a synthetic default
36864                     return false;
36865                 }
36866                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
36867                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
36868                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
36869                 return true;
36870             }
36871             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
36872             if (!ts.isSourceFileJS(file)) {
36873                 return hasExportAssignmentSymbol(moduleSymbol);
36874             }
36875             // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker
36876             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
36877         }
36878         function getTargetOfImportClause(node, dontResolveAlias) {
36879             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
36880             if (moduleSymbol) {
36881                 var exportDefaultSymbol = void 0;
36882                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
36883                     exportDefaultSymbol = moduleSymbol;
36884                 }
36885                 else {
36886                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
36887                 }
36888                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
36889                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
36890                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
36891                     if (hasExportAssignmentSymbol(moduleSymbol)) {
36892                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
36893                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
36894                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
36895                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
36896                         ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName));
36897                     }
36898                     else {
36899                         reportNonDefaultExport(moduleSymbol, node);
36900                     }
36901                 }
36902                 else if (hasSyntheticDefault) {
36903                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
36904                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
36905                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
36906                     return resolved;
36907                 }
36908                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
36909                 return exportDefaultSymbol;
36910             }
36911         }
36912         function reportNonDefaultExport(moduleSymbol, node) {
36913             var _a, _b;
36914             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
36915                 error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol));
36916             }
36917             else {
36918                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
36919                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
36920                 if (exportStar) {
36921                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
36922                         var _a, _b;
36923                         return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)));
36924                     });
36925                     if (defaultExport) {
36926                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
36927                     }
36928                 }
36929             }
36930         }
36931         function getTargetOfNamespaceImport(node, dontResolveAlias) {
36932             var moduleSpecifier = node.parent.parent.moduleSpecifier;
36933             var immediate = resolveExternalModuleName(node, moduleSpecifier);
36934             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36935             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36936             return resolved;
36937         }
36938         function getTargetOfNamespaceExport(node, dontResolveAlias) {
36939             var moduleSpecifier = node.parent.moduleSpecifier;
36940             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
36941             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36942             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36943             return resolved;
36944         }
36945         // This function creates a synthetic symbol that combines the value side of one symbol with the
36946         // type/namespace side of another symbol. Consider this example:
36947         //
36948         //   declare module graphics {
36949         //       interface Point {
36950         //           x: number;
36951         //           y: number;
36952         //       }
36953         //   }
36954         //   declare var graphics: {
36955         //       Point: new (x: number, y: number) => graphics.Point;
36956         //   }
36957         //   declare module "graphics" {
36958         //       export = graphics;
36959         //   }
36960         //
36961         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
36962         // property with the type/namespace side interface 'Point'.
36963         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
36964             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
36965                 return unknownSymbol;
36966             }
36967             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
36968                 return valueSymbol;
36969             }
36970             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
36971             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
36972             result.parent = valueSymbol.parent || typeSymbol.parent;
36973             if (valueSymbol.valueDeclaration)
36974                 result.valueDeclaration = valueSymbol.valueDeclaration;
36975             if (typeSymbol.members)
36976                 result.members = ts.cloneMap(typeSymbol.members);
36977             if (valueSymbol.exports)
36978                 result.exports = ts.cloneMap(valueSymbol.exports);
36979             return result;
36980         }
36981         function getExportOfModule(symbol, specifier, dontResolveAlias) {
36982             var _a;
36983             if (symbol.flags & 1536 /* Module */) {
36984                 var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
36985                 var exportSymbol = getExportsOfSymbol(symbol).get(name);
36986                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36987                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
36988                 return resolved;
36989             }
36990         }
36991         function getPropertyOfVariable(symbol, name) {
36992             if (symbol.flags & 3 /* Variable */) {
36993                 var typeAnnotation = symbol.valueDeclaration.type;
36994                 if (typeAnnotation) {
36995                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
36996                 }
36997             }
36998         }
36999         function getExternalModuleMember(node, specifier, dontResolveAlias) {
37000             var _a;
37001             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
37002             var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
37003             var name = specifier.propertyName || specifier.name;
37004             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
37005             var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
37006             if (targetSymbol) {
37007                 if (name.escapedText) {
37008                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
37009                         return moduleSymbol;
37010                     }
37011                     var symbolFromVariable = void 0;
37012                     // First check if module was specified with "export=". If so, get the member from the resolved type
37013                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
37014                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
37015                     }
37016                     else {
37017                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
37018                     }
37019                     // if symbolFromVariable is export - get its final target
37020                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
37021                     var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
37022                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
37023                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
37024                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
37025                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
37026                         }
37027                     }
37028                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
37029                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
37030                         symbolFromModule || symbolFromVariable;
37031                     if (!symbol) {
37032                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
37033                         var declarationName = ts.declarationNameToString(name);
37034                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
37035                         if (suggestion !== undefined) {
37036                             var suggestionName = symbolToString(suggestion);
37037                             var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
37038                             if (suggestion.valueDeclaration) {
37039                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
37040                             }
37041                         }
37042                         else {
37043                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
37044                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
37045                             }
37046                             else {
37047                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
37048                             }
37049                         }
37050                     }
37051                     return symbol;
37052                 }
37053             }
37054         }
37055         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
37056             var _a;
37057             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
37058             var exports = moduleSymbol.exports;
37059             if (localSymbol) {
37060                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
37061                 if (exportedEqualsSymbol) {
37062                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
37063                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37064                 }
37065                 else {
37066                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
37067                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
37068                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
37069                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
37070                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
37071                     })));
37072                 }
37073             }
37074             else {
37075                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37076             }
37077         }
37078         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
37079             if (moduleKind >= ts.ModuleKind.ES2015) {
37080                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
37081                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37082                 error(name, message, declarationName);
37083             }
37084             else {
37085                 if (ts.isInJSFile(node)) {
37086                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
37087                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37088                     error(name, message, declarationName);
37089                 }
37090                 else {
37091                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
37092                         ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37093                     error(name, message, declarationName, declarationName, moduleName);
37094                 }
37095             }
37096         }
37097         function getTargetOfImportSpecifier(node, dontResolveAlias) {
37098             var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
37099             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37100             return resolved;
37101         }
37102         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
37103             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
37104             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37105             return resolved;
37106         }
37107         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
37108             var resolved = node.parent.parent.moduleSpecifier ?
37109                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
37110                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
37111             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37112             return resolved;
37113         }
37114         function getTargetOfExportAssignment(node, dontResolveAlias) {
37115             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
37116             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
37117             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37118             return resolved;
37119         }
37120         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
37121             if (ts.isClassExpression(expression)) {
37122                 return checkExpressionCached(expression).symbol;
37123             }
37124             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
37125                 return undefined;
37126             }
37127             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
37128             if (aliasLike) {
37129                 return aliasLike;
37130             }
37131             checkExpressionCached(expression);
37132             return getNodeLinks(expression).resolvedSymbol;
37133         }
37134         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
37135             var expression = node.initializer;
37136             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
37137         }
37138         function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
37139             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
37140                 return undefined;
37141             }
37142             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
37143         }
37144         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
37145             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
37146             switch (node.kind) {
37147                 case 253 /* ImportEqualsDeclaration */:
37148                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
37149                 case 255 /* ImportClause */:
37150                     return getTargetOfImportClause(node, dontRecursivelyResolve);
37151                 case 256 /* NamespaceImport */:
37152                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
37153                 case 262 /* NamespaceExport */:
37154                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
37155                 case 258 /* ImportSpecifier */:
37156                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
37157                 case 263 /* ExportSpecifier */:
37158                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
37159                 case 259 /* ExportAssignment */:
37160                 case 209 /* BinaryExpression */:
37161                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
37162                 case 252 /* NamespaceExportDeclaration */:
37163                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
37164                 case 282 /* ShorthandPropertyAssignment */:
37165                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
37166                 case 281 /* PropertyAssignment */:
37167                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
37168                 case 194 /* PropertyAccessExpression */:
37169                     return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
37170                 default:
37171                     return ts.Debug.fail();
37172             }
37173         }
37174         /**
37175          * Indicates that a symbol is an alias that does not merge with a local declaration.
37176          * OR Is a JSContainer which may merge an alias with a local declaration
37177          */
37178         function isNonLocalAlias(symbol, excludes) {
37179             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
37180             if (!symbol)
37181                 return false;
37182             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
37183         }
37184         function resolveSymbol(symbol, dontResolveAlias) {
37185             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
37186         }
37187         function resolveAlias(symbol) {
37188             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
37189             var links = getSymbolLinks(symbol);
37190             if (!links.target) {
37191                 links.target = resolvingSymbol;
37192                 var node = getDeclarationOfAliasSymbol(symbol);
37193                 if (!node)
37194                     return ts.Debug.fail();
37195                 var target = getTargetOfAliasDeclaration(node);
37196                 if (links.target === resolvingSymbol) {
37197                     links.target = target || unknownSymbol;
37198                 }
37199                 else {
37200                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
37201                 }
37202             }
37203             else if (links.target === resolvingSymbol) {
37204                 links.target = unknownSymbol;
37205             }
37206             return links.target;
37207         }
37208         function tryResolveAlias(symbol) {
37209             var links = getSymbolLinks(symbol);
37210             if (links.target !== resolvingSymbol) {
37211                 return resolveAlias(symbol);
37212             }
37213             return undefined;
37214         }
37215         /**
37216          * Marks a symbol as type-only if its declaration is syntactically type-only.
37217          * If it is not itself marked type-only, but resolves to a type-only alias
37218          * somewhere in its resolution chain, save a reference to the type-only alias declaration
37219          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
37220          *
37221          * This function is called on each alias declaration that could be type-only or resolve to
37222          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
37223          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
37224          * and issue an error if so.
37225          *
37226          * @param aliasDeclaration The alias declaration not marked as type-only
37227          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
37228          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
37229          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
37230          * must still be checked for a type-only marker, overwriting the previous negative result if found.
37231          * @param immediateTarget The symbol to which the alias declaration immediately resolves
37232          * @param finalTarget The symbol to which the alias declaration ultimately resolves
37233          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
37234          */
37235         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
37236             if (!aliasDeclaration)
37237                 return false;
37238             // If the declaration itself is type-only, mark it and return.
37239             // No need to check what it resolves to.
37240             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
37241             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
37242                 var links_1 = getSymbolLinks(sourceSymbol);
37243                 links_1.typeOnlyDeclaration = aliasDeclaration;
37244                 return true;
37245             }
37246             var links = getSymbolLinks(sourceSymbol);
37247             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
37248                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
37249         }
37250         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
37251             var _a, _b, _c;
37252             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
37253                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
37254                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
37255                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
37256             }
37257             return !!aliasDeclarationLinks.typeOnlyDeclaration;
37258         }
37259         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
37260         function getTypeOnlyAliasDeclaration(symbol) {
37261             if (!(symbol.flags & 2097152 /* Alias */)) {
37262                 return undefined;
37263             }
37264             var links = getSymbolLinks(symbol);
37265             return links.typeOnlyDeclaration || undefined;
37266         }
37267         function markExportAsReferenced(node) {
37268             var symbol = getSymbolOfNode(node);
37269             var target = resolveAlias(symbol);
37270             if (target) {
37271                 var markAlias = target === unknownSymbol ||
37272                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
37273                 if (markAlias) {
37274                     markAliasSymbolAsReferenced(symbol);
37275                 }
37276             }
37277         }
37278         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
37279         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
37280         // the alias as an expression (which recursively takes us back here if the target references another alias).
37281         function markAliasSymbolAsReferenced(symbol) {
37282             var links = getSymbolLinks(symbol);
37283             if (!links.referenced) {
37284                 links.referenced = true;
37285                 var node = getDeclarationOfAliasSymbol(symbol);
37286                 if (!node)
37287                     return ts.Debug.fail();
37288                 // We defer checking of the reference of an `import =` until the import itself is referenced,
37289                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
37290                 // position.
37291                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
37292                     var target = resolveSymbol(symbol);
37293                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
37294                         // import foo = <symbol>
37295                         checkExpressionCached(node.moduleReference);
37296                     }
37297                 }
37298             }
37299         }
37300         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
37301         // but their usage in value positions must be tracked to determine if the import can be type-only.
37302         function markConstEnumAliasAsReferenced(symbol) {
37303             var links = getSymbolLinks(symbol);
37304             if (!links.constEnumReferenced) {
37305                 links.constEnumReferenced = true;
37306             }
37307         }
37308         // This function is only for imports with entity names
37309         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
37310             // There are three things we might try to look for. In the following examples,
37311             // the search term is enclosed in |...|:
37312             //
37313             //     import a = |b|; // Namespace
37314             //     import a = |b.c|; // Value, type, namespace
37315             //     import a = |b.c|.d; // Namespace
37316             if (entityName.kind === 75 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
37317                 entityName = entityName.parent;
37318             }
37319             // Check for case 1 and 3 in the above example
37320             if (entityName.kind === 75 /* Identifier */ || entityName.parent.kind === 153 /* QualifiedName */) {
37321                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37322             }
37323             else {
37324                 // Case 2 in above example
37325                 // entityName.kind could be a QualifiedName or a Missing identifier
37326                 ts.Debug.assert(entityName.parent.kind === 253 /* ImportEqualsDeclaration */);
37327                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37328             }
37329         }
37330         function getFullyQualifiedName(symbol, containingLocation) {
37331             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
37332         }
37333         /**
37334          * Resolves a qualified name and any involved aliases.
37335          */
37336         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
37337             if (ts.nodeIsMissing(name)) {
37338                 return undefined;
37339             }
37340             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
37341             var symbol;
37342             if (name.kind === 75 /* Identifier */) {
37343                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
37344                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
37345                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
37346                 if (!symbol) {
37347                     return getMergedSymbol(symbolFromJSPrototype);
37348                 }
37349             }
37350             else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) {
37351                 var left = name.kind === 153 /* QualifiedName */ ? name.left : name.expression;
37352                 var right = name.kind === 153 /* QualifiedName */ ? name.right : name.name;
37353                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
37354                 if (!namespace || ts.nodeIsMissing(right)) {
37355                     return undefined;
37356                 }
37357                 else if (namespace === unknownSymbol) {
37358                     return namespace;
37359                 }
37360                 if (ts.isInJSFile(name)) {
37361                     if (namespace.valueDeclaration &&
37362                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
37363                         namespace.valueDeclaration.initializer &&
37364                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
37365                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
37366                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
37367                         if (moduleSym) {
37368                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
37369                             if (resolvedModuleSymbol) {
37370                                 namespace = resolvedModuleSymbol;
37371                             }
37372                         }
37373                     }
37374                 }
37375                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
37376                 if (!symbol) {
37377                     if (!ignoreErrors) {
37378                         error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
37379                     }
37380                     return undefined;
37381                 }
37382             }
37383             else {
37384                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
37385             }
37386             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
37387             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) {
37388                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
37389             }
37390             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
37391         }
37392         /**
37393          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
37394          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
37395          * name resolution won't work either.
37396          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
37397          */
37398         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
37399             if (isJSDocTypeReference(name.parent)) {
37400                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
37401                 if (secondaryLocation) {
37402                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
37403                 }
37404             }
37405         }
37406         function getAssignmentDeclarationLocation(node) {
37407             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
37408             if (typeAlias) {
37409                 return;
37410             }
37411             var host = ts.getJSDocHost(node);
37412             if (ts.isExpressionStatement(host) &&
37413                 ts.isBinaryExpression(host.expression) &&
37414                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
37415                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
37416                 var symbol = getSymbolOfNode(host.expression.left);
37417                 if (symbol) {
37418                     return getDeclarationOfJSPrototypeContainer(symbol);
37419                 }
37420             }
37421             if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
37422                 ts.isBinaryExpression(host.parent.parent) &&
37423                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
37424                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
37425                 var symbol = getSymbolOfNode(host.parent.parent.left);
37426                 if (symbol) {
37427                     return getDeclarationOfJSPrototypeContainer(symbol);
37428                 }
37429             }
37430             var sig = ts.getEffectiveJSDocHost(node);
37431             if (sig && ts.isFunctionLike(sig)) {
37432                 var symbol = getSymbolOfNode(sig);
37433                 return symbol && symbol.valueDeclaration;
37434             }
37435         }
37436         function getDeclarationOfJSPrototypeContainer(symbol) {
37437             var decl = symbol.parent.valueDeclaration;
37438             if (!decl) {
37439                 return undefined;
37440             }
37441             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
37442                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
37443                     undefined;
37444             return initializer || decl;
37445         }
37446         /**
37447          * Get the real symbol of a declaration with an expando initializer.
37448          *
37449          * Normally, declarations have an associated symbol, but when a declaration has an expando
37450          * initializer, the expando's symbol is the one that has all the members merged into it.
37451          */
37452         function getExpandoSymbol(symbol) {
37453             var decl = symbol.valueDeclaration;
37454             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
37455                 return undefined;
37456             }
37457             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
37458             if (init) {
37459                 var initSymbol = getSymbolOfNode(init);
37460                 if (initSymbol) {
37461                     return mergeJSSymbols(initSymbol, symbol);
37462                 }
37463             }
37464         }
37465         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
37466             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations);
37467         }
37468         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
37469             if (isForAugmentation === void 0) { isForAugmentation = false; }
37470             return ts.isStringLiteralLike(moduleReferenceExpression)
37471                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
37472                 : undefined;
37473         }
37474         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
37475             if (isForAugmentation === void 0) { isForAugmentation = false; }
37476             if (ts.startsWith(moduleReference, "@types/")) {
37477                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
37478                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
37479                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
37480             }
37481             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
37482             if (ambientModule) {
37483                 return ambientModule;
37484             }
37485             var currentSourceFile = ts.getSourceFileOfNode(location);
37486             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
37487             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
37488             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
37489             if (sourceFile) {
37490                 if (sourceFile.symbol) {
37491                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
37492                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
37493                     }
37494                     // merged symbol is module declaration symbol combined with all augmentations
37495                     return getMergedSymbol(sourceFile.symbol);
37496                 }
37497                 if (moduleNotFoundError) {
37498                     // report errors only if it was requested
37499                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
37500                 }
37501                 return undefined;
37502             }
37503             if (patternAmbientModules) {
37504                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
37505                 if (pattern) {
37506                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
37507                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
37508                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
37509                     // from a.foo.
37510                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
37511                     if (augmentation) {
37512                         return getMergedSymbol(augmentation);
37513                     }
37514                     return getMergedSymbol(pattern.symbol);
37515                 }
37516             }
37517             // May be an untyped module. If so, ignore resolutionDiagnostic.
37518             if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
37519                 if (isForAugmentation) {
37520                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
37521                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
37522                 }
37523                 else {
37524                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
37525                 }
37526                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
37527                 return undefined;
37528             }
37529             if (moduleNotFoundError) {
37530                 // See if this was possibly a projectReference redirect
37531                 if (resolvedModule) {
37532                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
37533                     if (redirect) {
37534                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
37535                         return undefined;
37536                     }
37537                 }
37538                 if (resolutionDiagnostic) {
37539                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
37540                 }
37541                 else {
37542                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
37543                     if (tsExtension) {
37544                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
37545                         error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
37546                     }
37547                     else if (!compilerOptions.resolveJsonModule &&
37548                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
37549                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
37550                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
37551                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
37552                     }
37553                     else {
37554                         error(errorNode, moduleNotFoundError, moduleReference);
37555                     }
37556                 }
37557             }
37558             return undefined;
37559         }
37560         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
37561             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
37562             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
37563                 ? typesPackageExists(packageId.name)
37564                     ? ts.chainDiagnosticMessages(
37565                     /*details*/ undefined, ts.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, packageId.name, ts.mangleScopedPackageName(packageId.name))
37566                     : ts.chainDiagnosticMessages(
37567                     /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
37568                 : undefined;
37569             errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
37570         }
37571         function typesPackageExists(packageName) {
37572             return getPackagesSet().has(ts.getTypesPackageName(packageName));
37573         }
37574         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
37575             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
37576                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
37577                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
37578                 return getMergedSymbol(exported) || moduleSymbol;
37579             }
37580             return undefined;
37581         }
37582         function getCommonJsExportEquals(exported, moduleSymbol) {
37583             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
37584                 return exported;
37585             }
37586             var links = getSymbolLinks(exported);
37587             if (links.cjsExportMerged) {
37588                 return links.cjsExportMerged;
37589             }
37590             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
37591             merged.flags = merged.flags | 512 /* ValueModule */;
37592             if (merged.exports === undefined) {
37593                 merged.exports = ts.createSymbolTable();
37594             }
37595             moduleSymbol.exports.forEach(function (s, name) {
37596                 if (name === "export=" /* ExportEquals */)
37597                     return;
37598                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
37599             });
37600             getSymbolLinks(merged).cjsExportMerged = merged;
37601             return links.cjsExportMerged = merged;
37602         }
37603         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
37604         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
37605         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
37606         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
37607             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
37608             if (!dontResolveAlias && symbol) {
37609                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 290 /* SourceFile */)) {
37610                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
37611                         ? "allowSyntheticDefaultImports"
37612                         : "esModuleInterop";
37613                     error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName);
37614                     return symbol;
37615                 }
37616                 if (compilerOptions.esModuleInterop) {
37617                     var referenceParent = referencingLocation.parent;
37618                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
37619                         ts.isImportCall(referenceParent)) {
37620                         var type = getTypeOfSymbol(symbol);
37621                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
37622                         if (!sigs || !sigs.length) {
37623                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
37624                         }
37625                         if (sigs && sigs.length) {
37626                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
37627                             // Create a new symbol which has the module's type less the call and construct signatures
37628                             var result = createSymbol(symbol.flags, symbol.escapedName);
37629                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
37630                             result.parent = symbol.parent;
37631                             result.target = symbol;
37632                             result.originatingImport = referenceParent;
37633                             if (symbol.valueDeclaration)
37634                                 result.valueDeclaration = symbol.valueDeclaration;
37635                             if (symbol.constEnumOnlyModule)
37636                                 result.constEnumOnlyModule = true;
37637                             if (symbol.members)
37638                                 result.members = ts.cloneMap(symbol.members);
37639                             if (symbol.exports)
37640                                 result.exports = ts.cloneMap(symbol.exports);
37641                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
37642                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
37643                             return result;
37644                         }
37645                     }
37646                 }
37647             }
37648             return symbol;
37649         }
37650         function hasExportAssignmentSymbol(moduleSymbol) {
37651             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
37652         }
37653         function getExportsOfModuleAsArray(moduleSymbol) {
37654             return symbolsToArray(getExportsOfModule(moduleSymbol));
37655         }
37656         function getExportsAndPropertiesOfModule(moduleSymbol) {
37657             var exports = getExportsOfModuleAsArray(moduleSymbol);
37658             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37659             if (exportEquals !== moduleSymbol) {
37660                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
37661             }
37662             return exports;
37663         }
37664         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
37665             var symbolTable = getExportsOfModule(moduleSymbol);
37666             if (symbolTable) {
37667                 return symbolTable.get(memberName);
37668             }
37669         }
37670         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
37671             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
37672             if (symbol) {
37673                 return symbol;
37674             }
37675             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37676             if (exportEquals === moduleSymbol) {
37677                 return undefined;
37678             }
37679             var type = getTypeOfSymbol(exportEquals);
37680             return type.flags & 131068 /* Primitive */ ||
37681                 ts.getObjectFlags(type) & 1 /* Class */ ||
37682                 isArrayOrTupleLikeType(type)
37683                 ? undefined
37684                 : getPropertyOfType(type, memberName);
37685         }
37686         function getExportsOfSymbol(symbol) {
37687             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
37688                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
37689                     symbol.exports || emptySymbols;
37690         }
37691         function getExportsOfModule(moduleSymbol) {
37692             var links = getSymbolLinks(moduleSymbol);
37693             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
37694         }
37695         /**
37696          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
37697          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
37698          */
37699         function extendExportSymbols(target, source, lookupTable, exportNode) {
37700             if (!source)
37701                 return;
37702             source.forEach(function (sourceSymbol, id) {
37703                 if (id === "default" /* Default */)
37704                     return;
37705                 var targetSymbol = target.get(id);
37706                 if (!targetSymbol) {
37707                     target.set(id, sourceSymbol);
37708                     if (lookupTable && exportNode) {
37709                         lookupTable.set(id, {
37710                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
37711                         });
37712                     }
37713                 }
37714                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
37715                     var collisionTracker = lookupTable.get(id);
37716                     if (!collisionTracker.exportsWithDuplicate) {
37717                         collisionTracker.exportsWithDuplicate = [exportNode];
37718                     }
37719                     else {
37720                         collisionTracker.exportsWithDuplicate.push(exportNode);
37721                     }
37722                 }
37723             });
37724         }
37725         function getExportsOfModuleWorker(moduleSymbol) {
37726             var visitedSymbols = [];
37727             // A module defined by an 'export=' consists of one export that needs to be resolved
37728             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
37729             return visit(moduleSymbol) || emptySymbols;
37730             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
37731             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
37732             function visit(symbol) {
37733                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
37734                     return;
37735                 }
37736                 var symbols = ts.cloneMap(symbol.exports);
37737                 // All export * declarations are collected in an __export symbol by the binder
37738                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
37739                 if (exportStars) {
37740                     var nestedSymbols = ts.createSymbolTable();
37741                     var lookupTable_1 = ts.createMap();
37742                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
37743                         var node = _a[_i];
37744                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
37745                         var exportedSymbols = visit(resolvedModule);
37746                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
37747                     }
37748                     lookupTable_1.forEach(function (_a, id) {
37749                         var exportsWithDuplicate = _a.exportsWithDuplicate;
37750                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
37751                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
37752                             return;
37753                         }
37754                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
37755                             var node = exportsWithDuplicate_1[_i];
37756                             diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id)));
37757                         }
37758                     });
37759                     extendExportSymbols(symbols, nestedSymbols);
37760                 }
37761                 return symbols;
37762             }
37763         }
37764         function getMergedSymbol(symbol) {
37765             var merged;
37766             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
37767         }
37768         function getSymbolOfNode(node) {
37769             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
37770         }
37771         function getParentOfSymbol(symbol) {
37772             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
37773         }
37774         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
37775             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
37776             var id = "" + getNodeId(containingFile);
37777             var links = getSymbolLinks(symbol);
37778             var results;
37779             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
37780                 return results;
37781             }
37782             if (containingFile && containingFile.imports) {
37783                 // Try to make an import using an import already in the enclosing file, if possible
37784                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
37785                     var importRef = _a[_i];
37786                     if (ts.nodeIsSynthesized(importRef))
37787                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
37788                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
37789                     if (!resolvedModule)
37790                         continue;
37791                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
37792                     if (!ref)
37793                         continue;
37794                     results = ts.append(results, resolvedModule);
37795                 }
37796                 if (ts.length(results)) {
37797                     (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
37798                     return results;
37799                 }
37800             }
37801             if (links.extendedContainers) {
37802                 return links.extendedContainers;
37803             }
37804             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
37805             var otherFiles = host.getSourceFiles();
37806             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
37807                 var file = otherFiles_1[_b];
37808                 if (!ts.isExternalModule(file))
37809                     continue;
37810                 var sym = getSymbolOfNode(file);
37811                 var ref = getAliasForSymbolInContainer(sym, symbol);
37812                 if (!ref)
37813                     continue;
37814                 results = ts.append(results, sym);
37815             }
37816             return links.extendedContainers = results || ts.emptyArray;
37817         }
37818         /**
37819          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
37820          * is just its' `.parent`, but for locals, this value is `undefined`
37821          */
37822         function getContainersOfSymbol(symbol, enclosingDeclaration) {
37823             var container = getParentOfSymbol(symbol);
37824             // Type parameters end up in the `members` lists but are not externally visible
37825             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
37826                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
37827                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
37828                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
37829                     return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
37830                 }
37831                 var res = ts.append(additionalContainers, container);
37832                 return ts.concatenate(res, reexportContainers);
37833             }
37834             var candidates = ts.mapDefined(symbol.declarations, function (d) {
37835                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
37836                     return getSymbolOfNode(d.parent);
37837                 }
37838                 if (ts.isClassExpression(d) && ts.isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isAccessExpression(d.parent.left) && ts.isEntityNameExpression(d.parent.left.expression)) {
37839                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
37840                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
37841                     }
37842                     checkExpressionCached(d.parent.left.expression);
37843                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
37844                 }
37845             });
37846             if (!ts.length(candidates)) {
37847                 return undefined;
37848             }
37849             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
37850             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
37851                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
37852             }
37853         }
37854         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
37855             var fileSymbol = getExternalModuleContainer(d);
37856             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
37857             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
37858         }
37859         function getAliasForSymbolInContainer(container, symbol) {
37860             if (container === getParentOfSymbol(symbol)) {
37861                 // fast path, `symbol` is either already the alias or isn't aliased
37862                 return symbol;
37863             }
37864             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
37865             // the container itself as the alias for the symbol
37866             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
37867             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
37868                 return container;
37869             }
37870             var exports = getExportsOfSymbol(container);
37871             var quick = exports.get(symbol.escapedName);
37872             if (quick && getSymbolIfSameReference(quick, symbol)) {
37873                 return quick;
37874             }
37875             return ts.forEachEntry(exports, function (exported) {
37876                 if (getSymbolIfSameReference(exported, symbol)) {
37877                     return exported;
37878                 }
37879             });
37880         }
37881         /**
37882          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
37883          */
37884         function getSymbolIfSameReference(s1, s2) {
37885             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
37886                 return s1;
37887             }
37888         }
37889         function getExportSymbolOfValueSymbolIfExported(symbol) {
37890             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
37891         }
37892         function symbolIsValue(symbol) {
37893             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
37894         }
37895         function findConstructorDeclaration(node) {
37896             var members = node.members;
37897             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
37898                 var member = members_3[_i];
37899                 if (member.kind === 162 /* Constructor */ && ts.nodeIsPresent(member.body)) {
37900                     return member;
37901                 }
37902             }
37903         }
37904         function createType(flags) {
37905             var result = new Type(checker, flags);
37906             typeCount++;
37907             result.id = typeCount;
37908             return result;
37909         }
37910         function createIntrinsicType(kind, intrinsicName, objectFlags) {
37911             if (objectFlags === void 0) { objectFlags = 0; }
37912             var type = createType(kind);
37913             type.intrinsicName = intrinsicName;
37914             type.objectFlags = objectFlags;
37915             return type;
37916         }
37917         function createBooleanType(trueFalseTypes) {
37918             var type = getUnionType(trueFalseTypes);
37919             type.flags |= 16 /* Boolean */;
37920             type.intrinsicName = "boolean";
37921             return type;
37922         }
37923         function createObjectType(objectFlags, symbol) {
37924             var type = createType(524288 /* Object */);
37925             type.objectFlags = objectFlags;
37926             type.symbol = symbol;
37927             type.members = undefined;
37928             type.properties = undefined;
37929             type.callSignatures = undefined;
37930             type.constructSignatures = undefined;
37931             type.stringIndexInfo = undefined;
37932             type.numberIndexInfo = undefined;
37933             return type;
37934         }
37935         function createTypeofType() {
37936             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
37937         }
37938         function createTypeParameter(symbol) {
37939             var type = createType(262144 /* TypeParameter */);
37940             if (symbol)
37941                 type.symbol = symbol;
37942             return type;
37943         }
37944         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
37945         // @, or #. A third underscore indicates an escaped form of an identifier that started
37946         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
37947         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
37948         function isReservedMemberName(name) {
37949             return name.charCodeAt(0) === 95 /* _ */ &&
37950                 name.charCodeAt(1) === 95 /* _ */ &&
37951                 name.charCodeAt(2) !== 95 /* _ */ &&
37952                 name.charCodeAt(2) !== 64 /* at */ &&
37953                 name.charCodeAt(2) !== 35 /* hash */;
37954         }
37955         function getNamedMembers(members) {
37956             var result;
37957             members.forEach(function (symbol, id) {
37958                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
37959                     (result || (result = [])).push(symbol);
37960                 }
37961             });
37962             return result || ts.emptyArray;
37963         }
37964         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37965             type.members = members;
37966             type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
37967             type.callSignatures = callSignatures;
37968             type.constructSignatures = constructSignatures;
37969             type.stringIndexInfo = stringIndexInfo;
37970             type.numberIndexInfo = numberIndexInfo;
37971             return type;
37972         }
37973         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37974             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37975         }
37976         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
37977             var result;
37978             var _loop_7 = function (location) {
37979                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
37980                 if (location.locals && !isGlobalSourceFile(location)) {
37981                     if (result = callback(location.locals)) {
37982                         return { value: result };
37983                     }
37984                 }
37985                 switch (location.kind) {
37986                     case 290 /* SourceFile */:
37987                         if (!ts.isExternalOrCommonJsModule(location)) {
37988                             break;
37989                         }
37990                     // falls through
37991                     case 249 /* ModuleDeclaration */:
37992                         var sym = getSymbolOfNode(location);
37993                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
37994                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
37995                         // to one another anyway)
37996                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
37997                             return { value: result };
37998                         }
37999                         break;
38000                     case 245 /* ClassDeclaration */:
38001                     case 214 /* ClassExpression */:
38002                     case 246 /* InterfaceDeclaration */:
38003                         // Type parameters are bound into `members` lists so they can merge across declarations
38004                         // This is troublesome, since in all other respects, they behave like locals :cries:
38005                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
38006                         // lookup logic in terms of `resolveName` would be nice
38007                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
38008                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
38009                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
38010                         var table_1;
38011                         // TODO: Should this filtered table be cached in some way?
38012                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
38013                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
38014                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
38015                             }
38016                         });
38017                         if (table_1 && (result = callback(table_1))) {
38018                             return { value: result };
38019                         }
38020                         break;
38021                 }
38022             };
38023             for (var location = enclosingDeclaration; location; location = location.parent) {
38024                 var state_2 = _loop_7(location);
38025                 if (typeof state_2 === "object")
38026                     return state_2.value;
38027             }
38028             return callback(globals);
38029         }
38030         function getQualifiedLeftMeaning(rightMeaning) {
38031             // If we are looking in value space, the parent meaning is value, other wise it is namespace
38032             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
38033         }
38034         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
38035             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
38036             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
38037                 return undefined;
38038             }
38039             var id = "" + getSymbolId(symbol);
38040             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
38041             if (!visitedSymbolTables) {
38042                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
38043             }
38044             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
38045             /**
38046              * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already)
38047              */
38048             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
38049                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
38050                     return undefined;
38051                 }
38052                 var result = trySymbolTable(symbols, ignoreQualification);
38053                 visitedSymbolTables.pop();
38054                 return result;
38055             }
38056             function canQualifySymbol(symbolFromSymbolTable, meaning) {
38057                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
38058                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
38059                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
38060                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
38061             }
38062             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
38063                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
38064                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
38065                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
38066                     // check the symbol can be qualified, it is only then this symbol is accessible
38067                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
38068                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
38069             }
38070             function trySymbolTable(symbols, ignoreQualification) {
38071                 // If symbol is directly available by its name in the symbol table
38072                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
38073                     return [symbol];
38074                 }
38075                 // Check if symbol is any of the aliases in scope
38076                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
38077                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
38078                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
38079                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
38080                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
38081                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
38082                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
38083                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
38084                         // See similar comment in `resolveName` for details
38085                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */))) {
38086                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
38087                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
38088                         if (candidate) {
38089                             return candidate;
38090                         }
38091                     }
38092                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
38093                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
38094                             return [symbol];
38095                         }
38096                     }
38097                 });
38098                 // If there's no result and we're looking at the global symbol table, treat `globalThis` like an alias and try to lookup thru that
38099                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
38100             }
38101             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
38102                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
38103                     return [symbolFromSymbolTable];
38104                 }
38105                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
38106                 // but only if the symbolFromSymbolTable can be qualified
38107                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
38108                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
38109                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
38110                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
38111                 }
38112             }
38113         }
38114         function needsQualification(symbol, enclosingDeclaration, meaning) {
38115             var qualify = false;
38116             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
38117                 // If symbol of this name is not available in the symbol table we are ok
38118                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
38119                 if (!symbolFromSymbolTable) {
38120                     // Continue to the next symbol table
38121                     return false;
38122                 }
38123                 // If the symbol with this name is present it should refer to the symbol
38124                 if (symbolFromSymbolTable === symbol) {
38125                     // No need to qualify
38126                     return true;
38127                 }
38128                 // Qualify if the symbol from symbol table has same meaning as expected
38129                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
38130                 if (symbolFromSymbolTable.flags & meaning) {
38131                     qualify = true;
38132                     return true;
38133                 }
38134                 // Continue to the next symbol table
38135                 return false;
38136             });
38137             return qualify;
38138         }
38139         function isPropertyOrMethodDeclarationSymbol(symbol) {
38140             if (symbol.declarations && symbol.declarations.length) {
38141                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
38142                     var declaration = _a[_i];
38143                     switch (declaration.kind) {
38144                         case 159 /* PropertyDeclaration */:
38145                         case 161 /* MethodDeclaration */:
38146                         case 163 /* GetAccessor */:
38147                         case 164 /* SetAccessor */:
38148                             continue;
38149                         default:
38150                             return false;
38151                     }
38152                 }
38153                 return true;
38154             }
38155             return false;
38156         }
38157         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
38158             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
38159             return access.accessibility === 0 /* Accessible */;
38160         }
38161         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
38162             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
38163             return access.accessibility === 0 /* Accessible */;
38164         }
38165         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
38166             if (!ts.length(symbols))
38167                 return;
38168             var hadAccessibleChain;
38169             var earlyModuleBail = false;
38170             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
38171                 var symbol = _a[_i];
38172                 // Symbol is accessible if it by itself is accessible
38173                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
38174                 if (accessibleSymbolChain) {
38175                     hadAccessibleChain = symbol;
38176                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
38177                     if (hasAccessibleDeclarations) {
38178                         return hasAccessibleDeclarations;
38179                     }
38180                 }
38181                 else {
38182                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
38183                         if (shouldComputeAliasesToMakeVisible) {
38184                             earlyModuleBail = true;
38185                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
38186                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
38187                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
38188                             // all other visibility options (in order to capture the possible aliases used to reference the module)
38189                             continue;
38190                         }
38191                         // Any meaning of a module symbol is always accessible via an `import` type
38192                         return {
38193                             accessibility: 0 /* Accessible */
38194                         };
38195                     }
38196                 }
38197                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
38198                 // It could be a qualified symbol and hence verify the path
38199                 // e.g.:
38200                 // module m {
38201                 //     export class c {
38202                 //     }
38203                 // }
38204                 // const x: typeof m.c
38205                 // In the above example when we start with checking if typeof m.c symbol is accessible,
38206                 // we are going to see if c can be accessed in scope directly.
38207                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
38208                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
38209                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
38210                 // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
38211                 // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
38212                 // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
38213                 var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
38214                 if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
38215                     if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
38216                         containers = [getSymbolOfNode(firstDecl.parent)];
38217                     }
38218                 }
38219                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
38220                 if (parentResult) {
38221                     return parentResult;
38222                 }
38223             }
38224             if (earlyModuleBail) {
38225                 return {
38226                     accessibility: 0 /* Accessible */
38227                 };
38228             }
38229             if (hadAccessibleChain) {
38230                 return {
38231                     accessibility: 1 /* NotAccessible */,
38232                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
38233                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
38234                 };
38235             }
38236         }
38237         /**
38238          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
38239          *
38240          * @param symbol a Symbol to check if accessible
38241          * @param enclosingDeclaration a Node containing reference to the symbol
38242          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
38243          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
38244          */
38245         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
38246             if (symbol && enclosingDeclaration) {
38247                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
38248                 if (result) {
38249                     return result;
38250                 }
38251                 // This could be a symbol that is not exported in the external module
38252                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
38253                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
38254                 if (symbolExternalModule) {
38255                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
38256                     if (symbolExternalModule !== enclosingExternalModule) {
38257                         // name from different external module that is not visible
38258                         return {
38259                             accessibility: 2 /* CannotBeNamed */,
38260                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38261                             errorModuleName: symbolToString(symbolExternalModule)
38262                         };
38263                     }
38264                 }
38265                 // Just a local name that is not accessible
38266                 return {
38267                     accessibility: 1 /* NotAccessible */,
38268                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38269                 };
38270             }
38271             return { accessibility: 0 /* Accessible */ };
38272         }
38273         function getExternalModuleContainer(declaration) {
38274             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
38275             return node && getSymbolOfNode(node);
38276         }
38277         function hasExternalModuleSymbol(declaration) {
38278             return ts.isAmbientModule(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38279         }
38280         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
38281             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38282         }
38283         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
38284             var aliasesToMakeVisible;
38285             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 75 /* Identifier */; }), getIsDeclarationVisible)) {
38286                 return undefined;
38287             }
38288             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
38289             function getIsDeclarationVisible(declaration) {
38290                 if (!isDeclarationVisible(declaration)) {
38291                     // Mark the unexported alias as visible if its parent is visible
38292                     // because these kind of aliases can be used to name types in declaration file
38293                     var anyImportSyntax = getAnyImportSyntax(declaration);
38294                     if (anyImportSyntax &&
38295                         !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
38296                         isDeclarationVisible(anyImportSyntax.parent)) {
38297                         return addVisibleAlias(declaration, anyImportSyntax);
38298                     }
38299                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
38300                         !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
38301                         isDeclarationVisible(declaration.parent.parent.parent)) {
38302                         return addVisibleAlias(declaration, declaration.parent.parent);
38303                     }
38304                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
38305                         && !ts.hasModifier(declaration, 1 /* Export */)
38306                         && isDeclarationVisible(declaration.parent)) {
38307                         return addVisibleAlias(declaration, declaration);
38308                     }
38309                     // Declaration is not visible
38310                     return false;
38311                 }
38312                 return true;
38313             }
38314             function addVisibleAlias(declaration, aliasingStatement) {
38315                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
38316                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
38317                 // since we will do the emitting later in trackSymbol.
38318                 if (shouldComputeAliasToMakeVisible) {
38319                     getNodeLinks(declaration).isVisible = true;
38320                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
38321                 }
38322                 return true;
38323             }
38324         }
38325         function isEntityNameVisible(entityName, enclosingDeclaration) {
38326             // get symbol of the first identifier of the entityName
38327             var meaning;
38328             if (entityName.parent.kind === 172 /* TypeQuery */ ||
38329                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
38330                 entityName.parent.kind === 154 /* ComputedPropertyName */) {
38331                 // Typeof value
38332                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
38333             }
38334             else if (entityName.kind === 153 /* QualifiedName */ || entityName.kind === 194 /* PropertyAccessExpression */ ||
38335                 entityName.parent.kind === 253 /* ImportEqualsDeclaration */) {
38336                 // Left identifier from type reference or TypeAlias
38337                 // Entity name of the import declaration
38338                 meaning = 1920 /* Namespace */;
38339             }
38340             else {
38341                 // Type Reference or TypeAlias entity = Identifier
38342                 meaning = 788968 /* Type */;
38343             }
38344             var firstIdentifier = ts.getFirstIdentifier(entityName);
38345             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
38346             // Verify if the symbol is accessible
38347             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
38348                 accessibility: 1 /* NotAccessible */,
38349                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
38350                 errorNode: firstIdentifier
38351             };
38352         }
38353         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
38354             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
38355             var nodeFlags = 70221824 /* IgnoreErrors */;
38356             if (flags & 2 /* UseOnlyExternalAliasing */) {
38357                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
38358             }
38359             if (flags & 1 /* WriteTypeParametersOrArguments */) {
38360                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
38361             }
38362             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
38363                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
38364             }
38365             if (flags & 16 /* DoNotIncludeSymbolChain */) {
38366                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
38367             }
38368             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
38369             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
38370             function symbolToStringWorker(writer) {
38371                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
38372                 var printer = ts.createPrinter({ removeComments: true });
38373                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38374                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
38375                 return writer;
38376             }
38377         }
38378         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
38379             if (flags === void 0) { flags = 0 /* None */; }
38380             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
38381             function signatureToStringWorker(writer) {
38382                 var sigOutput;
38383                 if (flags & 262144 /* WriteArrowStyleSignature */) {
38384                     sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructorType */ : 170 /* FunctionType */;
38385                 }
38386                 else {
38387                     sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructSignature */ : 165 /* CallSignature */;
38388                 }
38389                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
38390                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
38391                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38392                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
38393                 return writer;
38394             }
38395         }
38396         function typeToString(type, enclosingDeclaration, flags, writer) {
38397             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
38398             if (writer === void 0) { writer = ts.createTextWriter(""); }
38399             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
38400             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
38401             if (typeNode === undefined)
38402                 return ts.Debug.fail("should always get typenode");
38403             var options = { removeComments: true };
38404             var printer = ts.createPrinter(options);
38405             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38406             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
38407             var result = writer.getText();
38408             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
38409             if (maxLength && result && result.length >= maxLength) {
38410                 return result.substr(0, maxLength - "...".length) + "...";
38411             }
38412             return result;
38413         }
38414         function getTypeNamesForErrorDisplay(left, right) {
38415             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
38416             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
38417             if (leftStr === rightStr) {
38418                 leftStr = typeToString(left, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38419                 rightStr = typeToString(right, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38420             }
38421             return [leftStr, rightStr];
38422         }
38423         function symbolValueDeclarationIsContextSensitive(symbol) {
38424             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
38425         }
38426         function toNodeBuilderFlags(flags) {
38427             if (flags === void 0) { flags = 0 /* None */; }
38428             return flags & 814775659 /* NodeBuilderFlagsMask */;
38429         }
38430         function createNodeBuilder() {
38431             return {
38432                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
38433                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
38434                 },
38435                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
38436                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
38437                 },
38438                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
38439                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
38440                 },
38441                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38442                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
38443                 },
38444                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38445                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
38446                 },
38447                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
38448                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
38449                 },
38450                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
38451                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
38452                 },
38453                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
38454                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
38455                 },
38456                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
38457                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
38458                 },
38459             };
38460             function withContext(enclosingDeclaration, flags, tracker, cb) {
38461                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
38462                 var context = {
38463                     enclosingDeclaration: enclosingDeclaration,
38464                     flags: flags || 0 /* None */,
38465                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
38466                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
38467                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
38468                             getSourceFiles: function () { return host.getSourceFiles(); },
38469                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
38470                             getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks),
38471                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
38472                             redirectTargetsMap: host.redirectTargetsMap,
38473                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
38474                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
38475                             fileExists: function (fileName) { return host.fileExists(fileName); },
38476                         } : undefined },
38477                     encounteredError: false,
38478                     visitedTypes: undefined,
38479                     symbolDepth: undefined,
38480                     inferTypeParameters: undefined,
38481                     approximateLength: 0
38482                 };
38483                 var resultingNode = cb(context);
38484                 return context.encounteredError ? undefined : resultingNode;
38485             }
38486             function checkTruncationLength(context) {
38487                 if (context.truncating)
38488                     return context.truncating;
38489                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
38490             }
38491             function typeToTypeNodeHelper(type, context) {
38492                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
38493                     cancellationToken.throwIfCancellationRequested();
38494                 }
38495                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
38496                 context.flags &= ~8388608 /* InTypeAlias */;
38497                 if (!type) {
38498                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38499                         context.encounteredError = true;
38500                         return undefined; // TODO: GH#18217
38501                     }
38502                     context.approximateLength += 3;
38503                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38504                 }
38505                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
38506                     type = getReducedType(type);
38507                 }
38508                 if (type.flags & 1 /* Any */) {
38509                     context.approximateLength += 3;
38510                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38511                 }
38512                 if (type.flags & 2 /* Unknown */) {
38513                     return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
38514                 }
38515                 if (type.flags & 4 /* String */) {
38516                     context.approximateLength += 6;
38517                     return ts.createKeywordTypeNode(143 /* StringKeyword */);
38518                 }
38519                 if (type.flags & 8 /* Number */) {
38520                     context.approximateLength += 6;
38521                     return ts.createKeywordTypeNode(140 /* NumberKeyword */);
38522                 }
38523                 if (type.flags & 64 /* BigInt */) {
38524                     context.approximateLength += 6;
38525                     return ts.createKeywordTypeNode(151 /* BigIntKeyword */);
38526                 }
38527                 if (type.flags & 16 /* Boolean */) {
38528                     context.approximateLength += 7;
38529                     return ts.createKeywordTypeNode(128 /* BooleanKeyword */);
38530                 }
38531                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
38532                     var parentSymbol = getParentOfSymbol(type.symbol);
38533                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
38534                     var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
38535                         ? parentName
38536                         : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
38537                     return enumLiteralName;
38538                 }
38539                 if (type.flags & 1056 /* EnumLike */) {
38540                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
38541                 }
38542                 if (type.flags & 128 /* StringLiteral */) {
38543                     context.approximateLength += (type.value.length + 2);
38544                     return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
38545                 }
38546                 if (type.flags & 256 /* NumberLiteral */) {
38547                     var value = type.value;
38548                     context.approximateLength += ("" + value).length;
38549                     return ts.createLiteralTypeNode(value < 0 ? ts.createPrefix(40 /* MinusToken */, ts.createLiteral(-value)) : ts.createLiteral(value));
38550                 }
38551                 if (type.flags & 2048 /* BigIntLiteral */) {
38552                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
38553                     return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
38554                 }
38555                 if (type.flags & 512 /* BooleanLiteral */) {
38556                     context.approximateLength += type.intrinsicName.length;
38557                     return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
38558                 }
38559                 if (type.flags & 8192 /* UniqueESSymbol */) {
38560                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
38561                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38562                             context.approximateLength += 6;
38563                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
38564                         }
38565                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
38566                             context.tracker.reportInaccessibleUniqueSymbolError();
38567                         }
38568                     }
38569                     context.approximateLength += 13;
38570                     return ts.createTypeOperatorNode(147 /* UniqueKeyword */, ts.createKeywordTypeNode(144 /* SymbolKeyword */));
38571                 }
38572                 if (type.flags & 16384 /* Void */) {
38573                     context.approximateLength += 4;
38574                     return ts.createKeywordTypeNode(110 /* VoidKeyword */);
38575                 }
38576                 if (type.flags & 32768 /* Undefined */) {
38577                     context.approximateLength += 9;
38578                     return ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
38579                 }
38580                 if (type.flags & 65536 /* Null */) {
38581                     context.approximateLength += 4;
38582                     return ts.createKeywordTypeNode(100 /* NullKeyword */);
38583                 }
38584                 if (type.flags & 131072 /* Never */) {
38585                     context.approximateLength += 5;
38586                     return ts.createKeywordTypeNode(137 /* NeverKeyword */);
38587                 }
38588                 if (type.flags & 4096 /* ESSymbol */) {
38589                     context.approximateLength += 6;
38590                     return ts.createKeywordTypeNode(144 /* SymbolKeyword */);
38591                 }
38592                 if (type.flags & 67108864 /* NonPrimitive */) {
38593                     context.approximateLength += 6;
38594                     return ts.createKeywordTypeNode(141 /* ObjectKeyword */);
38595                 }
38596                 if (isThisTypeParameter(type)) {
38597                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
38598                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
38599                             context.encounteredError = true;
38600                         }
38601                         if (context.tracker.reportInaccessibleThisError) {
38602                             context.tracker.reportInaccessibleThisError();
38603                         }
38604                     }
38605                     context.approximateLength += 4;
38606                     return ts.createThis();
38607                 }
38608                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
38609                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
38610                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
38611                         return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
38612                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
38613                 }
38614                 var objectFlags = ts.getObjectFlags(type);
38615                 if (objectFlags & 4 /* Reference */) {
38616                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38617                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
38618                 }
38619                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
38620                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
38621                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
38622                         return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
38623                     }
38624                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
38625                         type.flags & 262144 /* TypeParameter */ &&
38626                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38627                         var name = typeParameterToName(type, context);
38628                         context.approximateLength += ts.idText(name).length;
38629                         return ts.createTypeReferenceNode(ts.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
38630                     }
38631                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
38632                     return type.symbol
38633                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
38634                         : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
38635                 }
38636                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
38637                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
38638                     if (ts.length(types) === 1) {
38639                         return typeToTypeNodeHelper(types[0], context);
38640                     }
38641                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
38642                     if (typeNodes && typeNodes.length > 0) {
38643                         var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 178 /* UnionType */ : 179 /* IntersectionType */, typeNodes);
38644                         return unionOrIntersectionTypeNode;
38645                     }
38646                     else {
38647                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38648                             context.encounteredError = true;
38649                         }
38650                         return undefined; // TODO: GH#18217
38651                     }
38652                 }
38653                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
38654                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38655                     // The type is an object literal type.
38656                     return createAnonymousTypeNode(type);
38657                 }
38658                 if (type.flags & 4194304 /* Index */) {
38659                     var indexedType = type.type;
38660                     context.approximateLength += 6;
38661                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
38662                     return ts.createTypeOperatorNode(indexTypeNode);
38663                 }
38664                 if (type.flags & 8388608 /* IndexedAccess */) {
38665                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
38666                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
38667                     context.approximateLength += 2;
38668                     return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
38669                 }
38670                 if (type.flags & 16777216 /* Conditional */) {
38671                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
38672                     var saveInferTypeParameters = context.inferTypeParameters;
38673                     context.inferTypeParameters = type.root.inferTypeParameters;
38674                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
38675                     context.inferTypeParameters = saveInferTypeParameters;
38676                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
38677                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
38678                     context.approximateLength += 15;
38679                     return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
38680                 }
38681                 if (type.flags & 33554432 /* Substitution */) {
38682                     return typeToTypeNodeHelper(type.baseType, context);
38683                 }
38684                 return ts.Debug.fail("Should be unreachable.");
38685                 function typeToTypeNodeOrCircularityElision(type) {
38686                     var _a, _b;
38687                     if (type.flags & 1048576 /* Union */) {
38688                         if (context.visitedTypes && context.visitedTypes.has("" + getTypeId(type))) {
38689                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
38690                                 context.encounteredError = true;
38691                                 (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportCyclicStructureError) === null || _b === void 0 ? void 0 : _b.call(_a);
38692                             }
38693                             return createElidedInformationPlaceholder(context);
38694                         }
38695                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
38696                     }
38697                     return typeToTypeNodeHelper(type, context);
38698                 }
38699                 function createMappedTypeNodeFromType(type) {
38700                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38701                     var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
38702                     var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
38703                     var appropriateConstraintTypeNode;
38704                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
38705                         // We have a { [P in keyof T]: X }
38706                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
38707                         appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
38708                     }
38709                     else {
38710                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
38711                     }
38712                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
38713                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
38714                     var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
38715                     context.approximateLength += 10;
38716                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
38717                 }
38718                 function createAnonymousTypeNode(type) {
38719                     var typeId = "" + type.id;
38720                     var symbol = type.symbol;
38721                     if (symbol) {
38722                         if (isJSConstructor(symbol.valueDeclaration)) {
38723                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
38724                             var isInstanceType = type === getDeclaredTypeOfClassOrInterface(symbol) ? 788968 /* Type */ : 111551 /* Value */;
38725                             return symbolToTypeNode(symbol, context, isInstanceType);
38726                         }
38727                         // Always use 'typeof T' for type of class, enum, and module objects
38728                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 214 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
38729                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
38730                             shouldWriteTypeOfFunctionSymbol()) {
38731                             return symbolToTypeNode(symbol, context, 111551 /* Value */);
38732                         }
38733                         else if (context.visitedTypes && context.visitedTypes.has(typeId)) {
38734                             // If type is an anonymous type literal in a type alias declaration, use type alias name
38735                             var typeAlias = getTypeAliasForTypeLiteral(type);
38736                             if (typeAlias) {
38737                                 // The specified symbol flags need to be reinterpreted as type flags
38738                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
38739                             }
38740                             else {
38741                                 return createElidedInformationPlaceholder(context);
38742                             }
38743                         }
38744                         else {
38745                             return visitAndTransformType(type, createTypeNodeFromObjectType);
38746                         }
38747                     }
38748                     else {
38749                         // Anonymous types without a symbol are never circular.
38750                         return createTypeNodeFromObjectType(type);
38751                     }
38752                     function shouldWriteTypeOfFunctionSymbol() {
38753                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
38754                             ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
38755                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
38756                             (symbol.parent || // is exported function symbol
38757                                 ts.forEach(symbol.declarations, function (declaration) {
38758                                     return declaration.parent.kind === 290 /* SourceFile */ || declaration.parent.kind === 250 /* ModuleBlock */;
38759                                 }));
38760                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
38761                             // typeof is allowed only for static/non local functions
38762                             return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively
38763                                 (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed
38764                         }
38765                     }
38766                 }
38767                 function visitAndTransformType(type, transform) {
38768                     var typeId = "" + type.id;
38769                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
38770                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
38771                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
38772                             undefined;
38773                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
38774                     // of types allows us to catch circular references to instantiations of the same anonymous type
38775                     if (!context.visitedTypes) {
38776                         context.visitedTypes = ts.createMap();
38777                     }
38778                     if (id && !context.symbolDepth) {
38779                         context.symbolDepth = ts.createMap();
38780                     }
38781                     var depth;
38782                     if (id) {
38783                         depth = context.symbolDepth.get(id) || 0;
38784                         if (depth > 10) {
38785                             return createElidedInformationPlaceholder(context);
38786                         }
38787                         context.symbolDepth.set(id, depth + 1);
38788                     }
38789                     context.visitedTypes.set(typeId, true);
38790                     var result = transform(type);
38791                     context.visitedTypes.delete(typeId);
38792                     if (id) {
38793                         context.symbolDepth.set(id, depth);
38794                     }
38795                     return result;
38796                 }
38797                 function createTypeNodeFromObjectType(type) {
38798                     if (isGenericMappedType(type)) {
38799                         return createMappedTypeNodeFromType(type);
38800                     }
38801                     var resolved = resolveStructuredTypeMembers(type);
38802                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
38803                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
38804                             context.approximateLength += 2;
38805                             return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
38806                         }
38807                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
38808                             var signature = resolved.callSignatures[0];
38809                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 170 /* FunctionType */, context);
38810                             return signatureNode;
38811                         }
38812                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
38813                             var signature = resolved.constructSignatures[0];
38814                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 171 /* ConstructorType */, context);
38815                             return signatureNode;
38816                         }
38817                     }
38818                     var savedFlags = context.flags;
38819                     context.flags |= 4194304 /* InObjectTypeLiteral */;
38820                     var members = createTypeNodesFromResolvedType(resolved);
38821                     context.flags = savedFlags;
38822                     var typeLiteralNode = ts.createTypeLiteralNode(members);
38823                     context.approximateLength += 2;
38824                     return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
38825                 }
38826                 function typeReferenceToTypeNode(type) {
38827                     var typeArguments = getTypeArguments(type);
38828                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
38829                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
38830                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
38831                             return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
38832                         }
38833                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
38834                         var arrayType = ts.createArrayTypeNode(elementType);
38835                         return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, arrayType);
38836                     }
38837                     else if (type.target.objectFlags & 8 /* Tuple */) {
38838                         if (typeArguments.length > 0) {
38839                             var arity = getTypeReferenceArity(type);
38840                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
38841                             var hasRestElement = type.target.hasRestElement;
38842                             if (tupleConstituentNodes) {
38843                                 for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
38844                                     tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
38845                                         ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
38846                                         ts.createOptionalTypeNode(tupleConstituentNodes[i]);
38847                                 }
38848                                 var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
38849                                 return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38850                             }
38851                         }
38852                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
38853                             var tupleTypeNode = ts.createTupleTypeNode([]);
38854                             return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38855                         }
38856                         context.encounteredError = true;
38857                         return undefined; // TODO: GH#18217
38858                     }
38859                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
38860                         type.symbol.valueDeclaration &&
38861                         ts.isClassLike(type.symbol.valueDeclaration) &&
38862                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38863                         return createAnonymousTypeNode(type);
38864                     }
38865                     else {
38866                         var outerTypeParameters = type.target.outerTypeParameters;
38867                         var i = 0;
38868                         var resultType = void 0;
38869                         if (outerTypeParameters) {
38870                             var length_2 = outerTypeParameters.length;
38871                             while (i < length_2) {
38872                                 // Find group of type arguments for type parameters with the same declaring container.
38873                                 var start = i;
38874                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
38875                                 do {
38876                                     i++;
38877                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
38878                                 // When type parameters are their own type arguments for the whole group (i.e. we have
38879                                 // the default outer type arguments), we don't show the group.
38880                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
38881                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
38882                                     var flags_2 = context.flags;
38883                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38884                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
38885                                     context.flags = flags_2;
38886                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
38887                                 }
38888                             }
38889                         }
38890                         var typeArgumentNodes = void 0;
38891                         if (typeArguments.length > 0) {
38892                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
38893                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
38894                         }
38895                         var flags = context.flags;
38896                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38897                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
38898                         context.flags = flags;
38899                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
38900                     }
38901                 }
38902                 function appendReferenceToType(root, ref) {
38903                     if (ts.isImportTypeNode(root)) {
38904                         // first shift type arguments
38905                         var innerParams = root.typeArguments;
38906                         if (root.qualifier) {
38907                             (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
38908                         }
38909                         root.typeArguments = ref.typeArguments;
38910                         // then move qualifiers
38911                         var ids = getAccessStack(ref);
38912                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
38913                             var id = ids_1[_i];
38914                             root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
38915                         }
38916                         return root;
38917                     }
38918                     else {
38919                         // first shift type arguments
38920                         var innerParams = root.typeArguments;
38921                         (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
38922                         root.typeArguments = ref.typeArguments;
38923                         // then move qualifiers
38924                         var ids = getAccessStack(ref);
38925                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
38926                             var id = ids_2[_a];
38927                             root.typeName = ts.createQualifiedName(root.typeName, id);
38928                         }
38929                         return root;
38930                     }
38931                 }
38932                 function getAccessStack(ref) {
38933                     var state = ref.typeName;
38934                     var ids = [];
38935                     while (!ts.isIdentifier(state)) {
38936                         ids.unshift(state.right);
38937                         state = state.left;
38938                     }
38939                     ids.unshift(state);
38940                     return ids;
38941                 }
38942                 function createTypeNodesFromResolvedType(resolvedType) {
38943                     if (checkTruncationLength(context)) {
38944                         return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
38945                     }
38946                     var typeElements = [];
38947                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
38948                         var signature = _a[_i];
38949                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 165 /* CallSignature */, context));
38950                     }
38951                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
38952                         var signature = _c[_b];
38953                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 166 /* ConstructSignature */, context));
38954                     }
38955                     if (resolvedType.stringIndexInfo) {
38956                         var indexSignature = void 0;
38957                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
38958                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
38959                             indexSignature.type = createElidedInformationPlaceholder(context);
38960                         }
38961                         else {
38962                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
38963                         }
38964                         typeElements.push(indexSignature);
38965                     }
38966                     if (resolvedType.numberIndexInfo) {
38967                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
38968                     }
38969                     var properties = resolvedType.properties;
38970                     if (!properties) {
38971                         return typeElements;
38972                     }
38973                     var i = 0;
38974                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
38975                         var propertySymbol = properties_1[_d];
38976                         i++;
38977                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
38978                             if (propertySymbol.flags & 4194304 /* Prototype */) {
38979                                 continue;
38980                             }
38981                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
38982                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
38983                             }
38984                         }
38985                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
38986                             typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
38987                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
38988                             break;
38989                         }
38990                         addPropertyToElementList(propertySymbol, context, typeElements);
38991                     }
38992                     return typeElements.length ? typeElements : undefined;
38993                 }
38994             }
38995             function createElidedInformationPlaceholder(context) {
38996                 context.approximateLength += 3;
38997                 if (!(context.flags & 1 /* NoTruncation */)) {
38998                     return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
38999                 }
39000                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39001             }
39002             function addPropertyToElementList(propertySymbol, context, typeElements) {
39003                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
39004                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
39005                     anyType : getTypeOfSymbol(propertySymbol);
39006                 var saveEnclosingDeclaration = context.enclosingDeclaration;
39007                 context.enclosingDeclaration = undefined;
39008                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
39009                     var decl = ts.first(propertySymbol.declarations);
39010                     if (hasLateBindableName(decl)) {
39011                         if (ts.isBinaryExpression(decl)) {
39012                             var name = ts.getNameOfDeclaration(decl);
39013                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
39014                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
39015                             }
39016                         }
39017                         else {
39018                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
39019                         }
39020                     }
39021                 }
39022                 context.enclosingDeclaration = saveEnclosingDeclaration;
39023                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
39024                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
39025                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined;
39026                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
39027                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
39028                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
39029                         var signature = signatures_1[_i];
39030                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 160 /* MethodSignature */, context);
39031                         methodDeclaration.name = propertyName;
39032                         methodDeclaration.questionToken = optionalToken;
39033                         typeElements.push(preserveCommentsOn(methodDeclaration));
39034                     }
39035                 }
39036                 else {
39037                     var savedFlags = context.flags;
39038                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
39039                     var propertyTypeNode = void 0;
39040                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
39041                         propertyTypeNode = createElidedInformationPlaceholder(context);
39042                     }
39043                     else {
39044                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
39045                     }
39046                     context.flags = savedFlags;
39047                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined;
39048                     if (modifiers) {
39049                         context.approximateLength += 9;
39050                     }
39051                     var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, 
39052                     /*initializer*/ undefined);
39053                     typeElements.push(preserveCommentsOn(propertySignature));
39054                 }
39055                 function preserveCommentsOn(node) {
39056                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; })) {
39057                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; });
39058                         var commentText = d.comment;
39059                         if (commentText) {
39060                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
39061                         }
39062                     }
39063                     else if (propertySymbol.valueDeclaration) {
39064                         // Copy comments to node for declaration emit
39065                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
39066                     }
39067                     return node;
39068                 }
39069             }
39070             function mapToTypeNodes(types, context, isBareList) {
39071                 if (ts.some(types)) {
39072                     if (checkTruncationLength(context)) {
39073                         if (!isBareList) {
39074                             return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
39075                         }
39076                         else if (types.length > 2) {
39077                             return [
39078                                 typeToTypeNodeHelper(types[0], context),
39079                                 ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
39080                                 typeToTypeNodeHelper(types[types.length - 1], context)
39081                             ];
39082                         }
39083                     }
39084                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
39085                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
39086                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
39087                     var result_3 = [];
39088                     var i = 0;
39089                     for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
39090                         var type = types_1[_i];
39091                         i++;
39092                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
39093                             result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
39094                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
39095                             if (typeNode_1) {
39096                                 result_3.push(typeNode_1);
39097                             }
39098                             break;
39099                         }
39100                         context.approximateLength += 2; // Account for whitespace + separator
39101                         var typeNode = typeToTypeNodeHelper(type, context);
39102                         if (typeNode) {
39103                             result_3.push(typeNode);
39104                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
39105                                 seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]);
39106                             }
39107                         }
39108                     }
39109                     if (seenNames) {
39110                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
39111                         // occurrences of the same name actually come from different
39112                         // namespaces, go through the single-identifier type reference nodes
39113                         // we just generated, and see if any names were generated more than
39114                         // once while referring to different types. If so, regenerate the
39115                         // type node for each entry by that name with the
39116                         // `UseFullyQualifiedType` flag enabled.
39117                         var saveContextFlags = context.flags;
39118                         context.flags |= 64 /* UseFullyQualifiedType */;
39119                         seenNames.forEach(function (types) {
39120                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
39121                                 var a = _a[0];
39122                                 var b = _b[0];
39123                                 return typesAreSameReference(a, b);
39124                             })) {
39125                                 for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
39126                                     var _a = types_2[_i], type = _a[0], resultIndex = _a[1];
39127                                     result_3[resultIndex] = typeToTypeNodeHelper(type, context);
39128                                 }
39129                             }
39130                         });
39131                         context.flags = saveContextFlags;
39132                     }
39133                     return result_3;
39134                 }
39135             }
39136             function typesAreSameReference(a, b) {
39137                 return a === b
39138                     || !!a.symbol && a.symbol === b.symbol
39139                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
39140             }
39141             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
39142                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
39143                 var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */);
39144                 var indexingParameter = ts.createParameter(
39145                 /*decorators*/ undefined, 
39146                 /*modifiers*/ undefined, 
39147                 /*dotDotDotToken*/ undefined, name, 
39148                 /*questionToken*/ undefined, indexerTypeNode, 
39149                 /*initializer*/ undefined);
39150                 var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
39151                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
39152                     context.encounteredError = true;
39153                 }
39154                 context.approximateLength += (name.length + 4);
39155                 return ts.createIndexSignature(
39156                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
39157             }
39158             function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) {
39159                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
39160                 if (suppressAny)
39161                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
39162                 var typeParameters;
39163                 var typeArguments;
39164                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
39165                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
39166                 }
39167                 else {
39168                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
39169                 }
39170                 var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); });
39171                 if (signature.thisParameter) {
39172                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
39173                     parameters.unshift(thisParameter);
39174                 }
39175                 var returnTypeNode;
39176                 var typePredicate = getTypePredicateOfSignature(signature);
39177                 if (typePredicate) {
39178                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39179                         ts.createToken(124 /* AssertsKeyword */) :
39180                         undefined;
39181                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39182                         ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
39183                         ts.createThisTypeNode();
39184                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
39185                     returnTypeNode = ts.createTypePredicateNodeWithModifier(assertsModifier, parameterName, typeNode);
39186                 }
39187                 else {
39188                     var returnType = getReturnTypeOfSignature(signature);
39189                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
39190                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports);
39191                     }
39192                     else if (!suppressAny) {
39193                         returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */);
39194                     }
39195                 }
39196                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
39197                 return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
39198             }
39199             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
39200                 var savedContextFlags = context.flags;
39201                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
39202                 var name = typeParameterToName(type, context);
39203                 var defaultParameter = getDefaultFromTypeParameter(type);
39204                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
39205                 context.flags = savedContextFlags;
39206                 return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
39207             }
39208             function typeParameterToDeclaration(type, context, constraint) {
39209                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
39210                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
39211                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
39212             }
39213             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
39214                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */);
39215                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
39216                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */);
39217                 }
39218                 var parameterType = getTypeOfSymbol(parameterSymbol);
39219                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
39220                     parameterType = getOptionalType(parameterType);
39221                 }
39222                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
39223                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
39224                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
39225                 var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined;
39226                 var name = parameterDeclaration ? parameterDeclaration.name ?
39227                     parameterDeclaration.name.kind === 75 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
39228                         parameterDeclaration.name.kind === 153 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
39229                             cloneBindingName(parameterDeclaration.name) :
39230                     ts.symbolName(parameterSymbol) :
39231                     ts.symbolName(parameterSymbol);
39232                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
39233                 var questionToken = isOptional ? ts.createToken(57 /* QuestionToken */) : undefined;
39234                 var parameterNode = ts.createParameter(
39235                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
39236                 /*initializer*/ undefined);
39237                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
39238                 return parameterNode;
39239                 function cloneBindingName(node) {
39240                     return elideInitializerAndSetEmitFlags(node);
39241                     function elideInitializerAndSetEmitFlags(node) {
39242                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
39243                             trackComputedName(node.expression, context.enclosingDeclaration, context);
39244                         }
39245                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
39246                         var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
39247                         if (clone.kind === 191 /* BindingElement */) {
39248                             clone.initializer = undefined;
39249                         }
39250                         return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
39251                     }
39252                 }
39253             }
39254             function trackComputedName(accessExpression, enclosingDeclaration, context) {
39255                 if (!context.tracker.trackSymbol)
39256                     return;
39257                 // get symbol of the first identifier of the entityName
39258                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
39259                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
39260                 if (name) {
39261                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
39262                 }
39263             }
39264             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
39265                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
39266                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
39267             }
39268             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
39269                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
39270                 var chain;
39271                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
39272                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
39273                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
39274                     ts.Debug.assert(chain && chain.length > 0);
39275                 }
39276                 else {
39277                     chain = [symbol];
39278                 }
39279                 return chain;
39280                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
39281                 function getSymbolChain(symbol, meaning, endOfChain) {
39282                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
39283                     var parentSpecifiers;
39284                     if (!accessibleSymbolChain ||
39285                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
39286                         // Go up and add our parent.
39287                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
39288                         if (ts.length(parents_1)) {
39289                             parentSpecifiers = parents_1.map(function (symbol) {
39290                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
39291                                     ? getSpecifierForModuleSymbol(symbol, context)
39292                                     : undefined;
39293                             });
39294                             var indices = parents_1.map(function (_, i) { return i; });
39295                             indices.sort(sortByBestName);
39296                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
39297                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
39298                                 var parent = sortedParents_1[_i];
39299                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
39300                                 if (parentChain) {
39301                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
39302                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
39303                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
39304                                         // No need to lookup an alias for the symbol in itself
39305                                         accessibleSymbolChain = parentChain;
39306                                         break;
39307                                     }
39308                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
39309                                     break;
39310                                 }
39311                             }
39312                         }
39313                     }
39314                     if (accessibleSymbolChain) {
39315                         return accessibleSymbolChain;
39316                     }
39317                     if (
39318                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
39319                     endOfChain ||
39320                         // If a parent symbol is an anonymous type, don't write it.
39321                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
39322                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
39323                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39324                             return;
39325                         }
39326                         return [symbol];
39327                     }
39328                     function sortByBestName(a, b) {
39329                         var specifierA = parentSpecifiers[a];
39330                         var specifierB = parentSpecifiers[b];
39331                         if (specifierA && specifierB) {
39332                             var isBRelative = ts.pathIsRelative(specifierB);
39333                             if (ts.pathIsRelative(specifierA) === isBRelative) {
39334                                 // Both relative or both non-relative, sort by number of parts
39335                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
39336                             }
39337                             if (isBRelative) {
39338                                 // A is non-relative, B is relative: prefer A
39339                                 return -1;
39340                             }
39341                             // A is relative, B is non-relative: prefer B
39342                             return 1;
39343                         }
39344                         return 0;
39345                     }
39346                 }
39347             }
39348             function typeParametersToTypeParameterDeclarations(symbol, context) {
39349                 var typeParameterNodes;
39350                 var targetSymbol = getTargetSymbol(symbol);
39351                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
39352                     typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
39353                 }
39354                 return typeParameterNodes;
39355             }
39356             function lookupTypeParameterNodes(chain, index, context) {
39357                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
39358                 var symbol = chain[index];
39359                 var symbolId = "" + getSymbolId(symbol);
39360                 if (context.typeParameterSymbolList && context.typeParameterSymbolList.get(symbolId)) {
39361                     return undefined;
39362                 }
39363                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = ts.createMap())).set(symbolId, true);
39364                 var typeParameterNodes;
39365                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
39366                     var parentSymbol = symbol;
39367                     var nextSymbol_1 = chain[index + 1];
39368                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
39369                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
39370                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
39371                     }
39372                     else {
39373                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
39374                     }
39375                 }
39376                 return typeParameterNodes;
39377             }
39378             /**
39379              * Given A[B][C][D], finds A[B]
39380              */
39381             function getTopmostIndexedAccessType(top) {
39382                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
39383                     return getTopmostIndexedAccessType(top.objectType);
39384                 }
39385                 return top;
39386             }
39387             function getSpecifierForModuleSymbol(symbol, context) {
39388                 var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */);
39389                 if (!file) {
39390                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
39391                     if (equivalentFileSymbol) {
39392                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */);
39393                     }
39394                 }
39395                 if (file && file.moduleName !== undefined) {
39396                     // Use the amd name if it is available
39397                     return file.moduleName;
39398                 }
39399                 if (!file) {
39400                     if (context.tracker.trackReferencedAmbientModule) {
39401                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
39402                         if (ts.length(ambientDecls)) {
39403                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
39404                                 var decl = ambientDecls_1[_i];
39405                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
39406                             }
39407                         }
39408                     }
39409                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39410                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39411                     }
39412                 }
39413                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
39414                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
39415                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39416                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39417                     }
39418                     return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full
39419                 }
39420                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
39421                 var links = getSymbolLinks(symbol);
39422                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
39423                 if (!specifier) {
39424                     var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
39425                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
39426                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
39427                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
39428                     // specifier preference
39429                     var moduleResolverHost = context.tracker.moduleResolverHost;
39430                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
39431                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }));
39432                     links.specifierCache = links.specifierCache || ts.createMap();
39433                     links.specifierCache.set(contextFile.path, specifier);
39434                 }
39435                 return specifier;
39436             }
39437             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
39438                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
39439                 var isTypeOf = meaning === 111551 /* Value */;
39440                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39441                     // module is root, must use `ImportTypeNode`
39442                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
39443                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
39444                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
39445                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
39446                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
39447                         // since declaration files with these kinds of references are liable to fail when published :(
39448                         context.encounteredError = true;
39449                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
39450                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
39451                         }
39452                     }
39453                     var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
39454                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
39455                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
39456                     context.approximateLength += specifier.length + 10; // specifier + import("")
39457                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
39458                         if (nonRootParts) {
39459                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
39460                             lastId.typeArguments = undefined;
39461                         }
39462                         return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
39463                     }
39464                     else {
39465                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
39466                         var qualifier = splitNode.objectType.typeName;
39467                         return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
39468                     }
39469                 }
39470                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
39471                 if (ts.isIndexedAccessTypeNode(entityName)) {
39472                     return entityName; // Indexed accesses can never be `typeof`
39473                 }
39474                 if (isTypeOf) {
39475                     return ts.createTypeQueryNode(entityName);
39476                 }
39477                 else {
39478                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
39479                     var lastTypeArgs = lastId.typeArguments;
39480                     lastId.typeArguments = undefined;
39481                     return ts.createTypeReferenceNode(entityName, lastTypeArgs);
39482                 }
39483                 function createAccessFromSymbolChain(chain, index, stopper) {
39484                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
39485                     var symbol = chain[index];
39486                     var parent = chain[index - 1];
39487                     var symbolName;
39488                     if (index === 0) {
39489                         context.flags |= 16777216 /* InInitialEntityName */;
39490                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39491                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
39492                         context.flags ^= 16777216 /* InInitialEntityName */;
39493                     }
39494                     else {
39495                         if (parent && getExportsOfSymbol(parent)) {
39496                             var exports_1 = getExportsOfSymbol(parent);
39497                             ts.forEachEntry(exports_1, function (ex, name) {
39498                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
39499                                     symbolName = ts.unescapeLeadingUnderscores(name);
39500                                     return true;
39501                                 }
39502                             });
39503                         }
39504                     }
39505                     if (!symbolName) {
39506                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39507                     }
39508                     context.approximateLength += symbolName.length + 1;
39509                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
39510                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
39511                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
39512                         // Should use an indexed access
39513                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39514                         if (ts.isIndexedAccessTypeNode(LHS)) {
39515                             return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39516                         }
39517                         else {
39518                             return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39519                         }
39520                     }
39521                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39522                     identifier.symbol = symbol;
39523                     if (index > stopper) {
39524                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39525                         if (!ts.isEntityName(LHS)) {
39526                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
39527                         }
39528                         return ts.createQualifiedName(LHS, identifier);
39529                     }
39530                     return identifier;
39531                 }
39532             }
39533             function typeParameterShadowsNameInScope(escapedName, context, type) {
39534                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
39535                 if (result) {
39536                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
39537                         return false;
39538                     }
39539                     return true;
39540                 }
39541                 return false;
39542             }
39543             function typeParameterToName(type, context) {
39544                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
39545                     var cached = context.typeParameterNames.get("" + getTypeId(type));
39546                     if (cached) {
39547                         return cached;
39548                     }
39549                 }
39550                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
39551                 if (!(result.kind & 75 /* Identifier */)) {
39552                     return ts.createIdentifier("(Missing type parameter)");
39553                 }
39554                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
39555                     var rawtext = result.escapedText;
39556                     var i = 0;
39557                     var text = rawtext;
39558                     while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) {
39559                         i++;
39560                         text = rawtext + "_" + i;
39561                     }
39562                     if (text !== rawtext) {
39563                         result = ts.createIdentifier(text, result.typeArguments);
39564                     }
39565                     (context.typeParameterNames || (context.typeParameterNames = ts.createMap())).set("" + getTypeId(type), result);
39566                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = ts.createMap())).set(result.escapedText, true);
39567                 }
39568                 return result;
39569             }
39570             function symbolToName(symbol, context, meaning, expectsIdentifier) {
39571                 var chain = lookupSymbolChain(symbol, context, meaning);
39572                 if (expectsIdentifier && chain.length !== 1
39573                     && !context.encounteredError
39574                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
39575                     context.encounteredError = true;
39576                 }
39577                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
39578                 function createEntityNameFromSymbolChain(chain, index) {
39579                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39580                     var symbol = chain[index];
39581                     if (index === 0) {
39582                         context.flags |= 16777216 /* InInitialEntityName */;
39583                     }
39584                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39585                     if (index === 0) {
39586                         context.flags ^= 16777216 /* InInitialEntityName */;
39587                     }
39588                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39589                     identifier.symbol = symbol;
39590                     return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
39591                 }
39592             }
39593             function symbolToExpression(symbol, context, meaning) {
39594                 var chain = lookupSymbolChain(symbol, context, meaning);
39595                 return createExpressionFromSymbolChain(chain, chain.length - 1);
39596                 function createExpressionFromSymbolChain(chain, index) {
39597                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39598                     var symbol = chain[index];
39599                     if (index === 0) {
39600                         context.flags |= 16777216 /* InInitialEntityName */;
39601                     }
39602                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39603                     if (index === 0) {
39604                         context.flags ^= 16777216 /* InInitialEntityName */;
39605                     }
39606                     var firstChar = symbolName.charCodeAt(0);
39607                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39608                         return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context));
39609                     }
39610                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
39611                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
39612                         ts.isIdentifierStart(firstChar, languageVersion);
39613                     if (index === 0 || canUsePropertyAccess) {
39614                         var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39615                         identifier.symbol = symbol;
39616                         return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
39617                     }
39618                     else {
39619                         if (firstChar === 91 /* openBracket */) {
39620                             symbolName = symbolName.substring(1, symbolName.length - 1);
39621                             firstChar = symbolName.charCodeAt(0);
39622                         }
39623                         var expression = void 0;
39624                         if (ts.isSingleOrDoubleQuote(firstChar)) {
39625                             expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
39626                             expression.singleQuote = firstChar === 39 /* singleQuote */;
39627                         }
39628                         else if (("" + +symbolName) === symbolName) {
39629                             expression = ts.createLiteral(+symbolName);
39630                         }
39631                         if (!expression) {
39632                             expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39633                             expression.symbol = symbol;
39634                         }
39635                         return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
39636                     }
39637                 }
39638             }
39639             function isSingleQuotedStringNamed(d) {
39640                 var name = ts.getNameOfDeclaration(d);
39641                 if (name && ts.isStringLiteral(name) && (name.singleQuote ||
39642                     (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) {
39643                     return true;
39644                 }
39645                 return false;
39646             }
39647             function getPropertyNameNodeForSymbol(symbol, context) {
39648                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
39649                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
39650                 if (fromNameType) {
39651                     return fromNameType;
39652                 }
39653                 if (ts.isKnownSymbol(symbol)) {
39654                     return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
39655                 }
39656                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
39657                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote);
39658             }
39659             // See getNameForSymbolFromNameType for a stringy equivalent
39660             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
39661                 var nameType = getSymbolLinks(symbol).nameType;
39662                 if (nameType) {
39663                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
39664                         var name = "" + nameType.value;
39665                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
39666                             return ts.createLiteral(name, !!singleQuote);
39667                         }
39668                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
39669                             return ts.createComputedPropertyName(ts.createLiteral(+name));
39670                         }
39671                         return createPropertyNameNodeForIdentifierOrLiteral(name);
39672                     }
39673                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
39674                         return ts.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
39675                     }
39676                 }
39677             }
39678             function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) {
39679                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote);
39680             }
39681             function cloneNodeBuilderContext(context) {
39682                 var initial = __assign({}, context);
39683                 // Make type parameters created within this context not consume the name outside this context
39684                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
39685                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
39686                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
39687                 // were multiple generic overloads with similar generated type parameter names
39688                 // The effect:
39689                 // When we write out
39690                 // export const x: <T>(x: T) => T
39691                 // export const y: <T>(x: T) => T
39692                 // we write it out like that, rather than as
39693                 // export const x: <T>(x: T) => T
39694                 // export const y: <T_1>(x: T_1) => T_1
39695                 if (initial.typeParameterNames) {
39696                     initial.typeParameterNames = ts.cloneMap(initial.typeParameterNames);
39697                 }
39698                 if (initial.typeParameterNamesByText) {
39699                     initial.typeParameterNamesByText = ts.cloneMap(initial.typeParameterNamesByText);
39700                 }
39701                 if (initial.typeParameterSymbolList) {
39702                     initial.typeParameterSymbolList = ts.cloneMap(initial.typeParameterSymbolList);
39703                 }
39704                 return initial;
39705             }
39706             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
39707                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
39708             }
39709             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
39710                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
39711             }
39712             /**
39713              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
39714              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
39715              */
39716             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
39717                 if (type !== errorType && enclosingDeclaration) {
39718                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
39719                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
39720                         // try to reuse the existing annotation
39721                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
39722                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
39723                             var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
39724                             if (result_4) {
39725                                 return result_4;
39726                             }
39727                         }
39728                     }
39729                 }
39730                 var oldFlags = context.flags;
39731                 if (type.flags & 8192 /* UniqueESSymbol */ &&
39732                     type.symbol === symbol) {
39733                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
39734                 }
39735                 var result = typeToTypeNodeHelper(type, context);
39736                 context.flags = oldFlags;
39737                 return result;
39738             }
39739             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
39740                 if (type !== errorType && context.enclosingDeclaration) {
39741                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
39742                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
39743                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
39744                         if (result) {
39745                             return result;
39746                         }
39747                     }
39748                 }
39749                 return typeToTypeNodeHelper(type, context);
39750             }
39751             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
39752                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
39753                     cancellationToken.throwIfCancellationRequested();
39754                 }
39755                 var hadError = false;
39756                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
39757                 if (hadError) {
39758                     return undefined;
39759                 }
39760                 return transformed === existing ? ts.getMutableClone(existing) : transformed;
39761                 function visitExistingNodeTreeSymbols(node) {
39762                     var _a, _b;
39763                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
39764                     if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) {
39765                         return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39766                     }
39767                     if (ts.isJSDocUnknownType(node)) {
39768                         return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
39769                     }
39770                     if (ts.isJSDocNullableType(node)) {
39771                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]);
39772                     }
39773                     if (ts.isJSDocOptionalType(node)) {
39774                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
39775                     }
39776                     if (ts.isJSDocNonNullableType(node)) {
39777                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
39778                     }
39779                     if (ts.isJSDocVariadicType(node)) {
39780                         return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39781                     }
39782                     if (ts.isJSDocTypeLiteral(node)) {
39783                         return ts.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
39784                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
39785                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
39786                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
39787                             return ts.createPropertySignature(
39788                             /*modifiers*/ undefined, name, t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.createToken(57 /* QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.createKeywordTypeNode(125 /* AnyKeyword */), 
39789                             /*initializer*/ undefined);
39790                         }));
39791                     }
39792                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
39793                         return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node);
39794                     }
39795                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
39796                         return ts.createTypeLiteralNode([ts.createIndexSignature(
39797                             /*decorators*/ undefined, 
39798                             /*modifiers*/ undefined, [ts.createParameter(
39799                                 /*decorators*/ undefined, 
39800                                 /*modifiers*/ undefined, 
39801                                 /*dotdotdotToken*/ undefined, "x", 
39802                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
39803                     }
39804                     if (ts.isJSDocFunctionType(node)) {
39805                         if (ts.isJSDocConstructSignature(node)) {
39806                             var newTypeNode_1;
39807                             return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter(
39808                             /*decorators*/ undefined, 
39809                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39810                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols));
39811                         }
39812                         else {
39813                             return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(
39814                             /*decorators*/ undefined, 
39815                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39816                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39817                         }
39818                     }
39819                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
39820                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
39821                     }
39822                     if (ts.isLiteralImportTypeNode(node)) {
39823                         return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
39824                     }
39825                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
39826                         var leftmost = ts.getFirstIdentifier(node);
39827                         if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) {
39828                             hadError = true;
39829                             return node;
39830                         }
39831                         var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
39832                         if (sym) {
39833                             if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
39834                                 hadError = true;
39835                             }
39836                             else {
39837                                 (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863 /* All */);
39838                                 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
39839                             }
39840                             if (ts.isIdentifier(node)) {
39841                                 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node);
39842                                 name.symbol = sym; // for quickinfo, which uses identifier symbol information
39843                                 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
39844                             }
39845                         }
39846                     }
39847                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
39848                     function getEffectiveDotDotDotForParameter(p) {
39849                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined);
39850                     }
39851                     function rewriteModuleSpecifier(parent, lit) {
39852                         if (bundled) {
39853                             if (context.tracker && context.tracker.moduleResolverHost) {
39854                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
39855                                 if (targetFile) {
39856                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
39857                                     var resolverHost = {
39858                                         getCanonicalFileName: getCanonicalFileName,
39859                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
39860                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
39861                                     };
39862                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
39863                                     return ts.createLiteral(newName);
39864                                 }
39865                             }
39866                         }
39867                         else {
39868                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
39869                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
39870                                 if (moduleSym) {
39871                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
39872                                 }
39873                             }
39874                         }
39875                         return lit;
39876                     }
39877                 }
39878             }
39879             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
39880                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true);
39881                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false);
39882                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
39883                 // declaration mapping
39884                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
39885                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
39886                 // we're trying to emit from later on)
39887                 var enclosingDeclaration = context.enclosingDeclaration;
39888                 var results = [];
39889                 var visitedSymbols = ts.createMap();
39890                 var deferredPrivates;
39891                 var oldcontext = context;
39892                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
39893                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
39894                             if (accessibleResult.accessibility === 0 /* Accessible */) {
39895                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
39896                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
39897                                 if (!(sym.flags & 4 /* Property */)) {
39898                                     includePrivateSymbol(chain[0]);
39899                                 }
39900                             }
39901                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
39902                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
39903                             }
39904                         } }) });
39905                 if (oldcontext.usedSymbolNames) {
39906                     oldcontext.usedSymbolNames.forEach(function (_, name) {
39907                         context.usedSymbolNames.set(name, true);
39908                     });
39909                 }
39910                 ts.forEachEntry(symbolTable, function (symbol, name) {
39911                     var baseName = ts.unescapeLeadingUnderscores(name);
39912                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
39913                 });
39914                 var addingDeclare = !bundled;
39915                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
39916                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
39917                     symbolTable = ts.createSymbolTable();
39918                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
39919                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
39920                 }
39921                 visitSymbolTable(symbolTable);
39922                 return mergeRedundantStatements(results);
39923                 function isIdentifierAndNotUndefined(node) {
39924                     return !!node && node.kind === 75 /* Identifier */;
39925                 }
39926                 function getNamesOfDeclaration(statement) {
39927                     if (ts.isVariableStatement(statement)) {
39928                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
39929                     }
39930                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
39931                 }
39932                 function flattenExportAssignedNamespace(statements) {
39933                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
39934                     var ns = ts.find(statements, ts.isModuleDeclaration);
39935                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
39936                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
39937                         ns.body && ts.isModuleBlock(ns.body)) {
39938                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
39939                         //  the top-level exports and exporting them in the targeted ns, as can occur when a js file has both typedefs and `module.export` assignments
39940                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getModifierFlags(s) & 1 /* Export */); });
39941                         if (ts.length(excessExports)) {
39942                             ns.body.statements = ts.createNodeArray(__spreadArrays(ns.body.statements, [ts.createExportDeclaration(
39943                                 /*decorators*/ undefined, 
39944                                 /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.createExportSpecifier(/*alias*/ undefined, id); })), 
39945                                 /*moduleSpecifier*/ undefined)]));
39946                         }
39947                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
39948                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, ns.name); })) {
39949                             results = [];
39950                             ts.forEach(ns.body.statements, function (s) {
39951                                 addResult(s, 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
39952                             });
39953                             statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
39954                         }
39955                     }
39956                     return statements;
39957                 }
39958                 function mergeExportDeclarations(statements) {
39959                     // Pass 2: Combine all `export {}` declarations
39960                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39961                     if (ts.length(exports) > 1) {
39962                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
39963                         statements = __spreadArrays(nonExports, [ts.createExportDeclaration(
39964                             /*decorators*/ undefined, 
39965                             /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
39966                             /*moduleSpecifier*/ undefined)]);
39967                     }
39968                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
39969                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39970                     if (ts.length(reexports) > 1) {
39971                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
39972                         if (groups.length !== reexports.length) {
39973                             var _loop_8 = function (group_1) {
39974                                 if (group_1.length > 1) {
39975                                     // remove group members from statements and then merge group members and add back to statements
39976                                     statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
39977                                         ts.createExportDeclaration(
39978                                         /*decorators*/ undefined, 
39979                                         /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
39980                                     ]);
39981                                 }
39982                             };
39983                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
39984                                 var group_1 = groups_1[_i];
39985                                 _loop_8(group_1);
39986                             }
39987                         }
39988                     }
39989                     return statements;
39990                 }
39991                 function inlineExportModifiers(statements) {
39992                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
39993                     var exportDecl = ts.find(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause; });
39994                     if (exportDecl && exportDecl.exportClause && ts.isNamedExports(exportDecl.exportClause)) {
39995                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
39996                             if (!e.propertyName) {
39997                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
39998                                 var associated = ts.filter(statements, function (s) { return ts.nodeHasName(s, e.name); });
39999                                 if (ts.length(associated) && ts.every(associated, canHaveExportModifier)) {
40000                                     ts.forEach(associated, addExportModifier);
40001                                     return undefined;
40002                                 }
40003                             }
40004                             return e;
40005                         });
40006                         if (!ts.length(replacements)) {
40007                             // all clauses removed, filter the export declaration
40008                             statements = ts.filter(statements, function (s) { return s !== exportDecl; });
40009                         }
40010                         else {
40011                             // some items filtered, others not - update the export declaration
40012                             // (mutating because why not, we're building a whole new tree here anyway)
40013                             exportDecl.exportClause.elements = ts.createNodeArray(replacements);
40014                         }
40015                     }
40016                     return statements;
40017                 }
40018                 function mergeRedundantStatements(statements) {
40019                     statements = flattenExportAssignedNamespace(statements);
40020                     statements = mergeExportDeclarations(statements);
40021                     statements = inlineExportModifiers(statements);
40022                     // Not a cleanup, but as a final step: If there is a mix of `export` and non-`export` declarations, but no `export =` or `export {}` add a `export {};` so
40023                     // declaration privacy is respected.
40024                     if (enclosingDeclaration &&
40025                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
40026                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
40027                         statements.push(ts.createEmptyExports());
40028                     }
40029                     return statements;
40030                 }
40031                 function canHaveExportModifier(node) {
40032                     return ts.isEnumDeclaration(node) ||
40033                         ts.isVariableStatement(node) ||
40034                         ts.isFunctionDeclaration(node) ||
40035                         ts.isClassDeclaration(node) ||
40036                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
40037                         ts.isInterfaceDeclaration(node) ||
40038                         isTypeDeclaration(node);
40039                 }
40040                 function addExportModifier(statement) {
40041                     var flags = (ts.getModifierFlags(statement) | 1 /* Export */) & ~2 /* Ambient */;
40042                     statement.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flags));
40043                     statement.modifierFlagsCache = 0;
40044                 }
40045                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
40046                     var oldDeferredPrivates = deferredPrivates;
40047                     if (!suppressNewPrivateContext) {
40048                         deferredPrivates = ts.createMap();
40049                     }
40050                     symbolTable.forEach(function (symbol) {
40051                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
40052                     });
40053                     if (!suppressNewPrivateContext) {
40054                         // deferredPrivates will be filled up by visiting the symbol table
40055                         // And will continue to iterate as elements are added while visited `deferredPrivates`
40056                         // (As that's how a map iterator is defined to work)
40057                         deferredPrivates.forEach(function (symbol) {
40058                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
40059                         });
40060                     }
40061                     deferredPrivates = oldDeferredPrivates;
40062                 }
40063                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
40064                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
40065                     // still skip reserializing it if we encounter the merged product later on
40066                     var visitedSym = getMergedSymbol(symbol);
40067                     if (visitedSymbols.has("" + getSymbolId(visitedSym))) {
40068                         return; // Already printed
40069                     }
40070                     visitedSymbols.set("" + getSymbolId(visitedSym), true);
40071                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
40072                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
40073                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
40074                         var oldContext = context;
40075                         context = cloneNodeBuilderContext(context);
40076                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
40077                         context = oldContext;
40078                         return result;
40079                     }
40080                 }
40081                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
40082                 // or a merge of some number of those.
40083                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
40084                 // each symbol in only one of the representations
40085                 // Also, synthesizing a default export of some kind
40086                 // If it's an alias: emit `export default ref`
40087                 // If it's a property: emit `export default _default` with a `_default` prop
40088                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
40089                 // These forms can merge, eg (`export default 12; export default interface A {}`)
40090                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
40091                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
40092                     var isDefault = symbol.escapedName === "default" /* Default */;
40093                     if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
40094                         // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :(
40095                         context.encounteredError = true;
40096                         // TODO: Issue error via symbol tracker?
40097                         return; // If we need to emit a private with a keyword name, we're done for, since something else will try to refer to it by that name
40098                     }
40099                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
40100                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
40101                     if (needsPostExportDefault) {
40102                         isPrivate = true;
40103                     }
40104                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
40105                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
40106                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
40107                         symbol.escapedName !== "export=" /* ExportEquals */;
40108                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
40109                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
40110                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40111                     }
40112                     if (symbol.flags & 524288 /* TypeAlias */) {
40113                         serializeTypeAlias(symbol, symbolName, modifierFlags);
40114                     }
40115                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
40116                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
40117                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
40118                         && symbol.escapedName !== "export=" /* ExportEquals */
40119                         && !(symbol.flags & 4194304 /* Prototype */)
40120                         && !(symbol.flags & 32 /* Class */)
40121                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
40122                         serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags);
40123                     }
40124                     if (symbol.flags & 384 /* Enum */) {
40125                         serializeEnum(symbol, symbolName, modifierFlags);
40126                     }
40127                     if (symbol.flags & 32 /* Class */) {
40128                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
40129                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
40130                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
40131                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
40132                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40133                         }
40134                         else {
40135                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40136                         }
40137                     }
40138                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
40139                         serializeModule(symbol, symbolName, modifierFlags);
40140                     }
40141                     if (symbol.flags & 64 /* Interface */) {
40142                         serializeInterface(symbol, symbolName, modifierFlags);
40143                     }
40144                     if (symbol.flags & 2097152 /* Alias */) {
40145                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40146                     }
40147                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
40148                         serializeMaybeAliasAssignment(symbol);
40149                     }
40150                     if (symbol.flags & 8388608 /* ExportStar */) {
40151                         // synthesize export * from "moduleReference"
40152                         // Straightforward - only one thing to do - make an export declaration
40153                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
40154                             var node = _a[_i];
40155                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
40156                             if (!resolvedModule)
40157                                 continue;
40158                             addResult(ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*exportClause*/ undefined, ts.createLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
40159                         }
40160                     }
40161                     if (needsPostExportDefault) {
40162                         addResult(ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
40163                     }
40164                 }
40165                 function includePrivateSymbol(symbol) {
40166                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
40167                         return;
40168                     ts.Debug.assertIsDefined(deferredPrivates);
40169                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
40170                     deferredPrivates.set("" + getSymbolId(symbol), symbol);
40171                 }
40172                 function isExportingScope(enclosingDeclaration) {
40173                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
40174                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
40175                 }
40176                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
40177                 // Note: This _mutates_ `node` without using `updateNode` - the assumption being that all nodes should be manufactured fresh by the node builder
40178                 function addResult(node, additionalModifierFlags) {
40179                     var newModifierFlags = 0 /* None */;
40180                     if (additionalModifierFlags & 1 /* Export */ &&
40181                         enclosingDeclaration &&
40182                         isExportingScope(enclosingDeclaration) &&
40183                         canHaveExportModifier(node)) {
40184                         // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
40185                         newModifierFlags |= 1 /* Export */;
40186                     }
40187                     if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
40188                         (!enclosingDeclaration || !(enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
40189                         (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
40190                         // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
40191                         newModifierFlags |= 2 /* Ambient */;
40192                     }
40193                     if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
40194                         newModifierFlags |= 512 /* Default */;
40195                     }
40196                     if (newModifierFlags) {
40197                         node.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(newModifierFlags | ts.getModifierFlags(node)));
40198                         node.modifierFlagsCache = 0; // Reset computed flags cache
40199                     }
40200                     results.push(node);
40201                 }
40202                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
40203                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
40204                     var typeParams = getSymbolLinks(symbol).typeParameters;
40205                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
40206                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
40207                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
40208                     var oldFlags = context.flags;
40209                     context.flags |= 8388608 /* InTypeAlias */;
40210                     addResult(ts.setSyntheticLeadingComments(ts.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeToTypeNodeHelper(aliasType, context)), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags);
40211                     context.flags = oldFlags;
40212                 }
40213                 function serializeInterface(symbol, symbolName, modifierFlags) {
40214                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
40215                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40216                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40217                     var baseTypes = getBaseTypes(interfaceType);
40218                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
40219                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
40220                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 165 /* CallSignature */);
40221                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 166 /* ConstructSignature */);
40222                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
40223                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b); }))];
40224                     addResult(ts.createInterfaceDeclaration(
40225                     /*decorators*/ undefined, 
40226                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
40227                 }
40228                 function getNamespaceMembersForSerialization(symbol) {
40229                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
40230                 }
40231                 function isTypeOnlyNamespace(symbol) {
40232                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
40233                 }
40234                 function serializeModule(symbol, symbolName, modifierFlags) {
40235                     var members = getNamespaceMembersForSerialization(symbol);
40236                     // Split NS members up by declaration - members whose parent symbol is the ns symbol vs those whose is not (but were added in later via merging)
40237                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
40238                     var realMembers = locationMap.get("real") || ts.emptyArray;
40239                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
40240                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
40241                     // than whatever scope we traverse to them in. That's a bit of a complex rewrite, since we're not _actually_ tracking privates at all in advance,
40242                     // so we don't even have placeholders to fill in.
40243                     if (ts.length(realMembers)) {
40244                         var localName = getInternalSymbolName(symbol, symbolName);
40245                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
40246                     }
40247                     if (ts.length(mergedMembers)) {
40248                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
40249                         var localName = getInternalSymbolName(symbol, symbolName);
40250                         var nsBody = ts.createModuleBlock([ts.createExportDeclaration(
40251                             /*decorators*/ undefined, 
40252                             /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
40253                                 var _a, _b;
40254                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
40255                                 var localName = getInternalSymbolName(s, name);
40256                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
40257                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
40258                                     (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s);
40259                                     return undefined;
40260                                 }
40261                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40262                                 includePrivateSymbol(target || s);
40263                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
40264                                 return ts.createExportSpecifier(name === targetName ? undefined : targetName, name);
40265                             })))]);
40266                         addResult(ts.createModuleDeclaration(
40267                         /*decorators*/ undefined, 
40268                         /*modifiers*/ undefined, ts.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
40269                     }
40270                 }
40271                 function serializeEnum(symbol, symbolName, modifierFlags) {
40272                     addResult(ts.createEnumDeclaration(
40273                     /*decorators*/ undefined, ts.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* EnumMember */); }), function (p) {
40274                         // TODO: Handle computed names
40275                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
40276                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
40277                         // _on the declaration_, not on the declaration's symbol...
40278                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) && getConstantValue(p.declarations[0]);
40279                         return ts.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : ts.createLiteral(initializedValue));
40280                     })), modifierFlags);
40281                 }
40282                 function serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags) {
40283                     if (propertyAsAlias) {
40284                         serializeMaybeAliasAssignment(symbol);
40285                     }
40286                     else {
40287                         var type = getTypeOfSymbol(symbol);
40288                         var localName = getInternalSymbolName(symbol, symbolName);
40289                         if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
40290                             // If the type looks like a function declaration + ns could represent it, and it's type is sourced locally, rewrite it into a function declaration + ns
40291                             serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
40292                         }
40293                         else {
40294                             // A Class + Property merge is made for a `module.exports.Member = class {}`, and it doesn't serialize well as either a class _or_ a property symbol - in fact, _it behaves like an alias!_
40295                             // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
40296                             var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
40297                                 : isConstVariable(symbol) ? 2 /* Const */
40298                                     : 1 /* Let */;
40299                             var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
40300                             var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
40301                             if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
40302                                 textRange = textRange.parent.parent;
40303                             }
40304                             var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40305                                 ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40306                             ], flags)), textRange);
40307                             addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
40308                             if (name !== localName && !isPrivate) {
40309                                 // We rename the variable declaration we generate for Property symbols since they may have a name which
40310                                 // conflicts with a local declaration. For example, given input:
40311                                 // ```
40312                                 // function g() {}
40313                                 // module.exports.g = g
40314                                 // ```
40315                                 // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
40316                                 // Naively, we would emit
40317                                 // ```
40318                                 // function g() {}
40319                                 // export const g: typeof g;
40320                                 // ```
40321                                 // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
40322                                 // the export declaration shadows it.
40323                                 // To work around that, we instead write
40324                                 // ```
40325                                 // function g() {}
40326                                 // const g_1: typeof g;
40327                                 // export { g_1 as g };
40328                                 // ```
40329                                 // To create an export named `g` that does _not_ shadow the local `g`
40330                                 addResult(ts.createExportDeclaration(
40331                                 /*decorators*/ undefined, 
40332                                 /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(name, localName)])), 0 /* None */);
40333                             }
40334                         }
40335                     }
40336                 }
40337                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
40338                     var signatures = getSignaturesOfType(type, 0 /* Call */);
40339                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
40340                         var sig = signatures_2[_i];
40341                         // Each overload becomes a separate function declaration, in order
40342                         var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled);
40343                         decl.name = ts.createIdentifier(localName);
40344                         // for expressions assigned to `var`s, use the `var` as the text range
40345                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
40346                     }
40347                     // Module symbol emit will take care of module-y members, provided it has exports
40348                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
40349                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
40350                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
40351                     }
40352                 }
40353                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
40354                     if (ts.length(props)) {
40355                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
40356                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
40357                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
40358                             }) ? "local" : "remote";
40359                         });
40360                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
40361                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
40362                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
40363                         // Example:
40364                         // import Foo_1 = require("./exporter");
40365                         // export namespace ns {
40366                         //     import Foo = Foo_1.Foo;
40367                         //     export { Foo };
40368                         //     export const c: number;
40369                         // }
40370                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
40371                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
40372                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
40373                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
40374                         // emit akin to the above would be needed.
40375                         // Add a namespace
40376                         var fakespace = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(localName), ts.createModuleBlock([]), 16 /* Namespace */);
40377                         fakespace.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
40378                         fakespace.parent = enclosingDeclaration;
40379                         fakespace.locals = ts.createSymbolTable(props);
40380                         fakespace.symbol = props[0].parent;
40381                         var oldResults = results;
40382                         results = [];
40383                         var oldAddingDeclare = addingDeclare;
40384                         addingDeclare = false;
40385                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
40386                         var oldContext = context;
40387                         context = subcontext;
40388                         // TODO: implement handling for the localVsRemoteMap.get("remote") - should be difficult to trigger (see comment above), as only interesting cross-file js merges should make this possible
40389                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
40390                         context = oldContext;
40391                         addingDeclare = oldAddingDeclare;
40392                         var declarations = results;
40393                         results = oldResults;
40394                         fakespace.flags ^= 8 /* Synthesized */; // reset synthesized
40395                         fakespace.parent = undefined;
40396                         fakespace.locals = undefined;
40397                         fakespace.symbol = undefined;
40398                         fakespace.body = ts.createModuleBlock(declarations);
40399                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
40400                     }
40401                 }
40402                 function isNamespaceMember(p) {
40403                     return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent));
40404                 }
40405                 function serializeAsClass(symbol, localName, modifierFlags) {
40406                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40407                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40408                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
40409                     var baseTypes = getBaseTypes(classType);
40410                     var implementsTypes = getImplementsTypes(classType);
40411                     var staticType = getTypeOfSymbol(symbol);
40412                     var staticBaseType = getBaseConstructorTypeOfClass(staticType);
40413                     var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113 /* ImplementsKeyword */, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]);
40414                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
40415                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
40416                         // `valueDeclaration` could be undefined if inherited from
40417                         // a union/intersection base type, but inherited properties
40418                         // don't matter here.
40419                         var valueDecl = s.valueDeclaration;
40420                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
40421                     });
40422                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
40423                         // `valueDeclaration` could be undefined if inherited from
40424                         // a union/intersection base type, but inherited properties
40425                         // don't matter here.
40426                         var valueDecl = s.valueDeclaration;
40427                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
40428                     });
40429                     // Boil down all private properties into a single one.
40430                     var privateProperties = hasPrivateIdentifier ?
40431                         [ts.createProperty(
40432                             /*decorators*/ undefined, 
40433                             /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
40434                             /*questionOrExclamationToken*/ undefined, 
40435                             /*type*/ undefined, 
40436                             /*initializer*/ undefined)] :
40437                         ts.emptyArray;
40438                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
40439                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
40440                     var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); });
40441                     var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */);
40442                     for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) {
40443                         var c = constructors_1[_i];
40444                         // A constructor's return type and type parameters are supposed to be controlled by the enclosing class declaration
40445                         // `signatureToSignatureDeclarationHelper` appends them regardless, so for now we delete them here
40446                         c.type = undefined;
40447                         c.typeParameters = undefined;
40448                     }
40449                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
40450                     addResult(ts.setTextRange(ts.createClassDeclaration(
40451                     /*decorators*/ undefined, 
40452                     /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, staticMembers, constructors, publicProperties, privateProperties)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags);
40453                 }
40454                 function serializeAsAlias(symbol, localName, modifierFlags) {
40455                     // synthesize an alias, eg `export { symbolName as Name }`
40456                     // need to mark the alias `symbol` points at
40457                     // as something we need to serialize as a private declaration as well
40458                     var node = getDeclarationOfAliasSymbol(symbol);
40459                     if (!node)
40460                         return ts.Debug.fail();
40461                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
40462                     if (!target) {
40463                         return;
40464                     }
40465                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
40466                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
40467                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
40468                         verbatimTargetName = "default" /* Default */;
40469                     }
40470                     var targetName = getInternalSymbolName(target, verbatimTargetName);
40471                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
40472                     switch (node.kind) {
40473                         case 253 /* ImportEqualsDeclaration */:
40474                             // Could be a local `import localName = ns.member` or
40475                             // an external `import localName = require("whatever")`
40476                             var isLocalImport = !(target.flags & 512 /* ValueModule */);
40477                             addResult(ts.createImportEqualsDeclaration(
40478                             /*decorators*/ undefined, 
40479                             /*modifiers*/ undefined, ts.createIdentifier(localName), isLocalImport
40480                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
40481                                 : ts.createExternalModuleReference(ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)))), isLocalImport ? modifierFlags : 0 /* None */);
40482                             break;
40483                         case 252 /* NamespaceExportDeclaration */:
40484                             // export as namespace foo
40485                             // TODO: Not part of a file's local or export symbol tables
40486                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
40487                             addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
40488                             break;
40489                         case 255 /* ImportClause */:
40490                             addResult(ts.createImportDeclaration(
40491                             /*decorators*/ undefined, 
40492                             /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), 
40493                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
40494                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
40495                             // In such cases, the `target` refers to the module itself already
40496                             ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40497                             break;
40498                         case 256 /* NamespaceImport */:
40499                             addResult(ts.createImportDeclaration(
40500                             /*decorators*/ undefined, 
40501                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40502                             break;
40503                         case 262 /* NamespaceExport */:
40504                             addResult(ts.createExportDeclaration(
40505                             /*decorators*/ undefined, 
40506                             /*modifiers*/ undefined, ts.createNamespaceExport(ts.createIdentifier(localName)), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40507                             break;
40508                         case 258 /* ImportSpecifier */:
40509                             addResult(ts.createImportDeclaration(
40510                             /*decorators*/ undefined, 
40511                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([
40512                                 ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName))
40513                             ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40514                             break;
40515                         case 263 /* ExportSpecifier */:
40516                             // does not use localName because the symbol name in this case refers to the name in the exports table,
40517                             // which we must exactly preserve
40518                             var specifier = node.parent.parent.moduleSpecifier;
40519                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
40520                             // another file
40521                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.createLiteral(specifier.text) : undefined);
40522                             break;
40523                         case 259 /* ExportAssignment */:
40524                             serializeMaybeAliasAssignment(symbol);
40525                             break;
40526                         case 209 /* BinaryExpression */:
40527                         case 194 /* PropertyAccessExpression */:
40528                             // Could be best encoded as though an export specifier or as though an export assignment
40529                             // If name is default or export=, do an export assignment
40530                             // Otherwise do an export specifier
40531                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
40532                                 serializeMaybeAliasAssignment(symbol);
40533                             }
40534                             else {
40535                                 serializeExportSpecifier(localName, targetName);
40536                             }
40537                             break;
40538                         default:
40539                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
40540                     }
40541                 }
40542                 function serializeExportSpecifier(localName, targetName, specifier) {
40543                     addResult(ts.createExportDeclaration(
40544                     /*decorators*/ undefined, 
40545                     /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
40546                 }
40547                 function serializeMaybeAliasAssignment(symbol) {
40548                     if (symbol.flags & 4194304 /* Prototype */) {
40549                         return;
40550                     }
40551                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
40552                     var isExportEquals = name === "export=" /* ExportEquals */;
40553                     var isDefault = name === "default" /* Default */;
40554                     var isExportAssignment = isExportEquals || isDefault;
40555                     // synthesize export = ref
40556                     // ref should refer to either be a locally scoped symbol which we need to emit, or
40557                     // a reference to another namespace/module which we may need to emit an `import` statement for
40558                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
40559                     // serialize what the alias points to, preserve the declaration's initializer
40560                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40561                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
40562                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
40563                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
40564                         // eg, `namespace A { export class B {} }; exports = A.B;`
40565                         // Technically, this is all that's required in the case where the assignment is an entity name expression
40566                         var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl);
40567                         var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
40568                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
40569                         if (referenced || target) {
40570                             includePrivateSymbol(referenced || target);
40571                         }
40572                         // We disable the context's symbol tracker for the duration of this name serialization
40573                         // as, by virtue of being here, the name is required to print something, and we don't want to
40574                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
40575                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
40576                         // into the containing scope anyway, so we want to skip the visibility checks.
40577                         var oldTrack = context.tracker.trackSymbol;
40578                         context.tracker.trackSymbol = ts.noop;
40579                         if (isExportAssignment) {
40580                             results.push(ts.createExportAssignment(
40581                             /*decorators*/ undefined, 
40582                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
40583                         }
40584                         else {
40585                             if (first_1 === expr) {
40586                                 // serialize as `export {target as name}`
40587                                 serializeExportSpecifier(name, ts.idText(first_1));
40588                             }
40589                             else if (ts.isClassExpression(expr)) {
40590                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
40591                             }
40592                             else {
40593                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
40594                                 var varName = getUnusedName(name, symbol);
40595                                 addResult(ts.createImportEqualsDeclaration(
40596                                 /*decorators*/ undefined, 
40597                                 /*modifiers*/ undefined, ts.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
40598                                 serializeExportSpecifier(name, varName);
40599                             }
40600                         }
40601                         context.tracker.trackSymbol = oldTrack;
40602                     }
40603                     else {
40604                         // serialize as an anonymous property declaration
40605                         var varName = getUnusedName(name, symbol);
40606                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
40607                         // (Unwidened types can only exist in expression contexts and should never be serialized)
40608                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
40609                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
40610                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
40611                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */);
40612                         }
40613                         else {
40614                             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40615                                 ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40616                             ], 2 /* Const */));
40617                             addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */);
40618                         }
40619                         if (isExportAssignment) {
40620                             results.push(ts.createExportAssignment(
40621                             /*decorators*/ undefined, 
40622                             /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(varName)));
40623                         }
40624                         else if (name !== varName) {
40625                             serializeExportSpecifier(name, varName);
40626                         }
40627                     }
40628                 }
40629                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
40630                     // Only object types which are not constructable, or indexable, whose members all come from the
40631                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
40632                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
40633                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
40634                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
40635                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
40636                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
40637                         !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
40638                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
40639                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
40640                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
40641                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
40642                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
40643                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion) && !ts.isStringAKeyword(ts.symbolName(p)); });
40644                 }
40645                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
40646                     return function serializePropertySymbol(p, isStatic, baseType) {
40647                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
40648                         var isPrivate = !!(modifierFlags & 8 /* Private */);
40649                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
40650                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
40651                             // need to be merged namespace members
40652                             return [];
40653                         }
40654                         if (p.flags & 4194304 /* Prototype */ ||
40655                             (baseType && getPropertyOfType(baseType, p.escapedName)
40656                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
40657                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
40658                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
40659                             return [];
40660                         }
40661                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
40662                         var name = getPropertyNameNodeForSymbol(p, context);
40663                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
40664                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
40665                             var result = [];
40666                             if (p.flags & 65536 /* SetAccessor */) {
40667                                 result.push(ts.setTextRange(ts.createSetAccessor(
40668                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(
40669                                     /*decorators*/ undefined, 
40670                                     /*modifiers*/ undefined, 
40671                                     /*dotDotDotToken*/ undefined, "arg", 
40672                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
40673                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
40674                             }
40675                             if (p.flags & 32768 /* GetAccessor */) {
40676                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
40677                                 result.push(ts.setTextRange(ts.createGetAccessor(
40678                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
40679                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
40680                             }
40681                             return result;
40682                         }
40683                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
40684                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
40685                         else if (p.flags & (4 /* Property */ | 3 /* Variable */)) {
40686                             return ts.setTextRange(createProperty(
40687                             /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
40688                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
40689                             // interface members can't have initializers, however class members _can_
40690                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
40691                         }
40692                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
40693                             var type = getTypeOfSymbol(p);
40694                             var signatures = getSignaturesOfType(type, 0 /* Call */);
40695                             if (flag & 8 /* Private */) {
40696                                 return ts.setTextRange(createProperty(
40697                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, 
40698                                 /*type*/ undefined, 
40699                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
40700                             }
40701                             var results_1 = [];
40702                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
40703                                 var sig = signatures_3[_i];
40704                                 // Each overload becomes a separate method declaration, in order
40705                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context);
40706                                 decl.name = name; // TODO: Clone
40707                                 if (flag) {
40708                                     decl.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flag));
40709                                 }
40710                                 if (p.flags & 16777216 /* Optional */) {
40711                                     decl.questionToken = ts.createToken(57 /* QuestionToken */);
40712                                 }
40713                                 results_1.push(ts.setTextRange(decl, sig.declaration));
40714                             }
40715                             return results_1;
40716                         }
40717                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
40718                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
40719                     };
40720                 }
40721                 function serializePropertySymbolForInterface(p, baseType) {
40722                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
40723                 }
40724                 function serializeSignatures(kind, input, baseType, outputKind) {
40725                     var signatures = getSignaturesOfType(input, kind);
40726                     if (kind === 1 /* Construct */) {
40727                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40728                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
40729                         }
40730                         if (baseType) {
40731                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
40732                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
40733                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40734                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
40735                             }
40736                             if (baseSigs.length === signatures.length) {
40737                                 var failed = false;
40738                                 for (var i = 0; i < baseSigs.length; i++) {
40739                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
40740                                         failed = true;
40741                                         break;
40742                                     }
40743                                 }
40744                                 if (!failed) {
40745                                     return []; // Every signature was identical - elide constructor list as it is inherited
40746                                 }
40747                             }
40748                         }
40749                         var privateProtected = 0;
40750                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
40751                             var s = signatures_4[_i];
40752                             if (s.declaration) {
40753                                 privateProtected |= ts.getSelectedModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
40754                             }
40755                         }
40756                         if (privateProtected) {
40757                             return [ts.setTextRange(ts.createConstructor(
40758                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(privateProtected), 
40759                                 /*parameters*/ [], 
40760                                 /*body*/ undefined), signatures[0].declaration)];
40761                         }
40762                     }
40763                     var results = [];
40764                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
40765                         var sig = signatures_5[_a];
40766                         // Each overload becomes a separate constructor declaration, in order
40767                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
40768                         results.push(ts.setTextRange(decl, sig.declaration));
40769                     }
40770                     return results;
40771                 }
40772                 function serializeIndexSignatures(input, baseType) {
40773                     var results = [];
40774                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
40775                         var type = _a[_i];
40776                         var info = getIndexInfoOfType(input, type);
40777                         if (info) {
40778                             if (baseType) {
40779                                 var baseInfo = getIndexInfoOfType(baseType, type);
40780                                 if (baseInfo) {
40781                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
40782                                         continue; // elide identical index signatures
40783                                     }
40784                                 }
40785                             }
40786                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context));
40787                         }
40788                     }
40789                     return results;
40790                 }
40791                 function serializeBaseType(t, staticType, rootName) {
40792                     var ref = trySerializeAsTypeReference(t);
40793                     if (ref) {
40794                         return ref;
40795                     }
40796                     var tempName = getUnusedName(rootName + "_base");
40797                     var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40798                         ts.createVariableDeclaration(tempName, typeToTypeNodeHelper(staticType, context))
40799                     ], 2 /* Const */));
40800                     addResult(statement, 0 /* None */);
40801                     return ts.createExpressionWithTypeArguments(/*typeArgs*/ undefined, ts.createIdentifier(tempName));
40802                 }
40803                 function trySerializeAsTypeReference(t) {
40804                     var typeArgs;
40805                     var reference;
40806                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
40807                     // which we can't write out in a syntactically valid way as an expression
40808                     if (t.target && getAccessibleSymbolChain(t.target.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40809                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
40810                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
40811                     }
40812                     else if (t.symbol && getAccessibleSymbolChain(t.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40813                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
40814                     }
40815                     if (reference) {
40816                         return ts.createExpressionWithTypeArguments(typeArgs, reference);
40817                     }
40818                 }
40819                 function getUnusedName(input, symbol) {
40820                     if (symbol) {
40821                         if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40822                             return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40823                         }
40824                     }
40825                     if (symbol) {
40826                         input = getNameCandidateWorker(symbol, input);
40827                     }
40828                     var i = 0;
40829                     var original = input;
40830                     while (context.usedSymbolNames.has(input)) {
40831                         i++;
40832                         input = original + "_" + i;
40833                     }
40834                     context.usedSymbolNames.set(input, true);
40835                     if (symbol) {
40836                         context.remappedSymbolNames.set("" + getSymbolId(symbol), input);
40837                     }
40838                     return input;
40839                 }
40840                 function getNameCandidateWorker(symbol, localName) {
40841                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
40842                         var flags = context.flags;
40843                         context.flags |= 16777216 /* InInitialEntityName */;
40844                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
40845                         context.flags = flags;
40846                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
40847                     }
40848                     if (localName === "default" /* Default */) {
40849                         localName = "_default";
40850                     }
40851                     else if (localName === "export=" /* ExportEquals */) {
40852                         localName = "_exports";
40853                     }
40854                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
40855                     return localName;
40856                 }
40857                 function getInternalSymbolName(symbol, localName) {
40858                     if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40859                         return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40860                     }
40861                     localName = getNameCandidateWorker(symbol, localName);
40862                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
40863                     context.remappedSymbolNames.set("" + getSymbolId(symbol), localName);
40864                     return localName;
40865                 }
40866             }
40867         }
40868         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
40869             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
40870             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
40871             function typePredicateToStringWorker(writer) {
40872                 var predicate = ts.createTypePredicateNodeWithModifier(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.createToken(124 /* AssertsKeyword */) : undefined, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217
40873                 );
40874                 var printer = ts.createPrinter({ removeComments: true });
40875                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
40876                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
40877                 return writer;
40878             }
40879         }
40880         function formatUnionTypes(types) {
40881             var result = [];
40882             var flags = 0;
40883             for (var i = 0; i < types.length; i++) {
40884                 var t = types[i];
40885                 flags |= t.flags;
40886                 if (!(t.flags & 98304 /* Nullable */)) {
40887                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
40888                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
40889                         if (baseType.flags & 1048576 /* Union */) {
40890                             var count = baseType.types.length;
40891                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
40892                                 result.push(baseType);
40893                                 i += count - 1;
40894                                 continue;
40895                             }
40896                         }
40897                     }
40898                     result.push(t);
40899                 }
40900             }
40901             if (flags & 65536 /* Null */)
40902                 result.push(nullType);
40903             if (flags & 32768 /* Undefined */)
40904                 result.push(undefinedType);
40905             return result || types;
40906         }
40907         function visibilityToString(flags) {
40908             if (flags === 8 /* Private */) {
40909                 return "private";
40910             }
40911             if (flags === 16 /* Protected */) {
40912                 return "protected";
40913             }
40914             return "public";
40915         }
40916         function getTypeAliasForTypeLiteral(type) {
40917             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
40918                 var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 182 /* ParenthesizedType */; });
40919                 if (node.kind === 247 /* TypeAliasDeclaration */) {
40920                     return getSymbolOfNode(node);
40921                 }
40922             }
40923             return undefined;
40924         }
40925         function isTopLevelInExternalModuleAugmentation(node) {
40926             return node && node.parent &&
40927                 node.parent.kind === 250 /* ModuleBlock */ &&
40928                 ts.isExternalModuleAugmentation(node.parent.parent);
40929         }
40930         function isDefaultBindingContext(location) {
40931             return location.kind === 290 /* SourceFile */ || ts.isAmbientModule(location);
40932         }
40933         function getNameOfSymbolFromNameType(symbol, context) {
40934             var nameType = getSymbolLinks(symbol).nameType;
40935             if (nameType) {
40936                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
40937                     var name = "" + nameType.value;
40938                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
40939                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
40940                     }
40941                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
40942                         return "[" + name + "]";
40943                     }
40944                     return name;
40945                 }
40946                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
40947                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
40948                 }
40949             }
40950         }
40951         /**
40952          * Gets a human-readable name for a symbol.
40953          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
40954          *
40955          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
40956          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
40957          */
40958         function getNameOfSymbolAsWritten(symbol, context) {
40959             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
40960                 // If it's not the first part of an entity name, it must print as `default`
40961                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
40962                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
40963                     !symbol.declarations ||
40964                     // if not in the same binding context (source file, module declaration), it must print as `default`
40965                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
40966                 return "default";
40967             }
40968             if (symbol.declarations && symbol.declarations.length) {
40969                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
40970                 var name_2 = declaration && ts.getNameOfDeclaration(declaration);
40971                 if (declaration && name_2) {
40972                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
40973                         return ts.symbolName(symbol);
40974                     }
40975                     if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
40976                         var nameType = getSymbolLinks(symbol).nameType;
40977                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
40978                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
40979                             var result = getNameOfSymbolFromNameType(symbol, context);
40980                             if (result !== undefined) {
40981                                 return result;
40982                             }
40983                         }
40984                     }
40985                     return ts.declarationNameToString(name_2);
40986                 }
40987                 if (!declaration) {
40988                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
40989                 }
40990                 if (declaration.parent && declaration.parent.kind === 242 /* VariableDeclaration */) {
40991                     return ts.declarationNameToString(declaration.parent.name);
40992                 }
40993                 switch (declaration.kind) {
40994                     case 214 /* ClassExpression */:
40995                     case 201 /* FunctionExpression */:
40996                     case 202 /* ArrowFunction */:
40997                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
40998                             context.encounteredError = true;
40999                         }
41000                         return declaration.kind === 214 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
41001                 }
41002             }
41003             var name = getNameOfSymbolFromNameType(symbol, context);
41004             return name !== undefined ? name : ts.symbolName(symbol);
41005         }
41006         function isDeclarationVisible(node) {
41007             if (node) {
41008                 var links = getNodeLinks(node);
41009                 if (links.isVisible === undefined) {
41010                     links.isVisible = !!determineIfDeclarationIsVisible();
41011                 }
41012                 return links.isVisible;
41013             }
41014             return false;
41015             function determineIfDeclarationIsVisible() {
41016                 switch (node.kind) {
41017                     case 315 /* JSDocCallbackTag */:
41018                     case 322 /* JSDocTypedefTag */:
41019                     case 316 /* JSDocEnumTag */:
41020                         // Top-level jsdoc type aliases are considered exported
41021                         // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
41022                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
41023                     case 191 /* BindingElement */:
41024                         return isDeclarationVisible(node.parent.parent);
41025                     case 242 /* VariableDeclaration */:
41026                         if (ts.isBindingPattern(node.name) &&
41027                             !node.name.elements.length) {
41028                             // If the binding pattern is empty, this variable declaration is not visible
41029                             return false;
41030                         }
41031                     // falls through
41032                     case 249 /* ModuleDeclaration */:
41033                     case 245 /* ClassDeclaration */:
41034                     case 246 /* InterfaceDeclaration */:
41035                     case 247 /* TypeAliasDeclaration */:
41036                     case 244 /* FunctionDeclaration */:
41037                     case 248 /* EnumDeclaration */:
41038                     case 253 /* ImportEqualsDeclaration */:
41039                         // external module augmentation is always visible
41040                         if (ts.isExternalModuleAugmentation(node)) {
41041                             return true;
41042                         }
41043                         var parent = getDeclarationContainer(node);
41044                         // If the node is not exported or it is not ambient module element (except import declaration)
41045                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
41046                             !(node.kind !== 253 /* ImportEqualsDeclaration */ && parent.kind !== 290 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
41047                             return isGlobalSourceFile(parent);
41048                         }
41049                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
41050                         return isDeclarationVisible(parent);
41051                     case 159 /* PropertyDeclaration */:
41052                     case 158 /* PropertySignature */:
41053                     case 163 /* GetAccessor */:
41054                     case 164 /* SetAccessor */:
41055                     case 161 /* MethodDeclaration */:
41056                     case 160 /* MethodSignature */:
41057                         if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
41058                             // Private/protected properties/methods are not visible
41059                             return false;
41060                         }
41061                     // Public properties/methods are visible if its parents are visible, so:
41062                     // falls through
41063                     case 162 /* Constructor */:
41064                     case 166 /* ConstructSignature */:
41065                     case 165 /* CallSignature */:
41066                     case 167 /* IndexSignature */:
41067                     case 156 /* Parameter */:
41068                     case 250 /* ModuleBlock */:
41069                     case 170 /* FunctionType */:
41070                     case 171 /* ConstructorType */:
41071                     case 173 /* TypeLiteral */:
41072                     case 169 /* TypeReference */:
41073                     case 174 /* ArrayType */:
41074                     case 175 /* TupleType */:
41075                     case 178 /* UnionType */:
41076                     case 179 /* IntersectionType */:
41077                     case 182 /* ParenthesizedType */:
41078                         return isDeclarationVisible(node.parent);
41079                     // Default binding, import specifier and namespace import is visible
41080                     // only on demand so by default it is not visible
41081                     case 255 /* ImportClause */:
41082                     case 256 /* NamespaceImport */:
41083                     case 258 /* ImportSpecifier */:
41084                         return false;
41085                     // Type parameters are always visible
41086                     case 155 /* TypeParameter */:
41087                     // Source file and namespace export are always visible
41088                     // falls through
41089                     case 290 /* SourceFile */:
41090                     case 252 /* NamespaceExportDeclaration */:
41091                         return true;
41092                     // Export assignments do not create name bindings outside the module
41093                     case 259 /* ExportAssignment */:
41094                         return false;
41095                     default:
41096                         return false;
41097                 }
41098             }
41099         }
41100         function collectLinkedAliases(node, setVisibility) {
41101             var exportSymbol;
41102             if (node.parent && node.parent.kind === 259 /* ExportAssignment */) {
41103                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
41104             }
41105             else if (node.parent.kind === 263 /* ExportSpecifier */) {
41106                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
41107             }
41108             var result;
41109             var visited;
41110             if (exportSymbol) {
41111                 visited = ts.createMap();
41112                 visited.set("" + getSymbolId(exportSymbol), true);
41113                 buildVisibleNodeList(exportSymbol.declarations);
41114             }
41115             return result;
41116             function buildVisibleNodeList(declarations) {
41117                 ts.forEach(declarations, function (declaration) {
41118                     var resultNode = getAnyImportSyntax(declaration) || declaration;
41119                     if (setVisibility) {
41120                         getNodeLinks(declaration).isVisible = true;
41121                     }
41122                     else {
41123                         result = result || [];
41124                         ts.pushIfUnique(result, resultNode);
41125                     }
41126                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
41127                         // Add the referenced top container visible
41128                         var internalModuleReference = declaration.moduleReference;
41129                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
41130                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
41131                         var id = importSymbol && "" + getSymbolId(importSymbol);
41132                         if (importSymbol && !visited.has(id)) {
41133                             visited.set(id, true);
41134                             buildVisibleNodeList(importSymbol.declarations);
41135                         }
41136                     }
41137                 });
41138             }
41139         }
41140         /**
41141          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
41142          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
41143          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
41144          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
41145          * In order to see if the same query has already been done before, the target object and the propertyName both
41146          * must match the one passed in.
41147          *
41148          * @param target The symbol, type, or signature whose type is being queried
41149          * @param propertyName The property name that should be used to query the target for its type
41150          */
41151         function pushTypeResolution(target, propertyName) {
41152             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
41153             if (resolutionCycleStartIndex >= 0) {
41154                 // A cycle was found
41155                 var length_3 = resolutionTargets.length;
41156                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
41157                     resolutionResults[i] = false;
41158                 }
41159                 return false;
41160             }
41161             resolutionTargets.push(target);
41162             resolutionResults.push(/*items*/ true);
41163             resolutionPropertyNames.push(propertyName);
41164             return true;
41165         }
41166         function findResolutionCycleStartIndex(target, propertyName) {
41167             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
41168                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
41169                     return -1;
41170                 }
41171                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
41172                     return i;
41173                 }
41174             }
41175             return -1;
41176         }
41177         function hasType(target, propertyName) {
41178             switch (propertyName) {
41179                 case 0 /* Type */:
41180                     return !!getSymbolLinks(target).type;
41181                 case 5 /* EnumTagType */:
41182                     return !!(getNodeLinks(target).resolvedEnumType);
41183                 case 2 /* DeclaredType */:
41184                     return !!getSymbolLinks(target).declaredType;
41185                 case 1 /* ResolvedBaseConstructorType */:
41186                     return !!target.resolvedBaseConstructorType;
41187                 case 3 /* ResolvedReturnType */:
41188                     return !!target.resolvedReturnType;
41189                 case 4 /* ImmediateBaseConstraint */:
41190                     return !!target.immediateBaseConstraint;
41191                 case 6 /* ResolvedTypeArguments */:
41192                     return !!target.resolvedTypeArguments;
41193             }
41194             return ts.Debug.assertNever(propertyName);
41195         }
41196         /**
41197          * Pop an entry from the type resolution stack and return its associated result value. The result value will
41198          * be true if no circularities were detected, or false if a circularity was found.
41199          */
41200         function popTypeResolution() {
41201             resolutionTargets.pop();
41202             resolutionPropertyNames.pop();
41203             return resolutionResults.pop();
41204         }
41205         function getDeclarationContainer(node) {
41206             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
41207                 switch (node.kind) {
41208                     case 242 /* VariableDeclaration */:
41209                     case 243 /* VariableDeclarationList */:
41210                     case 258 /* ImportSpecifier */:
41211                     case 257 /* NamedImports */:
41212                     case 256 /* NamespaceImport */:
41213                     case 255 /* ImportClause */:
41214                         return false;
41215                     default:
41216                         return true;
41217                 }
41218             }).parent;
41219         }
41220         function getTypeOfPrototypeProperty(prototype) {
41221             // TypeScript 1.0 spec (April 2014): 8.4
41222             // Every class automatically contains a static property member named 'prototype',
41223             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
41224             // It is an error to explicitly declare a static property member with the name 'prototype'.
41225             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
41226             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
41227         }
41228         // Return the type of the given property in the given type, or undefined if no such property exists
41229         function getTypeOfPropertyOfType(type, name) {
41230             var prop = getPropertyOfType(type, name);
41231             return prop ? getTypeOfSymbol(prop) : undefined;
41232         }
41233         function getTypeOfPropertyOrIndexSignature(type, name) {
41234             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
41235         }
41236         function isTypeAny(type) {
41237             return type && (type.flags & 1 /* Any */) !== 0;
41238         }
41239         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
41240         // assigned by contextual typing.
41241         function getTypeForBindingElementParent(node) {
41242             var symbol = getSymbolOfNode(node);
41243             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
41244         }
41245         function getRestType(source, properties, symbol) {
41246             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
41247             if (source.flags & 131072 /* Never */) {
41248                 return emptyObjectType;
41249             }
41250             if (source.flags & 1048576 /* Union */) {
41251                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
41252             }
41253             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
41254             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
41255                 if (omitKeyType.flags & 131072 /* Never */) {
41256                     return source;
41257                 }
41258                 var omitTypeAlias = getGlobalOmitSymbol();
41259                 if (!omitTypeAlias) {
41260                     return errorType;
41261                 }
41262                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
41263             }
41264             var members = ts.createSymbolTable();
41265             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
41266                 var prop = _a[_i];
41267                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
41268                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
41269                     && isSpreadableProperty(prop)) {
41270                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
41271                 }
41272             }
41273             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
41274             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
41275             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
41276             result.objectFlags |= 131072 /* ObjectRestType */;
41277             return result;
41278         }
41279         // Determine the control flow type associated with a destructuring declaration or assignment. The following
41280         // forms of destructuring are possible:
41281         //   let { x } = obj;  // BindingElement
41282         //   let [ x ] = obj;  // BindingElement
41283         //   { x } = obj;      // ShorthandPropertyAssignment
41284         //   { x: v } = obj;   // PropertyAssignment
41285         //   [ x ] = obj;      // Expression
41286         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
41287         // flow analyzer doesn't have to handle all the different syntactic forms.
41288         function getFlowTypeOfDestructuring(node, declaredType) {
41289             var reference = getSyntheticElementAccess(node);
41290             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
41291         }
41292         function getSyntheticElementAccess(node) {
41293             var parentAccess = getParentElementAccess(node);
41294             if (parentAccess && parentAccess.flowNode) {
41295                 var propName = getDestructuringPropertyName(node);
41296                 if (propName) {
41297                     var result = ts.createNode(195 /* ElementAccessExpression */, node.pos, node.end);
41298                     result.parent = node;
41299                     result.expression = parentAccess;
41300                     var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end);
41301                     literal.parent = result;
41302                     literal.text = propName;
41303                     result.argumentExpression = literal;
41304                     result.flowNode = parentAccess.flowNode;
41305                     return result;
41306                 }
41307             }
41308         }
41309         function getParentElementAccess(node) {
41310             var ancestor = node.parent.parent;
41311             switch (ancestor.kind) {
41312                 case 191 /* BindingElement */:
41313                 case 281 /* PropertyAssignment */:
41314                     return getSyntheticElementAccess(ancestor);
41315                 case 192 /* ArrayLiteralExpression */:
41316                     return getSyntheticElementAccess(node.parent);
41317                 case 242 /* VariableDeclaration */:
41318                     return ancestor.initializer;
41319                 case 209 /* BinaryExpression */:
41320                     return ancestor.right;
41321             }
41322         }
41323         function getDestructuringPropertyName(node) {
41324             var parent = node.parent;
41325             if (node.kind === 191 /* BindingElement */ && parent.kind === 189 /* ObjectBindingPattern */) {
41326                 return getLiteralPropertyNameText(node.propertyName || node.name);
41327             }
41328             if (node.kind === 281 /* PropertyAssignment */ || node.kind === 282 /* ShorthandPropertyAssignment */) {
41329                 return getLiteralPropertyNameText(node.name);
41330             }
41331             return "" + parent.elements.indexOf(node);
41332         }
41333         function getLiteralPropertyNameText(name) {
41334             var type = getLiteralTypeFromPropertyName(name);
41335             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
41336         }
41337         /** Return the inferred type for a binding element */
41338         function getTypeForBindingElement(declaration) {
41339             var pattern = declaration.parent;
41340             var parentType = getTypeForBindingElementParent(pattern.parent);
41341             // If no type or an any type was inferred for parent, infer that for the binding element
41342             if (!parentType || isTypeAny(parentType)) {
41343                 return parentType;
41344             }
41345             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
41346             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
41347                 parentType = getNonNullableType(parentType);
41348             }
41349             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
41350             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
41351                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
41352             }
41353             var type;
41354             if (pattern.kind === 189 /* ObjectBindingPattern */) {
41355                 if (declaration.dotDotDotToken) {
41356                     parentType = getReducedType(parentType);
41357                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
41358                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
41359                         return errorType;
41360                     }
41361                     var literalMembers = [];
41362                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
41363                         var element = _a[_i];
41364                         if (!element.dotDotDotToken) {
41365                             literalMembers.push(element.propertyName || element.name);
41366                         }
41367                     }
41368                     type = getRestType(parentType, literalMembers, declaration.symbol);
41369                 }
41370                 else {
41371                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
41372                     var name = declaration.propertyName || declaration.name;
41373                     var indexType = getLiteralTypeFromPropertyName(name);
41374                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
41375                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41376                 }
41377             }
41378             else {
41379                 // This elementType will be used if the specific property corresponding to this index is not
41380                 // present (aka the tuple element property). This call also checks that the parentType is in
41381                 // fact an iterable or array (depending on target language).
41382                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, parentType, undefinedType, pattern);
41383                 var index_1 = pattern.elements.indexOf(declaration);
41384                 if (declaration.dotDotDotToken) {
41385                     // If the parent is a tuple type, the rest element has a tuple type of the
41386                     // remaining tuple element types. Otherwise, the rest element has an array type with same
41387                     // element type as the parent type.
41388                     type = everyType(parentType, isTupleType) ?
41389                         mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) :
41390                         createArrayType(elementType);
41391                 }
41392                 else if (isArrayLikeType(parentType)) {
41393                     var indexType = getLiteralType(index_1);
41394                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
41395                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, declaration.name, accessFlags) || errorType, declaration.name);
41396                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41397                 }
41398                 else {
41399                     type = elementType;
41400                 }
41401             }
41402             if (!declaration.initializer) {
41403                 return type;
41404             }
41405             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
41406                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
41407                 // undefined from the final type.
41408                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
41409                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
41410                     type;
41411             }
41412             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
41413         }
41414         function getTypeForDeclarationFromJSDocComment(declaration) {
41415             var jsdocType = ts.getJSDocType(declaration);
41416             if (jsdocType) {
41417                 return getTypeFromTypeNode(jsdocType);
41418             }
41419             return undefined;
41420         }
41421         function isNullOrUndefined(node) {
41422             var expr = ts.skipParentheses(node);
41423             return expr.kind === 100 /* NullKeyword */ || expr.kind === 75 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
41424         }
41425         function isEmptyArrayLiteral(node) {
41426             var expr = ts.skipParentheses(node);
41427             return expr.kind === 192 /* ArrayLiteralExpression */ && expr.elements.length === 0;
41428         }
41429         function addOptionality(type, optional) {
41430             if (optional === void 0) { optional = true; }
41431             return strictNullChecks && optional ? getOptionalType(type) : type;
41432         }
41433         // Return the inferred type for a variable, parameter, or property declaration
41434         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
41435             // A variable declared in a for..in statement is of type string, or of type keyof T when the
41436             // right hand expression is of a type parameter type.
41437             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 231 /* ForInStatement */) {
41438                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
41439                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
41440             }
41441             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
41442                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
41443                 // missing properties/signatures required to get its iteratedType (like
41444                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
41445                 // or it may have led to an error inside getElementTypeOfIterable.
41446                 var forOfStatement = declaration.parent.parent;
41447                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
41448             }
41449             if (ts.isBindingPattern(declaration.parent)) {
41450                 return getTypeForBindingElement(declaration);
41451             }
41452             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
41453                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
41454             // Use type from type annotation if one is present
41455             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
41456             if (declaredType) {
41457                 return addOptionality(declaredType, isOptional);
41458             }
41459             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
41460                 declaration.kind === 242 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
41461                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
41462                 // If --noImplicitAny is on or the declaration is in a Javascript file,
41463                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
41464                 // initializer or a 'null' or 'undefined' initializer.
41465                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
41466                     return autoType;
41467                 }
41468                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
41469                 // literal initializer.
41470                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
41471                     return autoArrayType;
41472                 }
41473             }
41474             if (declaration.kind === 156 /* Parameter */) {
41475                 var func = declaration.parent;
41476                 // For a parameter of a set accessor, use the type of the get accessor if one is present
41477                 if (func.kind === 164 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
41478                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 163 /* GetAccessor */);
41479                     if (getter) {
41480                         var getterSignature = getSignatureFromDeclaration(getter);
41481                         var thisParameter = getAccessorThisParameter(func);
41482                         if (thisParameter && declaration === thisParameter) {
41483                             // Use the type from the *getter*
41484                             ts.Debug.assert(!thisParameter.type);
41485                             return getTypeOfSymbol(getterSignature.thisParameter);
41486                         }
41487                         return getReturnTypeOfSignature(getterSignature);
41488                     }
41489                 }
41490                 if (ts.isInJSFile(declaration)) {
41491                     var typeTag = ts.getJSDocType(func);
41492                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
41493                         return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
41494                     }
41495                 }
41496                 // Use contextual parameter type if one is available
41497                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
41498                 if (type) {
41499                     return addOptionality(type, isOptional);
41500                 }
41501             }
41502             else if (ts.isInJSFile(declaration)) {
41503                 var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
41504                 if (containerObjectType) {
41505                     return containerObjectType;
41506                 }
41507             }
41508             // Use the type of the initializer expression if one is present and the declaration is
41509             // not a parameter of a contextually typed function
41510             if (declaration.initializer) {
41511                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
41512                 return addOptionality(type, isOptional);
41513             }
41514             if (ts.isJsxAttribute(declaration)) {
41515                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
41516                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
41517                 return trueType;
41518             }
41519             // If the declaration specifies a binding pattern and is not a parameter of a contextually
41520             // typed function, use the type implied by the binding pattern
41521             if (ts.isBindingPattern(declaration.name)) {
41522                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
41523             }
41524             // No type specified and nothing can be inferred
41525             return undefined;
41526         }
41527         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
41528             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
41529             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
41530             if (container) {
41531                 var tag = ts.getJSDocTypeTag(container);
41532                 if (tag && tag.typeExpression) {
41533                     return getTypeFromTypeNode(tag.typeExpression);
41534                 }
41535                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
41536                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
41537             }
41538             var definedInConstructor = false;
41539             var definedInMethod = false;
41540             var jsdocType;
41541             var types;
41542             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
41543                 var declaration = _a[_i];
41544                 var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
41545                     ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
41546                         undefined;
41547                 if (!expression) {
41548                     continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere
41549                 }
41550                 var kind = ts.isAccessExpression(expression)
41551                     ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
41552                     : ts.getAssignmentDeclarationKind(expression);
41553                 if (kind === 4 /* ThisProperty */) {
41554                     if (isDeclarationInConstructor(expression)) {
41555                         definedInConstructor = true;
41556                     }
41557                     else {
41558                         definedInMethod = true;
41559                     }
41560                 }
41561                 if (!ts.isCallExpression(expression)) {
41562                     jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
41563                 }
41564                 if (!jsdocType) {
41565                     (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
41566                 }
41567             }
41568             var type = jsdocType;
41569             if (!type) {
41570                 if (!ts.length(types)) {
41571                     return errorType; // No types from any declarations :(
41572                 }
41573                 var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
41574                 // use only the constructor types unless they were only assigned null | undefined (including widening variants)
41575                 if (definedInMethod) {
41576                     var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
41577                     if (propType) {
41578                         (constructorTypes || (constructorTypes = [])).push(propType);
41579                         definedInConstructor = true;
41580                     }
41581                 }
41582                 var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
41583                 type = getUnionType(sourceTypes, 2 /* Subtype */);
41584             }
41585             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
41586             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
41587                 reportImplicitAny(symbol.valueDeclaration, anyType);
41588                 return anyType;
41589             }
41590             return widened;
41591         }
41592         function getJSContainerObjectType(decl, symbol, init) {
41593             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
41594                 return undefined;
41595             }
41596             var exports = ts.createSymbolTable();
41597             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
41598                 var s_2 = getSymbolOfNode(decl);
41599                 if (s_2 && ts.hasEntries(s_2.exports)) {
41600                     mergeSymbolTable(exports, s_2.exports);
41601                 }
41602                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
41603             }
41604             var s = getSymbolOfNode(decl);
41605             if (s && ts.hasEntries(s.exports)) {
41606                 mergeSymbolTable(exports, s.exports);
41607             }
41608             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
41609             type.objectFlags |= 16384 /* JSLiteral */;
41610             return type;
41611         }
41612         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
41613             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
41614             if (typeNode) {
41615                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
41616                 if (!declaredType) {
41617                     return type;
41618                 }
41619                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
41620                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
41621                 }
41622             }
41623             if (symbol.parent) {
41624                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
41625                 if (typeNode_2) {
41626                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
41627                 }
41628             }
41629             return declaredType;
41630         }
41631         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
41632         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
41633             if (ts.isCallExpression(expression)) {
41634                 if (resolvedSymbol) {
41635                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
41636                 }
41637                 var objectLitType = checkExpressionCached(expression.arguments[2]);
41638                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
41639                 if (valueType) {
41640                     return valueType;
41641                 }
41642                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
41643                 if (getFunc) {
41644                     var getSig = getSingleCallSignature(getFunc);
41645                     if (getSig) {
41646                         return getReturnTypeOfSignature(getSig);
41647                     }
41648                 }
41649                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
41650                 if (setFunc) {
41651                     var setSig = getSingleCallSignature(setFunc);
41652                     if (setSig) {
41653                         return getTypeOfFirstParameterOfSignature(setSig);
41654                     }
41655                 }
41656                 return anyType;
41657             }
41658             if (containsSameNamedThisProperty(expression.left, expression.right)) {
41659                 return anyType;
41660             }
41661             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
41662             if (type.flags & 524288 /* Object */ &&
41663                 kind === 2 /* ModuleExports */ &&
41664                 symbol.escapedName === "export=" /* ExportEquals */) {
41665                 var exportedType = resolveStructuredTypeMembers(type);
41666                 var members_4 = ts.createSymbolTable();
41667                 ts.copyEntries(exportedType.members, members_4);
41668                 if (resolvedSymbol && !resolvedSymbol.exports) {
41669                     resolvedSymbol.exports = ts.createSymbolTable();
41670                 }
41671                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
41672                     var _a;
41673                     var exportedMember = members_4.get(name);
41674                     if (exportedMember && exportedMember !== s) {
41675                         if (s.flags & 111551 /* Value */) {
41676                             // If the member has an additional value-like declaration, union the types from the two declarations,
41677                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
41678                             // a pattern like:
41679                             //
41680                             // module.exports = { a: true };
41681                             // module.exports.a = 3;
41682                             //
41683                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
41684                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
41685                             // it's unclear what that's supposed to mean, so it's probably a mistake.
41686                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
41687                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
41688                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
41689                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41690                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41691                             }
41692                             var union = createSymbol(s.flags | exportedMember.flags, name);
41693                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
41694                             union.valueDeclaration = exportedMember.valueDeclaration;
41695                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
41696                             members_4.set(name, union);
41697                         }
41698                         else {
41699                             members_4.set(name, mergeSymbol(s, exportedMember));
41700                         }
41701                     }
41702                     else {
41703                         members_4.set(name, s);
41704                     }
41705                 });
41706                 var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
41707                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
41708                 return result;
41709             }
41710             if (isEmptyArrayLiteralType(type)) {
41711                 reportImplicitAny(expression, anyArrayType);
41712                 return anyArrayType;
41713             }
41714             return type;
41715         }
41716         function containsSameNamedThisProperty(thisProperty, expression) {
41717             return ts.isPropertyAccessExpression(thisProperty)
41718                 && thisProperty.expression.kind === 104 /* ThisKeyword */
41719                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
41720         }
41721         function isDeclarationInConstructor(expression) {
41722             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
41723             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
41724             // Function expressions that are assigned to the prototype count as methods.
41725             return thisContainer.kind === 162 /* Constructor */ ||
41726                 thisContainer.kind === 244 /* FunctionDeclaration */ ||
41727                 (thisContainer.kind === 201 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
41728         }
41729         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
41730             ts.Debug.assert(types.length === declarations.length);
41731             return types.filter(function (_, i) {
41732                 var declaration = declarations[i];
41733                 var expression = ts.isBinaryExpression(declaration) ? declaration :
41734                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
41735                 return expression && isDeclarationInConstructor(expression);
41736             });
41737         }
41738         /** check for definition in base class if any declaration is in a class */
41739         function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
41740             var parentDeclaration = ts.forEach(property.declarations, function (d) {
41741                 var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
41742                 return ts.isClassLike(parent) && parent;
41743             });
41744             if (parentDeclaration) {
41745                 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
41746                 var baseClassType = classType && getBaseTypes(classType)[0];
41747                 if (baseClassType) {
41748                     return getTypeOfPropertyOfType(baseClassType, property.escapedName);
41749                 }
41750             }
41751         }
41752         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
41753         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
41754         // pattern. Otherwise, it is the type any.
41755         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
41756             if (element.initializer) {
41757                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
41758                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
41759                 // pattern.
41760                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
41761                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
41762             }
41763             if (ts.isBindingPattern(element.name)) {
41764                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
41765             }
41766             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
41767                 reportImplicitAny(element, anyType);
41768             }
41769             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
41770             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
41771             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
41772             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
41773             return includePatternInType ? nonInferrableAnyType : anyType;
41774         }
41775         // Return the type implied by an object binding pattern
41776         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
41777             var members = ts.createSymbolTable();
41778             var stringIndexInfo;
41779             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
41780             ts.forEach(pattern.elements, function (e) {
41781                 var name = e.propertyName || e.name;
41782                 if (e.dotDotDotToken) {
41783                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
41784                     return;
41785                 }
41786                 var exprType = getLiteralTypeFromPropertyName(name);
41787                 if (!isTypeUsableAsPropertyName(exprType)) {
41788                     // do not include computed properties in the implied type
41789                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
41790                     return;
41791                 }
41792                 var text = getPropertyNameFromType(exprType);
41793                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
41794                 var symbol = createSymbol(flags, text);
41795                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
41796                 symbol.bindingElement = e;
41797                 members.set(symbol.escapedName, symbol);
41798             });
41799             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
41800             result.objectFlags |= objectFlags;
41801             if (includePatternInType) {
41802                 result.pattern = pattern;
41803                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41804             }
41805             return result;
41806         }
41807         // Return the type implied by an array binding pattern
41808         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
41809             var elements = pattern.elements;
41810             var lastElement = ts.lastOrUndefined(elements);
41811             var hasRestElement = !!(lastElement && lastElement.kind === 191 /* BindingElement */ && lastElement.dotDotDotToken);
41812             if (elements.length === 0 || elements.length === 1 && hasRestElement) {
41813                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
41814             }
41815             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
41816             var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
41817             var result = createTupleType(elementTypes, minLength, hasRestElement);
41818             if (includePatternInType) {
41819                 result = cloneTypeReference(result);
41820                 result.pattern = pattern;
41821                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41822             }
41823             return result;
41824         }
41825         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
41826         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
41827         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
41828         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
41829         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
41830         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
41831         // the parameter.
41832         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
41833             if (includePatternInType === void 0) { includePatternInType = false; }
41834             if (reportErrors === void 0) { reportErrors = false; }
41835             return pattern.kind === 189 /* ObjectBindingPattern */
41836                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
41837                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
41838         }
41839         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
41840         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
41841         // is a bit more involved. For example:
41842         //
41843         //   var [x, s = ""] = [1, "one"];
41844         //
41845         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
41846         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
41847         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
41848         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
41849             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
41850         }
41851         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
41852             if (type) {
41853                 if (reportErrors) {
41854                     reportErrorsFromWidening(declaration, type);
41855                 }
41856                 // always widen a 'unique symbol' type if the type was created for a different declaration.
41857                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
41858                     type = esSymbolType;
41859                 }
41860                 return getWidenedType(type);
41861             }
41862             // Rest parameters default to type any[], other parameters default to type any
41863             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
41864             // Report implicit any errors unless this is a private property within an ambient declaration
41865             if (reportErrors) {
41866                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
41867                     reportImplicitAny(declaration, type);
41868                 }
41869             }
41870             return type;
41871         }
41872         function declarationBelongsToPrivateAmbientMember(declaration) {
41873             var root = ts.getRootDeclaration(declaration);
41874             var memberDeclaration = root.kind === 156 /* Parameter */ ? root.parent : root;
41875             return isPrivateWithinAmbient(memberDeclaration);
41876         }
41877         function tryGetTypeFromEffectiveTypeNode(declaration) {
41878             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
41879             if (typeNode) {
41880                 return getTypeFromTypeNode(typeNode);
41881             }
41882         }
41883         function getTypeOfVariableOrParameterOrProperty(symbol) {
41884             var links = getSymbolLinks(symbol);
41885             if (!links.type) {
41886                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
41887                 // For a contextually typed parameter it is possible that a type has already
41888                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
41889                 // to preserve this type.
41890                 if (!links.type) {
41891                     links.type = type;
41892                 }
41893             }
41894             return links.type;
41895         }
41896         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
41897             // Handle prototype property
41898             if (symbol.flags & 4194304 /* Prototype */) {
41899                 return getTypeOfPrototypeProperty(symbol);
41900             }
41901             // CommonsJS require and module both have type any.
41902             if (symbol === requireSymbol) {
41903                 return anyType;
41904             }
41905             if (symbol.flags & 134217728 /* ModuleExports */) {
41906                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
41907                 var members = ts.createSymbolTable();
41908                 members.set("exports", fileSymbol);
41909                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
41910             }
41911             // Handle catch clause variables
41912             var declaration = symbol.valueDeclaration;
41913             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
41914                 return anyType;
41915             }
41916             // Handle export default expressions
41917             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
41918                 if (!declaration.statements.length) {
41919                     return emptyObjectType;
41920                 }
41921                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
41922             }
41923             // Handle variable, parameter or property
41924             if (!pushTypeResolution(symbol, 0 /* Type */)) {
41925                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41926                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41927                     return getTypeOfFuncClassEnumModule(symbol);
41928                 }
41929                 return reportCircularityError(symbol);
41930             }
41931             var type;
41932             if (declaration.kind === 259 /* ExportAssignment */) {
41933                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
41934             }
41935             else if (ts.isBinaryExpression(declaration) ||
41936                 (ts.isInJSFile(declaration) &&
41937                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
41938                 type = getWidenedTypeForAssignmentDeclaration(symbol);
41939             }
41940             else if (ts.isJSDocPropertyLikeTag(declaration)
41941                 || ts.isPropertyAccessExpression(declaration)
41942                 || ts.isElementAccessExpression(declaration)
41943                 || ts.isIdentifier(declaration)
41944                 || ts.isStringLiteralLike(declaration)
41945                 || ts.isNumericLiteral(declaration)
41946                 || ts.isClassDeclaration(declaration)
41947                 || ts.isFunctionDeclaration(declaration)
41948                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
41949                 || ts.isMethodSignature(declaration)
41950                 || ts.isSourceFile(declaration)) {
41951                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41952                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
41953                     return getTypeOfFuncClassEnumModule(symbol);
41954                 }
41955                 type = ts.isBinaryExpression(declaration.parent) ?
41956                     getWidenedTypeForAssignmentDeclaration(symbol) :
41957                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
41958             }
41959             else if (ts.isPropertyAssignment(declaration)) {
41960                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
41961             }
41962             else if (ts.isJsxAttribute(declaration)) {
41963                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
41964             }
41965             else if (ts.isShorthandPropertyAssignment(declaration)) {
41966                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
41967             }
41968             else if (ts.isObjectLiteralMethod(declaration)) {
41969                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
41970             }
41971             else if (ts.isParameter(declaration)
41972                 || ts.isPropertyDeclaration(declaration)
41973                 || ts.isPropertySignature(declaration)
41974                 || ts.isVariableDeclaration(declaration)
41975                 || ts.isBindingElement(declaration)) {
41976                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
41977             }
41978             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
41979             // Re-dispatch based on valueDeclaration.kind instead.
41980             else if (ts.isEnumDeclaration(declaration)) {
41981                 type = getTypeOfFuncClassEnumModule(symbol);
41982             }
41983             else if (ts.isEnumMember(declaration)) {
41984                 type = getTypeOfEnumMember(symbol);
41985             }
41986             else if (ts.isAccessor(declaration)) {
41987                 type = resolveTypeOfAccessors(symbol);
41988             }
41989             else {
41990                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
41991             }
41992             if (!popTypeResolution()) {
41993                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41994                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41995                     return getTypeOfFuncClassEnumModule(symbol);
41996                 }
41997                 return reportCircularityError(symbol);
41998             }
41999             return type;
42000         }
42001         function getAnnotatedAccessorTypeNode(accessor) {
42002             if (accessor) {
42003                 if (accessor.kind === 163 /* GetAccessor */) {
42004                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
42005                     return getterTypeAnnotation;
42006                 }
42007                 else {
42008                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
42009                     return setterTypeAnnotation;
42010                 }
42011             }
42012             return undefined;
42013         }
42014         function getAnnotatedAccessorType(accessor) {
42015             var node = getAnnotatedAccessorTypeNode(accessor);
42016             return node && getTypeFromTypeNode(node);
42017         }
42018         function getAnnotatedAccessorThisParameter(accessor) {
42019             var parameter = getAccessorThisParameter(accessor);
42020             return parameter && parameter.symbol;
42021         }
42022         function getThisTypeOfDeclaration(declaration) {
42023             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
42024         }
42025         function getTypeOfAccessors(symbol) {
42026             var links = getSymbolLinks(symbol);
42027             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
42028         }
42029         function getTypeOfAccessorsWorker(symbol) {
42030             if (!pushTypeResolution(symbol, 0 /* Type */)) {
42031                 return errorType;
42032             }
42033             var type = resolveTypeOfAccessors(symbol);
42034             if (!popTypeResolution()) {
42035                 type = anyType;
42036                 if (noImplicitAny) {
42037                     var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42038                     error(getter, ts.Diagnostics._0_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, symbolToString(symbol));
42039                 }
42040             }
42041             return type;
42042         }
42043         function resolveTypeOfAccessors(symbol) {
42044             var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42045             var setter = ts.getDeclarationOfKind(symbol, 164 /* SetAccessor */);
42046             if (getter && ts.isInJSFile(getter)) {
42047                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
42048                 if (jsDocType) {
42049                     return jsDocType;
42050                 }
42051             }
42052             // First try to see if the user specified a return type on the get-accessor.
42053             var getterReturnType = getAnnotatedAccessorType(getter);
42054             if (getterReturnType) {
42055                 return getterReturnType;
42056             }
42057             else {
42058                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
42059                 var setterParameterType = getAnnotatedAccessorType(setter);
42060                 if (setterParameterType) {
42061                     return setterParameterType;
42062                 }
42063                 else {
42064                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
42065                     if (getter && getter.body) {
42066                         return getReturnTypeFromBody(getter);
42067                     }
42068                     // Otherwise, fall back to 'any'.
42069                     else {
42070                         if (setter) {
42071                             if (!isPrivateWithinAmbient(setter)) {
42072                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
42073                             }
42074                         }
42075                         else {
42076                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
42077                             if (!isPrivateWithinAmbient(getter)) {
42078                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
42079                             }
42080                         }
42081                         return anyType;
42082                     }
42083                 }
42084             }
42085         }
42086         function getBaseTypeVariableOfClass(symbol) {
42087             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
42088             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
42089                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
42090                     undefined;
42091         }
42092         function getTypeOfFuncClassEnumModule(symbol) {
42093             var links = getSymbolLinks(symbol);
42094             var originalLinks = links;
42095             if (!links.type) {
42096                 var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration);
42097                 if (jsDeclaration) {
42098                     var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration));
42099                     if (merged) {
42100                         // note:we overwrite links because we just cloned the symbol
42101                         symbol = links = merged;
42102                     }
42103                 }
42104                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
42105             }
42106             return links.type;
42107         }
42108         function getTypeOfFuncClassEnumModuleWorker(symbol) {
42109             var declaration = symbol.valueDeclaration;
42110             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
42111                 return anyType;
42112             }
42113             else if (declaration && (declaration.kind === 209 /* BinaryExpression */ ||
42114                 ts.isAccessExpression(declaration) &&
42115                     declaration.parent.kind === 209 /* BinaryExpression */)) {
42116                 return getWidenedTypeForAssignmentDeclaration(symbol);
42117             }
42118             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
42119                 var resolvedModule = resolveExternalModuleSymbol(symbol);
42120                 if (resolvedModule !== symbol) {
42121                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
42122                         return errorType;
42123                     }
42124                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
42125                     var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
42126                     if (!popTypeResolution()) {
42127                         return reportCircularityError(symbol);
42128                     }
42129                     return type_1;
42130                 }
42131             }
42132             var type = createObjectType(16 /* Anonymous */, symbol);
42133             if (symbol.flags & 32 /* Class */) {
42134                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
42135                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
42136             }
42137             else {
42138                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
42139             }
42140         }
42141         function getTypeOfEnumMember(symbol) {
42142             var links = getSymbolLinks(symbol);
42143             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
42144         }
42145         function getTypeOfAlias(symbol) {
42146             var links = getSymbolLinks(symbol);
42147             if (!links.type) {
42148                 var targetSymbol = resolveAlias(symbol);
42149                 // It only makes sense to get the type of a value symbol. If the result of resolving
42150                 // the alias is not a value, then it has no type. To get the type associated with a
42151                 // type symbol, call getDeclaredTypeOfSymbol.
42152                 // This check is important because without it, a call to getTypeOfSymbol could end
42153                 // up recursively calling getTypeOfAlias, causing a stack overflow.
42154                 links.type = targetSymbol.flags & 111551 /* Value */
42155                     ? getTypeOfSymbol(targetSymbol)
42156                     : errorType;
42157             }
42158             return links.type;
42159         }
42160         function getTypeOfInstantiatedSymbol(symbol) {
42161             var links = getSymbolLinks(symbol);
42162             if (!links.type) {
42163                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
42164                     return links.type = errorType;
42165                 }
42166                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
42167                 if (!popTypeResolution()) {
42168                     type = reportCircularityError(symbol);
42169                 }
42170                 links.type = type;
42171             }
42172             return links.type;
42173         }
42174         function reportCircularityError(symbol) {
42175             var declaration = symbol.valueDeclaration;
42176             // Check if variable has type annotation that circularly references the variable itself
42177             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
42178                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
42179                 return errorType;
42180             }
42181             // Check if variable has initializer that circularly references the variable itself
42182             if (noImplicitAny && (declaration.kind !== 156 /* Parameter */ || declaration.initializer)) {
42183                 error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
42184             }
42185             // Circularities could also result from parameters in function expressions that end up
42186             // having themselves as contextual types following type argument inference. In those cases
42187             // we have already reported an implicit any error so we don't report anything here.
42188             return anyType;
42189         }
42190         function getTypeOfSymbolWithDeferredType(symbol) {
42191             var links = getSymbolLinks(symbol);
42192             if (!links.type) {
42193                 ts.Debug.assertIsDefined(links.deferralParent);
42194                 ts.Debug.assertIsDefined(links.deferralConstituents);
42195                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
42196             }
42197             return links.type;
42198         }
42199         function getTypeOfSymbol(symbol) {
42200             var checkFlags = ts.getCheckFlags(symbol);
42201             if (checkFlags & 65536 /* DeferredType */) {
42202                 return getTypeOfSymbolWithDeferredType(symbol);
42203             }
42204             if (checkFlags & 1 /* Instantiated */) {
42205                 return getTypeOfInstantiatedSymbol(symbol);
42206             }
42207             if (checkFlags & 262144 /* Mapped */) {
42208                 return getTypeOfMappedSymbol(symbol);
42209             }
42210             if (checkFlags & 8192 /* ReverseMapped */) {
42211                 return getTypeOfReverseMappedSymbol(symbol);
42212             }
42213             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
42214                 return getTypeOfVariableOrParameterOrProperty(symbol);
42215             }
42216             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
42217                 return getTypeOfFuncClassEnumModule(symbol);
42218             }
42219             if (symbol.flags & 8 /* EnumMember */) {
42220                 return getTypeOfEnumMember(symbol);
42221             }
42222             if (symbol.flags & 98304 /* Accessor */) {
42223                 return getTypeOfAccessors(symbol);
42224             }
42225             if (symbol.flags & 2097152 /* Alias */) {
42226                 return getTypeOfAlias(symbol);
42227             }
42228             return errorType;
42229         }
42230         function isReferenceToType(type, target) {
42231             return type !== undefined
42232                 && target !== undefined
42233                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
42234                 && type.target === target;
42235         }
42236         function getTargetType(type) {
42237             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
42238         }
42239         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
42240         function hasBaseType(type, checkBase) {
42241             return check(type);
42242             function check(type) {
42243                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
42244                     var target = getTargetType(type);
42245                     return target === checkBase || ts.some(getBaseTypes(target), check);
42246                 }
42247                 else if (type.flags & 2097152 /* Intersection */) {
42248                     return ts.some(type.types, check);
42249                 }
42250                 return false;
42251             }
42252         }
42253         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
42254         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
42255         // in-place and returns the same array.
42256         function appendTypeParameters(typeParameters, declarations) {
42257             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
42258                 var declaration = declarations_2[_i];
42259                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
42260             }
42261             return typeParameters;
42262         }
42263         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
42264         function getOuterTypeParameters(node, includeThisTypes) {
42265             while (true) {
42266                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
42267                 if (node && ts.isBinaryExpression(node)) {
42268                     // prototype assignments get the outer type parameters of their constructor function
42269                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42270                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
42271                         var symbol = getSymbolOfNode(node.left);
42272                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
42273                             node = symbol.parent.valueDeclaration;
42274                         }
42275                     }
42276                 }
42277                 if (!node) {
42278                     return undefined;
42279                 }
42280                 switch (node.kind) {
42281                     case 225 /* VariableStatement */:
42282                     case 245 /* ClassDeclaration */:
42283                     case 214 /* ClassExpression */:
42284                     case 246 /* InterfaceDeclaration */:
42285                     case 165 /* CallSignature */:
42286                     case 166 /* ConstructSignature */:
42287                     case 160 /* MethodSignature */:
42288                     case 170 /* FunctionType */:
42289                     case 171 /* ConstructorType */:
42290                     case 300 /* JSDocFunctionType */:
42291                     case 244 /* FunctionDeclaration */:
42292                     case 161 /* MethodDeclaration */:
42293                     case 201 /* FunctionExpression */:
42294                     case 202 /* ArrowFunction */:
42295                     case 247 /* TypeAliasDeclaration */:
42296                     case 321 /* JSDocTemplateTag */:
42297                     case 322 /* JSDocTypedefTag */:
42298                     case 316 /* JSDocEnumTag */:
42299                     case 315 /* JSDocCallbackTag */:
42300                     case 186 /* MappedType */:
42301                     case 180 /* ConditionalType */:
42302                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
42303                         if (node.kind === 186 /* MappedType */) {
42304                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
42305                         }
42306                         else if (node.kind === 180 /* ConditionalType */) {
42307                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
42308                         }
42309                         else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) {
42310                             break;
42311                         }
42312                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
42313                         var thisType = includeThisTypes &&
42314                             (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
42315                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
42316                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
42317                 }
42318             }
42319         }
42320         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
42321         function getOuterTypeParametersOfClassOrInterface(symbol) {
42322             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
42323             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
42324             return getOuterTypeParameters(declaration);
42325         }
42326         // The local type parameters are the combined set of type parameters from all declarations of the class,
42327         // interface, or type alias.
42328         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
42329             var result;
42330             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42331                 var node = _a[_i];
42332                 if (node.kind === 246 /* InterfaceDeclaration */ ||
42333                     node.kind === 245 /* ClassDeclaration */ ||
42334                     node.kind === 214 /* ClassExpression */ ||
42335                     isJSConstructor(node) ||
42336                     ts.isTypeAlias(node)) {
42337                     var declaration = node;
42338                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
42339                 }
42340             }
42341             return result;
42342         }
42343         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
42344         // its locally declared type parameters.
42345         function getTypeParametersOfClassOrInterface(symbol) {
42346             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
42347         }
42348         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
42349         // rest parameter of type any[].
42350         function isMixinConstructorType(type) {
42351             var signatures = getSignaturesOfType(type, 1 /* Construct */);
42352             if (signatures.length === 1) {
42353                 var s = signatures[0];
42354                 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
42355             }
42356             return false;
42357         }
42358         function isConstructorType(type) {
42359             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
42360                 return true;
42361             }
42362             if (type.flags & 8650752 /* TypeVariable */) {
42363                 var constraint = getBaseConstraintOfType(type);
42364                 return !!constraint && isMixinConstructorType(constraint);
42365             }
42366             return false;
42367         }
42368         function getBaseTypeNodeOfClass(type) {
42369             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
42370         }
42371         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42372             var typeArgCount = ts.length(typeArgumentNodes);
42373             var isJavascript = ts.isInJSFile(location);
42374             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
42375         }
42376         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42377             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
42378             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
42379             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
42380         }
42381         /**
42382          * The base constructor of a class can resolve to
42383          * * undefinedType if the class has no extends clause,
42384          * * unknownType if an error occurred during resolution of the extends expression,
42385          * * nullType if the extends expression is the null value,
42386          * * anyType if the extends expression has type any, or
42387          * * an object type with at least one construct signature.
42388          */
42389         function getBaseConstructorTypeOfClass(type) {
42390             if (!type.resolvedBaseConstructorType) {
42391                 var decl = type.symbol.valueDeclaration;
42392                 var extended = ts.getEffectiveBaseTypeNode(decl);
42393                 var baseTypeNode = getBaseTypeNodeOfClass(type);
42394                 if (!baseTypeNode) {
42395                     return type.resolvedBaseConstructorType = undefinedType;
42396                 }
42397                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
42398                     return errorType;
42399                 }
42400                 var baseConstructorType = checkExpression(baseTypeNode.expression);
42401                 if (extended && baseTypeNode !== extended) {
42402                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
42403                     checkExpression(extended.expression);
42404                 }
42405                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
42406                     // Resolving the members of a class requires us to resolve the base class of that class.
42407                     // We force resolution here such that we catch circularities now.
42408                     resolveStructuredTypeMembers(baseConstructorType);
42409                 }
42410                 if (!popTypeResolution()) {
42411                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
42412                     return type.resolvedBaseConstructorType = errorType;
42413                 }
42414                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
42415                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
42416                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
42417                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
42418                         var ctorReturn = unknownType;
42419                         if (constraint) {
42420                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
42421                             if (ctorSig[0]) {
42422                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
42423                             }
42424                         }
42425                         ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
42426                     }
42427                     return type.resolvedBaseConstructorType = errorType;
42428                 }
42429                 type.resolvedBaseConstructorType = baseConstructorType;
42430             }
42431             return type.resolvedBaseConstructorType;
42432         }
42433         function getImplementsTypes(type) {
42434             var resolvedImplementsTypes = ts.emptyArray;
42435             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42436                 var declaration = _a[_i];
42437                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
42438                 if (!implementsTypeNodes)
42439                     continue;
42440                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
42441                     var node = implementsTypeNodes_1[_b];
42442                     var implementsType = getTypeFromTypeNode(node);
42443                     if (implementsType !== errorType) {
42444                         if (resolvedImplementsTypes === ts.emptyArray) {
42445                             resolvedImplementsTypes = [implementsType];
42446                         }
42447                         else {
42448                             resolvedImplementsTypes.push(implementsType);
42449                         }
42450                     }
42451                 }
42452             }
42453             return resolvedImplementsTypes;
42454         }
42455         function getBaseTypes(type) {
42456             if (!type.resolvedBaseTypes) {
42457                 if (type.objectFlags & 8 /* Tuple */) {
42458                     type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
42459                 }
42460                 else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42461                     if (type.symbol.flags & 32 /* Class */) {
42462                         resolveBaseTypesOfClass(type);
42463                     }
42464                     if (type.symbol.flags & 64 /* Interface */) {
42465                         resolveBaseTypesOfInterface(type);
42466                     }
42467                 }
42468                 else {
42469                     ts.Debug.fail("type must be class or interface");
42470                 }
42471             }
42472             return type.resolvedBaseTypes;
42473         }
42474         function resolveBaseTypesOfClass(type) {
42475             type.resolvedBaseTypes = ts.resolvingEmptyArray;
42476             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
42477             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
42478                 return type.resolvedBaseTypes = ts.emptyArray;
42479             }
42480             var baseTypeNode = getBaseTypeNodeOfClass(type);
42481             var baseType;
42482             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
42483             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
42484                 areAllOuterTypeParametersApplied(originalBaseType)) {
42485                 // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the
42486                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
42487                 // type arguments in the same manner as a type reference to get the same error reporting experience.
42488                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
42489             }
42490             else if (baseConstructorType.flags & 1 /* Any */) {
42491                 baseType = baseConstructorType;
42492             }
42493             else {
42494                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
42495                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
42496                 // we check that all instantiated signatures return the same type.
42497                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
42498                 if (!constructors.length) {
42499                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
42500                     return type.resolvedBaseTypes = ts.emptyArray;
42501                 }
42502                 baseType = getReturnTypeOfSignature(constructors[0]);
42503             }
42504             if (baseType === errorType) {
42505                 return type.resolvedBaseTypes = ts.emptyArray;
42506             }
42507             var reducedBaseType = getReducedType(baseType);
42508             if (!isValidBaseType(reducedBaseType)) {
42509                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
42510                 var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType));
42511                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
42512                 return type.resolvedBaseTypes = ts.emptyArray;
42513             }
42514             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
42515                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42516                 return type.resolvedBaseTypes = ts.emptyArray;
42517             }
42518             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
42519                 // Circular reference, likely through instantiation of default parameters
42520                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
42521                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
42522                 // partial instantiation of the members without the base types fully resolved
42523                 type.members = undefined;
42524             }
42525             return type.resolvedBaseTypes = [reducedBaseType];
42526         }
42527         function areAllOuterTypeParametersApplied(type) {
42528             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
42529             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
42530             var outerTypeParameters = type.outerTypeParameters;
42531             if (outerTypeParameters) {
42532                 var last_1 = outerTypeParameters.length - 1;
42533                 var typeArguments = getTypeArguments(type);
42534                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
42535             }
42536             return true;
42537         }
42538         // A valid base type is `any`, an object type or intersection of object types.
42539         function isValidBaseType(type) {
42540             if (type.flags & 262144 /* TypeParameter */) {
42541                 var constraint = getBaseConstraintOfType(type);
42542                 if (constraint) {
42543                     return isValidBaseType(constraint);
42544                 }
42545             }
42546             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
42547             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
42548             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
42549                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
42550         }
42551         function resolveBaseTypesOfInterface(type) {
42552             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
42553             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42554                 var declaration = _a[_i];
42555                 if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
42556                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
42557                         var node = _c[_b];
42558                         var baseType = getReducedType(getTypeFromTypeNode(node));
42559                         if (baseType !== errorType) {
42560                             if (isValidBaseType(baseType)) {
42561                                 if (type !== baseType && !hasBaseType(baseType, type)) {
42562                                     if (type.resolvedBaseTypes === ts.emptyArray) {
42563                                         type.resolvedBaseTypes = [baseType];
42564                                     }
42565                                     else {
42566                                         type.resolvedBaseTypes.push(baseType);
42567                                     }
42568                                 }
42569                                 else {
42570                                     error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42571                                 }
42572                             }
42573                             else {
42574                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
42575                             }
42576                         }
42577                     }
42578                 }
42579             }
42580         }
42581         /**
42582          * Returns true if the interface given by the symbol is free of "this" references.
42583          *
42584          * Specifically, the result is true if the interface itself contains no references
42585          * to "this" in its body, if all base types are interfaces,
42586          * and if none of the base interfaces have a "this" type.
42587          */
42588         function isThislessInterface(symbol) {
42589             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42590                 var declaration = _a[_i];
42591                 if (declaration.kind === 246 /* InterfaceDeclaration */) {
42592                     if (declaration.flags & 128 /* ContainsThis */) {
42593                         return false;
42594                     }
42595                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
42596                     if (baseTypeNodes) {
42597                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
42598                             var node = baseTypeNodes_1[_b];
42599                             if (ts.isEntityNameExpression(node.expression)) {
42600                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
42601                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
42602                                     return false;
42603                                 }
42604                             }
42605                         }
42606                     }
42607                 }
42608             }
42609             return true;
42610         }
42611         function getDeclaredTypeOfClassOrInterface(symbol) {
42612             var links = getSymbolLinks(symbol);
42613             var originalLinks = links;
42614             if (!links.declaredType) {
42615                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
42616                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
42617                 if (merged) {
42618                     // note:we overwrite links because we just cloned the symbol
42619                     symbol = links = merged;
42620                 }
42621                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
42622                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
42623                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42624                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
42625                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
42626                 // property types inferred from initializers and method return types inferred from return statements are very hard
42627                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
42628                 // "this" references.
42629                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
42630                     type.objectFlags |= 4 /* Reference */;
42631                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
42632                     type.outerTypeParameters = outerTypeParameters;
42633                     type.localTypeParameters = localTypeParameters;
42634                     type.instantiations = ts.createMap();
42635                     type.instantiations.set(getTypeListId(type.typeParameters), type);
42636                     type.target = type;
42637                     type.resolvedTypeArguments = type.typeParameters;
42638                     type.thisType = createTypeParameter(symbol);
42639                     type.thisType.isThisType = true;
42640                     type.thisType.constraint = type;
42641                 }
42642             }
42643             return links.declaredType;
42644         }
42645         function getDeclaredTypeOfTypeAlias(symbol) {
42646             var links = getSymbolLinks(symbol);
42647             if (!links.declaredType) {
42648                 // Note that we use the links object as the target here because the symbol object is used as the unique
42649                 // identity for resolution of the 'type' property in SymbolLinks.
42650                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
42651                     return errorType;
42652                 }
42653                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
42654                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
42655                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
42656                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
42657                 if (popTypeResolution()) {
42658                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42659                     if (typeParameters) {
42660                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
42661                         // an instantiation of the type alias with the type parameters supplied as type arguments.
42662                         links.typeParameters = typeParameters;
42663                         links.instantiations = ts.createMap();
42664                         links.instantiations.set(getTypeListId(typeParameters), type);
42665                     }
42666                 }
42667                 else {
42668                     type = errorType;
42669                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
42670                 }
42671                 links.declaredType = type;
42672             }
42673             return links.declaredType;
42674         }
42675         function isStringConcatExpression(expr) {
42676             if (ts.isStringLiteralLike(expr)) {
42677                 return true;
42678             }
42679             else if (expr.kind === 209 /* BinaryExpression */) {
42680                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
42681             }
42682             return false;
42683         }
42684         function isLiteralEnumMember(member) {
42685             var expr = member.initializer;
42686             if (!expr) {
42687                 return !(member.flags & 8388608 /* Ambient */);
42688             }
42689             switch (expr.kind) {
42690                 case 10 /* StringLiteral */:
42691                 case 8 /* NumericLiteral */:
42692                 case 14 /* NoSubstitutionTemplateLiteral */:
42693                     return true;
42694                 case 207 /* PrefixUnaryExpression */:
42695                     return expr.operator === 40 /* MinusToken */ &&
42696                         expr.operand.kind === 8 /* NumericLiteral */;
42697                 case 75 /* Identifier */:
42698                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
42699                 case 209 /* BinaryExpression */:
42700                     return isStringConcatExpression(expr);
42701                 default:
42702                     return false;
42703             }
42704         }
42705         function getEnumKind(symbol) {
42706             var links = getSymbolLinks(symbol);
42707             if (links.enumKind !== undefined) {
42708                 return links.enumKind;
42709             }
42710             var hasNonLiteralMember = false;
42711             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42712                 var declaration = _a[_i];
42713                 if (declaration.kind === 248 /* EnumDeclaration */) {
42714                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42715                         var member = _c[_b];
42716                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
42717                             return links.enumKind = 1 /* Literal */;
42718                         }
42719                         if (!isLiteralEnumMember(member)) {
42720                             hasNonLiteralMember = true;
42721                         }
42722                     }
42723                 }
42724             }
42725             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
42726         }
42727         function getBaseTypeOfEnumLiteralType(type) {
42728             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
42729         }
42730         function getDeclaredTypeOfEnum(symbol) {
42731             var links = getSymbolLinks(symbol);
42732             if (links.declaredType) {
42733                 return links.declaredType;
42734             }
42735             if (getEnumKind(symbol) === 1 /* Literal */) {
42736                 enumCount++;
42737                 var memberTypeList = [];
42738                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42739                     var declaration = _a[_i];
42740                     if (declaration.kind === 248 /* EnumDeclaration */) {
42741                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42742                             var member = _c[_b];
42743                             var value = getEnumMemberValue(member);
42744                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
42745                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
42746                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
42747                         }
42748                     }
42749                 }
42750                 if (memberTypeList.length) {
42751                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
42752                     if (enumType_1.flags & 1048576 /* Union */) {
42753                         enumType_1.flags |= 1024 /* EnumLiteral */;
42754                         enumType_1.symbol = symbol;
42755                     }
42756                     return links.declaredType = enumType_1;
42757                 }
42758             }
42759             var enumType = createType(32 /* Enum */);
42760             enumType.symbol = symbol;
42761             return links.declaredType = enumType;
42762         }
42763         function getDeclaredTypeOfEnumMember(symbol) {
42764             var links = getSymbolLinks(symbol);
42765             if (!links.declaredType) {
42766                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
42767                 if (!links.declaredType) {
42768                     links.declaredType = enumType;
42769                 }
42770             }
42771             return links.declaredType;
42772         }
42773         function getDeclaredTypeOfTypeParameter(symbol) {
42774             var links = getSymbolLinks(symbol);
42775             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
42776         }
42777         function getDeclaredTypeOfAlias(symbol) {
42778             var links = getSymbolLinks(symbol);
42779             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
42780         }
42781         function getDeclaredTypeOfSymbol(symbol) {
42782             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
42783         }
42784         function tryGetDeclaredTypeOfSymbol(symbol) {
42785             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42786                 return getDeclaredTypeOfClassOrInterface(symbol);
42787             }
42788             if (symbol.flags & 524288 /* TypeAlias */) {
42789                 return getDeclaredTypeOfTypeAlias(symbol);
42790             }
42791             if (symbol.flags & 262144 /* TypeParameter */) {
42792                 return getDeclaredTypeOfTypeParameter(symbol);
42793             }
42794             if (symbol.flags & 384 /* Enum */) {
42795                 return getDeclaredTypeOfEnum(symbol);
42796             }
42797             if (symbol.flags & 8 /* EnumMember */) {
42798                 return getDeclaredTypeOfEnumMember(symbol);
42799             }
42800             if (symbol.flags & 2097152 /* Alias */) {
42801                 return getDeclaredTypeOfAlias(symbol);
42802             }
42803             return undefined;
42804         }
42805         /**
42806          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
42807          * literal type, an array with an element type that is free of this references, or a type reference that is
42808          * free of this references.
42809          */
42810         function isThislessType(node) {
42811             switch (node.kind) {
42812                 case 125 /* AnyKeyword */:
42813                 case 148 /* UnknownKeyword */:
42814                 case 143 /* StringKeyword */:
42815                 case 140 /* NumberKeyword */:
42816                 case 151 /* BigIntKeyword */:
42817                 case 128 /* BooleanKeyword */:
42818                 case 144 /* SymbolKeyword */:
42819                 case 141 /* ObjectKeyword */:
42820                 case 110 /* VoidKeyword */:
42821                 case 146 /* UndefinedKeyword */:
42822                 case 100 /* NullKeyword */:
42823                 case 137 /* NeverKeyword */:
42824                 case 187 /* LiteralType */:
42825                     return true;
42826                 case 174 /* ArrayType */:
42827                     return isThislessType(node.elementType);
42828                 case 169 /* TypeReference */:
42829                     return !node.typeArguments || node.typeArguments.every(isThislessType);
42830             }
42831             return false;
42832         }
42833         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
42834         function isThislessTypeParameter(node) {
42835             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
42836             return !constraint || isThislessType(constraint);
42837         }
42838         /**
42839          * A variable-like declaration is free of this references if it has a type annotation
42840          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
42841          */
42842         function isThislessVariableLikeDeclaration(node) {
42843             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
42844             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
42845         }
42846         /**
42847          * A function-like declaration is considered free of `this` references if it has a return type
42848          * annotation that is free of this references and if each parameter is thisless and if
42849          * each type parameter (if present) is thisless.
42850          */
42851         function isThislessFunctionLikeDeclaration(node) {
42852             var returnType = ts.getEffectiveReturnTypeNode(node);
42853             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
42854             return (node.kind === 162 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
42855                 node.parameters.every(isThislessVariableLikeDeclaration) &&
42856                 typeParameters.every(isThislessTypeParameter);
42857         }
42858         /**
42859          * Returns true if the class or interface member given by the symbol is free of "this" references. The
42860          * function may return false for symbols that are actually free of "this" references because it is not
42861          * feasible to perform a complete analysis in all cases. In particular, property members with types
42862          * inferred from their initializers and function members with inferred return types are conservatively
42863          * assumed not to be free of "this" references.
42864          */
42865         function isThisless(symbol) {
42866             if (symbol.declarations && symbol.declarations.length === 1) {
42867                 var declaration = symbol.declarations[0];
42868                 if (declaration) {
42869                     switch (declaration.kind) {
42870                         case 159 /* PropertyDeclaration */:
42871                         case 158 /* PropertySignature */:
42872                             return isThislessVariableLikeDeclaration(declaration);
42873                         case 161 /* MethodDeclaration */:
42874                         case 160 /* MethodSignature */:
42875                         case 162 /* Constructor */:
42876                         case 163 /* GetAccessor */:
42877                         case 164 /* SetAccessor */:
42878                             return isThislessFunctionLikeDeclaration(declaration);
42879                     }
42880                 }
42881             }
42882             return false;
42883         }
42884         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
42885         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
42886         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
42887             var result = ts.createSymbolTable();
42888             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
42889                 var symbol = symbols_2[_i];
42890                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
42891             }
42892             return result;
42893         }
42894         function addInheritedMembers(symbols, baseSymbols) {
42895             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
42896                 var s = baseSymbols_1[_i];
42897                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
42898                     symbols.set(s.escapedName, s);
42899                 }
42900             }
42901         }
42902         function isStaticPrivateIdentifierProperty(s) {
42903             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasModifier(s.valueDeclaration, 32 /* Static */);
42904         }
42905         function resolveDeclaredMembers(type) {
42906             if (!type.declaredProperties) {
42907                 var symbol = type.symbol;
42908                 var members = getMembersOfSymbol(symbol);
42909                 type.declaredProperties = getNamedMembers(members);
42910                 // Start with signatures at empty array in case of recursive types
42911                 type.declaredCallSignatures = ts.emptyArray;
42912                 type.declaredConstructSignatures = ts.emptyArray;
42913                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
42914                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
42915                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
42916                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
42917             }
42918             return type;
42919         }
42920         /**
42921          * Indicates whether a type can be used as a property name.
42922          */
42923         function isTypeUsableAsPropertyName(type) {
42924             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
42925         }
42926         /**
42927          * Indicates whether a declaration name is definitely late-bindable.
42928          * A declaration name is only late-bindable if:
42929          * - It is a `ComputedPropertyName`.
42930          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
42931          * `ElementAccessExpression` consisting only of these same three types of nodes.
42932          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
42933          */
42934         function isLateBindableName(node) {
42935             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
42936                 return false;
42937             }
42938             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
42939             return ts.isEntityNameExpression(expr)
42940                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
42941         }
42942         function isLateBoundName(name) {
42943             return name.charCodeAt(0) === 95 /* _ */ &&
42944                 name.charCodeAt(1) === 95 /* _ */ &&
42945                 name.charCodeAt(2) === 64 /* at */;
42946         }
42947         /**
42948          * Indicates whether a declaration has a late-bindable dynamic name.
42949          */
42950         function hasLateBindableName(node) {
42951             var name = ts.getNameOfDeclaration(node);
42952             return !!name && isLateBindableName(name);
42953         }
42954         /**
42955          * Indicates whether a declaration has a dynamic name that cannot be late-bound.
42956          */
42957         function hasNonBindableDynamicName(node) {
42958             return ts.hasDynamicName(node) && !hasLateBindableName(node);
42959         }
42960         /**
42961          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
42962          */
42963         function isNonBindableDynamicName(node) {
42964             return ts.isDynamicName(node) && !isLateBindableName(node);
42965         }
42966         /**
42967          * Gets the symbolic name for a member from its type.
42968          */
42969         function getPropertyNameFromType(type) {
42970             if (type.flags & 8192 /* UniqueESSymbol */) {
42971                 return type.escapedName;
42972             }
42973             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
42974                 return ts.escapeLeadingUnderscores("" + type.value);
42975             }
42976             return ts.Debug.fail();
42977         }
42978         /**
42979          * Adds a declaration to a late-bound dynamic member. This performs the same function for
42980          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
42981          * members.
42982          */
42983         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
42984             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
42985             symbol.flags |= symbolFlags;
42986             getSymbolLinks(member.symbol).lateSymbol = symbol;
42987             if (!symbol.declarations) {
42988                 symbol.declarations = [member];
42989             }
42990             else {
42991                 symbol.declarations.push(member);
42992             }
42993             if (symbolFlags & 111551 /* Value */) {
42994                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
42995                     symbol.valueDeclaration = member;
42996                 }
42997             }
42998         }
42999         /**
43000          * Performs late-binding of a dynamic member. This performs the same function for
43001          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
43002          * members.
43003          *
43004          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
43005          * binding phase to attempt to resolve the name for the symbol from the type of the computed
43006          * property's expression. If the type of the expression is a string-literal, numeric-literal,
43007          * or unique symbol type, we can use that type as the name of the symbol.
43008          *
43009          * For example, given:
43010          *
43011          *   const x = Symbol();
43012          *
43013          *   interface I {
43014          *     [x]: number;
43015          *   }
43016          *
43017          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
43018          * In the late-binding phase we can type-check the expression `x` and see that it has a
43019          * unique symbol type which we can then use as the name of the member. This allows users
43020          * to define custom symbols that can be used in the members of an object type.
43021          *
43022          * @param parent The containing symbol for the member.
43023          * @param earlySymbols The early-bound symbols of the parent.
43024          * @param lateSymbols The late-bound symbols of the parent.
43025          * @param decl The member to bind.
43026          */
43027         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
43028             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
43029             var links = getNodeLinks(decl);
43030             if (!links.resolvedSymbol) {
43031                 // In the event we attempt to resolve the late-bound name of this member recursively,
43032                 // fall back to the early-bound name of this member.
43033                 links.resolvedSymbol = decl.symbol;
43034                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
43035                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
43036                 if (isTypeUsableAsPropertyName(type)) {
43037                     var memberName = getPropertyNameFromType(type);
43038                     var symbolFlags = decl.symbol.flags;
43039                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
43040                     var lateSymbol = lateSymbols.get(memberName);
43041                     if (!lateSymbol)
43042                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
43043                     // Report an error if a late-bound member has the same name as an early-bound member,
43044                     // or if we have another early-bound symbol declaration with the same name and
43045                     // conflicting flags.
43046                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
43047                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
43048                         // If we have an existing early-bound member, combine its declarations so that we can
43049                         // report an error at each declaration.
43050                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
43051                         var name_3 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
43052                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_3); });
43053                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_3);
43054                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
43055                     }
43056                     lateSymbol.nameType = type;
43057                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
43058                     if (lateSymbol.parent) {
43059                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
43060                     }
43061                     else {
43062                         lateSymbol.parent = parent;
43063                     }
43064                     return links.resolvedSymbol = lateSymbol;
43065                 }
43066             }
43067             return links.resolvedSymbol;
43068         }
43069         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
43070             var links = getSymbolLinks(symbol);
43071             if (!links[resolutionKind]) {
43072                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
43073                 var earlySymbols = !isStatic ? symbol.members :
43074                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
43075                         symbol.exports;
43076                 // In the event we recursively resolve the members/exports of the symbol, we
43077                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
43078                 // members/exports of the symbol.
43079                 links[resolutionKind] = earlySymbols || emptySymbols;
43080                 // fill in any as-yet-unresolved late-bound members.
43081                 var lateSymbols = ts.createSymbolTable();
43082                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
43083                     var decl = _a[_i];
43084                     var members = ts.getMembersOfDeclaration(decl);
43085                     if (members) {
43086                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
43087                             var member = members_5[_b];
43088                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
43089                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
43090                             }
43091                         }
43092                     }
43093                 }
43094                 var assignments = symbol.assignmentDeclarationMembers;
43095                 if (assignments) {
43096                     var decls = ts.arrayFrom(assignments.values());
43097                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
43098                         var member = decls_1[_c];
43099                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
43100                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
43101                             || assignmentKind === 4 /* ThisProperty */
43102                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
43103                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
43104                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
43105                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
43106                         }
43107                     }
43108                 }
43109                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
43110             }
43111             return links[resolutionKind];
43112         }
43113         /**
43114          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
43115          *
43116          * For a description of late-binding, see `lateBindMember`.
43117          */
43118         function getMembersOfSymbol(symbol) {
43119             return symbol.flags & 6256 /* LateBindingContainer */
43120                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
43121                 : symbol.members || emptySymbols;
43122         }
43123         /**
43124          * If a symbol is the dynamic name of the member of an object type, get the late-bound
43125          * symbol of the member.
43126          *
43127          * For a description of late-binding, see `lateBindMember`.
43128          */
43129         function getLateBoundSymbol(symbol) {
43130             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
43131                 var links = getSymbolLinks(symbol);
43132                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
43133                     // force late binding of members/exports. This will set the late-bound symbol
43134                     var parent = getMergedSymbol(symbol.parent);
43135                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
43136                         getExportsOfSymbol(parent);
43137                     }
43138                     else {
43139                         getMembersOfSymbol(parent);
43140                     }
43141                 }
43142                 return links.lateSymbol || (links.lateSymbol = symbol);
43143             }
43144             return symbol;
43145         }
43146         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
43147             if (ts.getObjectFlags(type) & 4 /* Reference */) {
43148                 var target = type.target;
43149                 var typeArguments = getTypeArguments(type);
43150                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
43151                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
43152                     return needApparentType ? getApparentType(ref) : ref;
43153                 }
43154             }
43155             else if (type.flags & 2097152 /* Intersection */) {
43156                 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
43157             }
43158             return needApparentType ? getApparentType(type) : type;
43159         }
43160         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
43161             var mapper;
43162             var members;
43163             var callSignatures;
43164             var constructSignatures;
43165             var stringIndexInfo;
43166             var numberIndexInfo;
43167             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
43168                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
43169                 callSignatures = source.declaredCallSignatures;
43170                 constructSignatures = source.declaredConstructSignatures;
43171                 stringIndexInfo = source.declaredStringIndexInfo;
43172                 numberIndexInfo = source.declaredNumberIndexInfo;
43173             }
43174             else {
43175                 mapper = createTypeMapper(typeParameters, typeArguments);
43176                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
43177                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
43178                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
43179                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
43180                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
43181             }
43182             var baseTypes = getBaseTypes(source);
43183             if (baseTypes.length) {
43184                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
43185                     members = ts.createSymbolTable(source.declaredProperties);
43186                 }
43187                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43188                 var thisArgument = ts.lastOrUndefined(typeArguments);
43189                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
43190                     var baseType = baseTypes_1[_i];
43191                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
43192                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
43193                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
43194                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
43195                     if (!stringIndexInfo) {
43196                         stringIndexInfo = instantiatedBaseType === anyType ?
43197                             createIndexInfo(anyType, /*isReadonly*/ false) :
43198                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
43199                     }
43200                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
43201                 }
43202             }
43203             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43204         }
43205         function resolveClassOrInterfaceMembers(type) {
43206             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
43207         }
43208         function resolveTypeReferenceMembers(type) {
43209             var source = resolveDeclaredMembers(type.target);
43210             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
43211             var typeArguments = getTypeArguments(type);
43212             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
43213             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
43214         }
43215         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
43216             var sig = new Signature(checker, flags);
43217             sig.declaration = declaration;
43218             sig.typeParameters = typeParameters;
43219             sig.parameters = parameters;
43220             sig.thisParameter = thisParameter;
43221             sig.resolvedReturnType = resolvedReturnType;
43222             sig.resolvedTypePredicate = resolvedTypePredicate;
43223             sig.minArgumentCount = minArgumentCount;
43224             sig.target = undefined;
43225             sig.mapper = undefined;
43226             sig.unionSignatures = undefined;
43227             return sig;
43228         }
43229         function cloneSignature(sig) {
43230             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
43231             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */);
43232             result.target = sig.target;
43233             result.mapper = sig.mapper;
43234             result.unionSignatures = sig.unionSignatures;
43235             return result;
43236         }
43237         function createUnionSignature(signature, unionSignatures) {
43238             var result = cloneSignature(signature);
43239             result.unionSignatures = unionSignatures;
43240             result.target = undefined;
43241             result.mapper = undefined;
43242             return result;
43243         }
43244         function getOptionalCallSignature(signature, callChainFlags) {
43245             if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
43246                 return signature;
43247             }
43248             if (!signature.optionalCallSignatureCache) {
43249                 signature.optionalCallSignatureCache = {};
43250             }
43251             var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
43252             return signature.optionalCallSignatureCache[key]
43253                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
43254         }
43255         function createOptionalCallSignature(signature, callChainFlags) {
43256             ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
43257             var result = cloneSignature(signature);
43258             result.flags |= callChainFlags;
43259             return result;
43260         }
43261         function getExpandedParameters(sig) {
43262             if (signatureHasRestParameter(sig)) {
43263                 var restIndex_1 = sig.parameters.length - 1;
43264                 var restParameter = sig.parameters[restIndex_1];
43265                 var restType = getTypeOfSymbol(restParameter);
43266                 if (isTupleType(restType)) {
43267                     var elementTypes = getTypeArguments(restType);
43268                     var minLength_1 = restType.target.minLength;
43269                     var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
43270                     var restParams = ts.map(elementTypes, function (t, i) {
43271                         var name = getParameterNameAtPosition(sig, restIndex_1 + i);
43272                         var checkFlags = i === tupleRestIndex_1 ? 32768 /* RestParameter */ :
43273                             i >= minLength_1 ? 16384 /* OptionalParameter */ : 0;
43274                         var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
43275                         symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
43276                         return symbol;
43277                     });
43278                     return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
43279                 }
43280             }
43281             return sig.parameters;
43282         }
43283         function getDefaultConstructSignatures(classType) {
43284             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43285             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
43286             if (baseSignatures.length === 0) {
43287                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
43288             }
43289             var baseTypeNode = getBaseTypeNodeOfClass(classType);
43290             var isJavaScript = ts.isInJSFile(baseTypeNode);
43291             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
43292             var typeArgCount = ts.length(typeArguments);
43293             var result = [];
43294             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
43295                 var baseSig = baseSignatures_1[_i];
43296                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
43297                 var typeParamCount = ts.length(baseSig.typeParameters);
43298                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
43299                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
43300                     sig.typeParameters = classType.localTypeParameters;
43301                     sig.resolvedReturnType = classType;
43302                     result.push(sig);
43303                 }
43304             }
43305             return result;
43306         }
43307         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
43308             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
43309                 var s = signatureList_1[_i];
43310                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
43311                     return s;
43312                 }
43313             }
43314         }
43315         function findMatchingSignatures(signatureLists, signature, listIndex) {
43316             if (signature.typeParameters) {
43317                 // We require an exact match for generic signatures, so we only return signatures from the first
43318                 // signature list and only if they have exact matches in the other signature lists.
43319                 if (listIndex > 0) {
43320                     return undefined;
43321                 }
43322                 for (var i = 1; i < signatureLists.length; i++) {
43323                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
43324                         return undefined;
43325                     }
43326                 }
43327                 return [signature];
43328             }
43329             var result;
43330             for (var i = 0; i < signatureLists.length; i++) {
43331                 // Allow matching non-generic signatures to have excess parameters and different return types.
43332                 // Prefer matching this types if possible.
43333                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
43334                 if (!match) {
43335                     return undefined;
43336                 }
43337                 result = ts.appendIfUnique(result, match);
43338             }
43339             return result;
43340         }
43341         // The signatures of a union type are those signatures that are present in each of the constituent types.
43342         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
43343         // parameters and may differ in return types. When signatures differ in return types, the resulting return
43344         // type is the union of the constituent return types.
43345         function getUnionSignatures(signatureLists) {
43346             var result;
43347             var indexWithLengthOverOne;
43348             for (var i = 0; i < signatureLists.length; i++) {
43349                 if (signatureLists[i].length === 0)
43350                     return ts.emptyArray;
43351                 if (signatureLists[i].length > 1) {
43352                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
43353                 }
43354                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
43355                     var signature = _a[_i];
43356                     // Only process signatures with parameter lists that aren't already in the result list
43357                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
43358                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
43359                         if (unionSignatures) {
43360                             var s = signature;
43361                             // Union the result types when more than one signature matches
43362                             if (unionSignatures.length > 1) {
43363                                 var thisParameter = signature.thisParameter;
43364                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
43365                                 if (firstThisParameterOfUnionSignatures) {
43366                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
43367                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
43368                                 }
43369                                 s = createUnionSignature(signature, unionSignatures);
43370                                 s.thisParameter = thisParameter;
43371                             }
43372                             (result || (result = [])).push(s);
43373                         }
43374                     }
43375                 }
43376             }
43377             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
43378                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
43379                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
43380                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
43381                 // signatures from the type, whose ordering would be non-obvious)
43382                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
43383                 var results = masterList.slice();
43384                 var _loop_9 = function (signatures) {
43385                     if (signatures !== masterList) {
43386                         var signature_1 = signatures[0];
43387                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
43388                         results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
43389                         if (!results) {
43390                             return "break";
43391                         }
43392                     }
43393                 };
43394                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
43395                     var signatures = signatureLists_1[_b];
43396                     var state_3 = _loop_9(signatures);
43397                     if (state_3 === "break")
43398                         break;
43399                 }
43400                 result = results;
43401             }
43402             return result || ts.emptyArray;
43403         }
43404         function combineUnionThisParam(left, right) {
43405             if (!left || !right) {
43406                 return left || right;
43407             }
43408             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
43409             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
43410             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
43411             var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
43412             return createSymbolWithType(left, thisType);
43413         }
43414         function combineUnionParameters(left, right) {
43415             var leftCount = getParameterCount(left);
43416             var rightCount = getParameterCount(right);
43417             var longest = leftCount >= rightCount ? left : right;
43418             var shorter = longest === left ? right : left;
43419             var longestCount = longest === left ? leftCount : rightCount;
43420             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
43421             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
43422             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
43423             for (var i = 0; i < longestCount; i++) {
43424                 var longestParamType = tryGetTypeAtPosition(longest, i);
43425                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
43426                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
43427                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
43428                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
43429                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
43430                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
43431                 var paramName = leftName === rightName ? leftName :
43432                     !leftName ? rightName :
43433                         !rightName ? leftName :
43434                             undefined;
43435                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
43436                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
43437                 params[i] = paramSymbol;
43438             }
43439             if (needsExtraRestElement) {
43440                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
43441                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
43442                 params[longestCount] = restParamSymbol;
43443             }
43444             return params;
43445         }
43446         function combineSignaturesOfUnionMembers(left, right) {
43447             var declaration = left.declaration;
43448             var params = combineUnionParameters(left, right);
43449             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
43450             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
43451             var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, 
43452             /*resolvedReturnType*/ undefined, 
43453             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */);
43454             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
43455             return result;
43456         }
43457         function getUnionIndexInfo(types, kind) {
43458             var indexTypes = [];
43459             var isAnyReadonly = false;
43460             for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
43461                 var type = types_3[_i];
43462                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
43463                 if (!indexInfo) {
43464                     return undefined;
43465                 }
43466                 indexTypes.push(indexInfo.type);
43467                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
43468             }
43469             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
43470         }
43471         function resolveUnionTypeMembers(type) {
43472             // The members and properties collections are empty for union types. To get all properties of a union
43473             // type use getPropertiesOfType (only the language service uses this).
43474             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
43475             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
43476             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
43477             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
43478             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43479         }
43480         function intersectTypes(type1, type2) {
43481             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
43482         }
43483         function intersectIndexInfos(info1, info2) {
43484             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
43485         }
43486         function unionSpreadIndexInfos(info1, info2) {
43487             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
43488         }
43489         function findMixins(types) {
43490             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
43491             var mixinFlags = ts.map(types, isMixinConstructorType);
43492             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
43493                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
43494                 mixinFlags[firstMixinIndex] = false;
43495             }
43496             return mixinFlags;
43497         }
43498         function includeMixinType(type, types, mixinFlags, index) {
43499             var mixedTypes = [];
43500             for (var i = 0; i < types.length; i++) {
43501                 if (i === index) {
43502                     mixedTypes.push(type);
43503                 }
43504                 else if (mixinFlags[i]) {
43505                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
43506                 }
43507             }
43508             return getIntersectionType(mixedTypes);
43509         }
43510         function resolveIntersectionTypeMembers(type) {
43511             // The members and properties collections are empty for intersection types. To get all properties of an
43512             // intersection type use getPropertiesOfType (only the language service uses this).
43513             var callSignatures;
43514             var constructSignatures;
43515             var stringIndexInfo;
43516             var numberIndexInfo;
43517             var types = type.types;
43518             var mixinFlags = findMixins(types);
43519             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
43520             var _loop_10 = function (i) {
43521                 var t = type.types[i];
43522                 // When an intersection type contains mixin constructor types, the construct signatures from
43523                 // those types are discarded and their return types are mixed into the return types of all
43524                 // other construct signatures in the intersection type. For example, the intersection type
43525                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
43526                 // 'new(s: string) => A & B'.
43527                 if (!mixinFlags[i]) {
43528                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
43529                     if (signatures.length && mixinCount > 0) {
43530                         signatures = ts.map(signatures, function (s) {
43531                             var clone = cloneSignature(s);
43532                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
43533                             return clone;
43534                         });
43535                     }
43536                     constructSignatures = appendSignatures(constructSignatures, signatures);
43537                 }
43538                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
43539                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
43540                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
43541             };
43542             for (var i = 0; i < types.length; i++) {
43543                 _loop_10(i);
43544             }
43545             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
43546         }
43547         function appendSignatures(signatures, newSignatures) {
43548             var _loop_11 = function (sig) {
43549                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
43550                     signatures = ts.append(signatures, sig);
43551                 }
43552             };
43553             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
43554                 var sig = newSignatures_1[_i];
43555                 _loop_11(sig);
43556             }
43557             return signatures;
43558         }
43559         /**
43560          * Converts an AnonymousType to a ResolvedType.
43561          */
43562         function resolveAnonymousTypeMembers(type) {
43563             var symbol = getMergedSymbol(type.symbol);
43564             if (type.target) {
43565                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43566                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
43567                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
43568                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
43569                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
43570                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
43571                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43572             }
43573             else if (symbol.flags & 2048 /* TypeLiteral */) {
43574                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43575                 var members = getMembersOfSymbol(symbol);
43576                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
43577                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
43578                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
43579                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
43580                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43581             }
43582             else {
43583                 // Combinations of function, class, enum and module
43584                 var members = emptySymbols;
43585                 var stringIndexInfo = void 0;
43586                 if (symbol.exports) {
43587                     members = getExportsOfSymbol(symbol);
43588                     if (symbol === globalThisSymbol) {
43589                         var varsOnly_1 = ts.createMap();
43590                         members.forEach(function (p) {
43591                             if (!(p.flags & 418 /* BlockScoped */)) {
43592                                 varsOnly_1.set(p.escapedName, p);
43593                             }
43594                         });
43595                         members = varsOnly_1;
43596                     }
43597                 }
43598                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
43599                 if (symbol.flags & 32 /* Class */) {
43600                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
43601                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43602                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
43603                         members = ts.createSymbolTable(getNamedMembers(members));
43604                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
43605                     }
43606                     else if (baseConstructorType === anyType) {
43607                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
43608                     }
43609                 }
43610                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
43611                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
43612                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43613                 // We resolve the members before computing the signatures because a signature may use
43614                 // typeof with a qualified name expression that circularly references the type we are
43615                 // in the process of resolving (see issue #6072). The temporarily empty signature list
43616                 // will never be observed because a qualified name can't reference signatures.
43617                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
43618                     type.callSignatures = getSignaturesOfSymbol(symbol);
43619                 }
43620                 // And likewise for construct signatures for classes
43621                 if (symbol.flags & 32 /* Class */) {
43622                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
43623                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
43624                     if (symbol.flags & 16 /* Function */) {
43625                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
43626                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) :
43627                             undefined; }));
43628                     }
43629                     if (!constructSignatures.length) {
43630                         constructSignatures = getDefaultConstructSignatures(classType_1);
43631                     }
43632                     type.constructSignatures = constructSignatures;
43633                 }
43634             }
43635         }
43636         function resolveReverseMappedTypeMembers(type) {
43637             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
43638             var modifiers = getMappedTypeModifiers(type.mappedType);
43639             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
43640             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
43641             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
43642             var members = ts.createSymbolTable();
43643             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
43644                 var prop = _a[_i];
43645                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
43646                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
43647                 inferredProp.declarations = prop.declarations;
43648                 inferredProp.nameType = getSymbolLinks(prop).nameType;
43649                 inferredProp.propertyType = getTypeOfSymbol(prop);
43650                 inferredProp.mappedType = type.mappedType;
43651                 inferredProp.constraintType = type.constraintType;
43652                 members.set(prop.escapedName, inferredProp);
43653             }
43654             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
43655         }
43656         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
43657         // bound includes those keys that are known to always be present, for example because
43658         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
43659         function getLowerBoundOfKeyType(type) {
43660             if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
43661                 return type;
43662             }
43663             if (type.flags & 4194304 /* Index */) {
43664                 return getIndexType(getApparentType(type.type));
43665             }
43666             if (type.flags & 16777216 /* Conditional */) {
43667                 if (type.root.isDistributive) {
43668                     var checkType = type.checkType;
43669                     var constraint = getLowerBoundOfKeyType(checkType);
43670                     if (constraint !== checkType) {
43671                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43672                     }
43673                 }
43674                 return type;
43675             }
43676             if (type.flags & 1048576 /* Union */) {
43677                 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43678             }
43679             if (type.flags & 2097152 /* Intersection */) {
43680                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43681             }
43682             return neverType;
43683         }
43684         /** Resolve the members of a mapped type { [P in K]: T } */
43685         function resolveMappedTypeMembers(type) {
43686             var members = ts.createSymbolTable();
43687             var stringIndexInfo;
43688             var numberIndexInfo;
43689             // Resolve upfront such that recursive references see an empty object type.
43690             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43691             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
43692             // and T as the template type.
43693             var typeParameter = getTypeParameterFromMappedType(type);
43694             var constraintType = getConstraintTypeFromMappedType(type);
43695             var templateType = getTemplateTypeFromMappedType(type.target || type);
43696             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
43697             var templateModifiers = getMappedTypeModifiers(type);
43698             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
43699             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43700                 // We have a { [P in keyof T]: X }
43701                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
43702                     var prop = _a[_i];
43703                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
43704                 }
43705                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
43706                     addMemberForKeyType(stringType);
43707                 }
43708                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
43709                     addMemberForKeyType(numberType);
43710                 }
43711             }
43712             else {
43713                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
43714             }
43715             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43716             function addMemberForKeyType(t) {
43717                 // Create a mapper from T to the current iteration type constituent. Then, if the
43718                 // mapped type is itself an instantiated type, combine the iteration mapper with the
43719                 // instantiation mapper.
43720                 var templateMapper = appendTypeMapping(type.mapper, typeParameter, t);
43721                 // If the current iteration type constituent is a string literal type, create a property.
43722                 // Otherwise, for type string create a string index signature.
43723                 if (isTypeUsableAsPropertyName(t)) {
43724                     var propName = getPropertyNameFromType(t);
43725                     var modifiersProp = getPropertyOfType(modifiersType, propName);
43726                     var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
43727                         !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
43728                     var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
43729                         !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
43730                     var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
43731                     var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
43732                     prop.mappedType = type;
43733                     prop.mapper = templateMapper;
43734                     if (modifiersProp) {
43735                         prop.syntheticOrigin = modifiersProp;
43736                         prop.declarations = modifiersProp.declarations;
43737                     }
43738                     prop.nameType = t;
43739                     members.set(propName, prop);
43740                 }
43741                 else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
43742                     var propType = instantiateType(templateType, templateMapper);
43743                     if (t.flags & (1 /* Any */ | 4 /* String */)) {
43744                         stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43745                     }
43746                     else {
43747                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43748                     }
43749                 }
43750             }
43751         }
43752         function getTypeOfMappedSymbol(symbol) {
43753             if (!symbol.type) {
43754                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
43755                     return errorType;
43756                 }
43757                 var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType);
43758                 var propType = instantiateType(templateType, symbol.mapper);
43759                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
43760                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
43761                 // mode, if the underlying property is optional we remove 'undefined' from the type.
43762                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
43763                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
43764                         propType;
43765                 if (!popTypeResolution()) {
43766                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType));
43767                     type = errorType;
43768                 }
43769                 symbol.type = type;
43770                 symbol.mapper = undefined;
43771             }
43772             return symbol.type;
43773         }
43774         function getTypeParameterFromMappedType(type) {
43775             return type.typeParameter ||
43776                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
43777         }
43778         function getConstraintTypeFromMappedType(type) {
43779             return type.constraintType ||
43780                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
43781         }
43782         function getTemplateTypeFromMappedType(type) {
43783             return type.templateType ||
43784                 (type.templateType = type.declaration.type ?
43785                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
43786                     errorType);
43787         }
43788         function getConstraintDeclarationForMappedType(type) {
43789             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
43790         }
43791         function isMappedTypeWithKeyofConstraintDeclaration(type) {
43792             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
43793             return constraintDeclaration.kind === 184 /* TypeOperator */ &&
43794                 constraintDeclaration.operator === 134 /* KeyOfKeyword */;
43795         }
43796         function getModifiersTypeFromMappedType(type) {
43797             if (!type.modifiersType) {
43798                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43799                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
43800                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
43801                     // 'keyof T' to a literal union type and we can't recover T from that type.
43802                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
43803                 }
43804                 else {
43805                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
43806                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
43807                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
43808                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
43809                     var constraint = getConstraintTypeFromMappedType(declaredType);
43810                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
43811                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
43812                 }
43813             }
43814             return type.modifiersType;
43815         }
43816         function getMappedTypeModifiers(type) {
43817             var declaration = type.declaration;
43818             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
43819                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
43820         }
43821         function getMappedTypeOptionality(type) {
43822             var modifiers = getMappedTypeModifiers(type);
43823             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
43824         }
43825         function getCombinedMappedTypeOptionality(type) {
43826             var optionality = getMappedTypeOptionality(type);
43827             var modifiersType = getModifiersTypeFromMappedType(type);
43828             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
43829         }
43830         function isPartialMappedType(type) {
43831             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
43832         }
43833         function isGenericMappedType(type) {
43834             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
43835         }
43836         function resolveStructuredTypeMembers(type) {
43837             if (!type.members) {
43838                 if (type.flags & 524288 /* Object */) {
43839                     if (type.objectFlags & 4 /* Reference */) {
43840                         resolveTypeReferenceMembers(type);
43841                     }
43842                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
43843                         resolveClassOrInterfaceMembers(type);
43844                     }
43845                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
43846                         resolveReverseMappedTypeMembers(type);
43847                     }
43848                     else if (type.objectFlags & 16 /* Anonymous */) {
43849                         resolveAnonymousTypeMembers(type);
43850                     }
43851                     else if (type.objectFlags & 32 /* Mapped */) {
43852                         resolveMappedTypeMembers(type);
43853                     }
43854                 }
43855                 else if (type.flags & 1048576 /* Union */) {
43856                     resolveUnionTypeMembers(type);
43857                 }
43858                 else if (type.flags & 2097152 /* Intersection */) {
43859                     resolveIntersectionTypeMembers(type);
43860                 }
43861             }
43862             return type;
43863         }
43864         /** Return properties of an object type or an empty array for other types */
43865         function getPropertiesOfObjectType(type) {
43866             if (type.flags & 524288 /* Object */) {
43867                 return resolveStructuredTypeMembers(type).properties;
43868             }
43869             return ts.emptyArray;
43870         }
43871         /** If the given type is an object type and that type has a property by the given name,
43872          * return the symbol for that property. Otherwise return undefined.
43873          */
43874         function getPropertyOfObjectType(type, name) {
43875             if (type.flags & 524288 /* Object */) {
43876                 var resolved = resolveStructuredTypeMembers(type);
43877                 var symbol = resolved.members.get(name);
43878                 if (symbol && symbolIsValue(symbol)) {
43879                     return symbol;
43880                 }
43881             }
43882         }
43883         function getPropertiesOfUnionOrIntersectionType(type) {
43884             if (!type.resolvedProperties) {
43885                 var members = ts.createSymbolTable();
43886                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
43887                     var current = _a[_i];
43888                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
43889                         var prop = _c[_b];
43890                         if (!members.has(prop.escapedName)) {
43891                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
43892                             if (combinedProp) {
43893                                 members.set(prop.escapedName, combinedProp);
43894                             }
43895                         }
43896                     }
43897                     // The properties of a union type are those that are present in all constituent types, so
43898                     // we only need to check the properties of the first type without index signature
43899                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
43900                         break;
43901                     }
43902                 }
43903                 type.resolvedProperties = getNamedMembers(members);
43904             }
43905             return type.resolvedProperties;
43906         }
43907         function getPropertiesOfType(type) {
43908             type = getReducedApparentType(type);
43909             return type.flags & 3145728 /* UnionOrIntersection */ ?
43910                 getPropertiesOfUnionOrIntersectionType(type) :
43911                 getPropertiesOfObjectType(type);
43912         }
43913         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
43914             var list = obj.properties;
43915             return list.some(function (property) {
43916                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
43917                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
43918                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
43919                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
43920             });
43921         }
43922         function getAllPossiblePropertiesOfTypes(types) {
43923             var unionType = getUnionType(types);
43924             if (!(unionType.flags & 1048576 /* Union */)) {
43925                 return getAugmentedPropertiesOfType(unionType);
43926             }
43927             var props = ts.createSymbolTable();
43928             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
43929                 var memberType = types_4[_i];
43930                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
43931                     var escapedName = _b[_a].escapedName;
43932                     if (!props.has(escapedName)) {
43933                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
43934                         // May be undefined if the property is private
43935                         if (prop)
43936                             props.set(escapedName, prop);
43937                     }
43938                 }
43939             }
43940             return ts.arrayFrom(props.values());
43941         }
43942         function getConstraintOfType(type) {
43943             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
43944                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
43945                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
43946                         getBaseConstraintOfType(type);
43947         }
43948         function getConstraintOfTypeParameter(typeParameter) {
43949             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
43950         }
43951         function getConstraintOfIndexedAccess(type) {
43952             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
43953         }
43954         function getSimplifiedTypeOrConstraint(type) {
43955             var simplified = getSimplifiedType(type, /*writing*/ false);
43956             return simplified !== type ? simplified : getConstraintOfType(type);
43957         }
43958         function getConstraintFromIndexedAccess(type) {
43959             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
43960             if (indexConstraint && indexConstraint !== type.indexType) {
43961                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
43962                 if (indexedAccess) {
43963                     return indexedAccess;
43964                 }
43965             }
43966             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
43967             if (objectConstraint && objectConstraint !== type.objectType) {
43968                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
43969             }
43970             return undefined;
43971         }
43972         function getDefaultConstraintOfConditionalType(type) {
43973             if (!type.resolvedDefaultConstraint) {
43974                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
43975                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
43976                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
43977                 // in effect treating `any` like `never` rather than `unknown` in this location.
43978                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
43979                 var falseConstraint = getFalseTypeFromConditionalType(type);
43980                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
43981             }
43982             return type.resolvedDefaultConstraint;
43983         }
43984         function getConstraintOfDistributiveConditionalType(type) {
43985             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
43986             // type parameter. If so, create an instantiation of the conditional type where T is replaced
43987             // with its constraint. We do this because if the constraint is a union type it will be distributed
43988             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
43989             // removes 'undefined' from T.
43990             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
43991             // as the constraint for all type params (check type included) have been replace with `unknown`, which
43992             // is going to produce even more false positive/negative results than the distribute constraint already does.
43993             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
43994             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
43995             // likely doesn't need to exist.
43996             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
43997                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
43998                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
43999                 if (constraint && constraint !== type.checkType) {
44000                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
44001                     if (!(instantiated.flags & 131072 /* Never */)) {
44002                         return instantiated;
44003                     }
44004                 }
44005             }
44006             return undefined;
44007         }
44008         function getConstraintFromConditionalType(type) {
44009             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
44010         }
44011         function getConstraintOfConditionalType(type) {
44012             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
44013         }
44014         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
44015             var constraints;
44016             var hasDisjointDomainType = false;
44017             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
44018                 var t = types_5[_i];
44019                 if (t.flags & 63176704 /* Instantiable */) {
44020                     // We keep following constraints as long as we have an instantiable type that is known
44021                     // not to be circular or infinite (hence we stop on index access types).
44022                     var constraint = getConstraintOfType(t);
44023                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
44024                         constraint = getConstraintOfType(constraint);
44025                     }
44026                     if (constraint) {
44027                         constraints = ts.append(constraints, constraint);
44028                         if (targetIsUnion) {
44029                             constraints = ts.append(constraints, t);
44030                         }
44031                     }
44032                 }
44033                 else if (t.flags & 67238908 /* DisjointDomains */) {
44034                     hasDisjointDomainType = true;
44035                 }
44036             }
44037             // If the target is a union type or if we are intersecting with types belonging to one of the
44038             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
44039             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
44040                 if (hasDisjointDomainType) {
44041                     // We add any types belong to one of the disjoint domains because they might cause the final
44042                     // intersection operation to reduce the union constraints.
44043                     for (var _a = 0, types_6 = types; _a < types_6.length; _a++) {
44044                         var t = types_6[_a];
44045                         if (t.flags & 67238908 /* DisjointDomains */) {
44046                             constraints = ts.append(constraints, t);
44047                         }
44048                     }
44049                 }
44050                 return getIntersectionType(constraints);
44051             }
44052             return undefined;
44053         }
44054         function getBaseConstraintOfType(type) {
44055             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
44056                 var constraint = getResolvedBaseConstraint(type);
44057                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
44058             }
44059             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
44060         }
44061         /**
44062          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
44063          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
44064          */
44065         function getBaseConstraintOrType(type) {
44066             return getBaseConstraintOfType(type) || type;
44067         }
44068         function hasNonCircularBaseConstraint(type) {
44069             return getResolvedBaseConstraint(type) !== circularConstraintType;
44070         }
44071         /**
44072          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
44073          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
44074          * circularly references the type variable.
44075          */
44076         function getResolvedBaseConstraint(type) {
44077             var nonTerminating = false;
44078             return type.resolvedBaseConstraint ||
44079                 (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
44080             function getImmediateBaseConstraint(t) {
44081                 if (!t.immediateBaseConstraint) {
44082                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
44083                         return circularConstraintType;
44084                     }
44085                     if (constraintDepth >= 50) {
44086                         // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
44087                         // very high likelihood we're dealing with an infinite generic type that perpetually generates
44088                         // new type identities as we descend into it. We stop the recursion here and mark this type
44089                         // and the outer types as having circular constraints.
44090                         error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
44091                         nonTerminating = true;
44092                         return t.immediateBaseConstraint = noConstraintType;
44093                     }
44094                     constraintDepth++;
44095                     var result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
44096                     constraintDepth--;
44097                     if (!popTypeResolution()) {
44098                         if (t.flags & 262144 /* TypeParameter */) {
44099                             var errorNode = getConstraintDeclaration(t);
44100                             if (errorNode) {
44101                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
44102                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
44103                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
44104                                 }
44105                             }
44106                         }
44107                         result = circularConstraintType;
44108                     }
44109                     if (nonTerminating) {
44110                         result = circularConstraintType;
44111                     }
44112                     t.immediateBaseConstraint = result || noConstraintType;
44113                 }
44114                 return t.immediateBaseConstraint;
44115             }
44116             function getBaseConstraint(t) {
44117                 var c = getImmediateBaseConstraint(t);
44118                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
44119             }
44120             function computeBaseConstraint(t) {
44121                 if (t.flags & 262144 /* TypeParameter */) {
44122                     var constraint = getConstraintFromTypeParameter(t);
44123                     return t.isThisType || !constraint ?
44124                         constraint :
44125                         getBaseConstraint(constraint);
44126                 }
44127                 if (t.flags & 3145728 /* UnionOrIntersection */) {
44128                     var types = t.types;
44129                     var baseTypes = [];
44130                     for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
44131                         var type_2 = types_7[_i];
44132                         var baseType = getBaseConstraint(type_2);
44133                         if (baseType) {
44134                             baseTypes.push(baseType);
44135                         }
44136                     }
44137                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
44138                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
44139                             undefined;
44140                 }
44141                 if (t.flags & 4194304 /* Index */) {
44142                     return keyofConstraintType;
44143                 }
44144                 if (t.flags & 8388608 /* IndexedAccess */) {
44145                     var baseObjectType = getBaseConstraint(t.objectType);
44146                     var baseIndexType = getBaseConstraint(t.indexType);
44147                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
44148                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
44149                 }
44150                 if (t.flags & 16777216 /* Conditional */) {
44151                     var constraint = getConstraintFromConditionalType(t);
44152                     constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
44153                     var result = constraint && getBaseConstraint(constraint);
44154                     constraintDepth--;
44155                     return result;
44156                 }
44157                 if (t.flags & 33554432 /* Substitution */) {
44158                     return getBaseConstraint(t.substitute);
44159                 }
44160                 return t;
44161             }
44162         }
44163         function getApparentTypeOfIntersectionType(type) {
44164             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
44165         }
44166         function getResolvedTypeParameterDefault(typeParameter) {
44167             if (!typeParameter.default) {
44168                 if (typeParameter.target) {
44169                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
44170                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
44171                 }
44172                 else {
44173                     // To block recursion, set the initial value to the resolvingDefaultType.
44174                     typeParameter.default = resolvingDefaultType;
44175                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
44176                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
44177                     if (typeParameter.default === resolvingDefaultType) {
44178                         // If we have not been called recursively, set the correct default type.
44179                         typeParameter.default = defaultType;
44180                     }
44181                 }
44182             }
44183             else if (typeParameter.default === resolvingDefaultType) {
44184                 // If we are called recursively for this type parameter, mark the default as circular.
44185                 typeParameter.default = circularConstraintType;
44186             }
44187             return typeParameter.default;
44188         }
44189         /**
44190          * Gets the default type for a type parameter.
44191          *
44192          * If the type parameter is the result of an instantiation, this gets the instantiated
44193          * default type of its target. If the type parameter has no default type or the default is
44194          * circular, `undefined` is returned.
44195          */
44196         function getDefaultFromTypeParameter(typeParameter) {
44197             var defaultType = getResolvedTypeParameterDefault(typeParameter);
44198             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
44199         }
44200         function hasNonCircularTypeParameterDefault(typeParameter) {
44201             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
44202         }
44203         /**
44204          * Indicates whether the declaration of a typeParameter has a default type.
44205          */
44206         function hasTypeParameterDefault(typeParameter) {
44207             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
44208         }
44209         function getApparentTypeOfMappedType(type) {
44210             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
44211         }
44212         function getResolvedApparentTypeOfMappedType(type) {
44213             var typeVariable = getHomomorphicTypeVariable(type);
44214             if (typeVariable) {
44215                 var constraint = getConstraintOfTypeParameter(typeVariable);
44216                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
44217                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
44218                 }
44219             }
44220             return type;
44221         }
44222         /**
44223          * For a type parameter, return the base constraint of the type parameter. For the string, number,
44224          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
44225          * type itself.
44226          */
44227         function getApparentType(type) {
44228             var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
44229             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
44230                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
44231                     t.flags & 132 /* StringLike */ ? globalStringType :
44232                         t.flags & 296 /* NumberLike */ ? globalNumberType :
44233                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
44234                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
44235                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
44236                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
44237                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
44238                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
44239                                                     t;
44240         }
44241         function getReducedApparentType(type) {
44242             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
44243             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
44244             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
44245             // that type may need futher reduction to remove empty intersections.
44246             return getReducedType(getApparentType(getReducedType(type)));
44247         }
44248         function createUnionOrIntersectionProperty(containingType, name) {
44249             var singleProp;
44250             var propSet;
44251             var indexTypes;
44252             var isUnion = containingType.flags & 1048576 /* Union */;
44253             // Flags we want to propagate to the result if they exist in all source symbols
44254             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
44255             var syntheticFlag = 4 /* SyntheticMethod */;
44256             var checkFlags = 0;
44257             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
44258                 var current = _a[_i];
44259                 var type = getApparentType(current);
44260                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
44261                     var prop = getPropertyOfType(type, name);
44262                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
44263                     if (prop) {
44264                         if (isUnion) {
44265                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
44266                         }
44267                         else {
44268                             optionalFlag &= prop.flags;
44269                         }
44270                         if (!singleProp) {
44271                             singleProp = prop;
44272                         }
44273                         else if (prop !== singleProp) {
44274                             if (!propSet) {
44275                                 propSet = ts.createMap();
44276                                 propSet.set("" + getSymbolId(singleProp), singleProp);
44277                             }
44278                             var id = "" + getSymbolId(prop);
44279                             if (!propSet.has(id)) {
44280                                 propSet.set(id, prop);
44281                             }
44282                         }
44283                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
44284                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
44285                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
44286                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
44287                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
44288                         if (!isPrototypeProperty(prop)) {
44289                             syntheticFlag = 2 /* SyntheticProperty */;
44290                         }
44291                     }
44292                     else if (isUnion) {
44293                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
44294                         if (indexInfo) {
44295                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
44296                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
44297                         }
44298                         else if (isObjectLiteralType(type)) {
44299                             checkFlags |= 32 /* WritePartial */;
44300                             indexTypes = ts.append(indexTypes, undefinedType);
44301                         }
44302                         else {
44303                             checkFlags |= 16 /* ReadPartial */;
44304                         }
44305                     }
44306                 }
44307             }
44308             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
44309                 // No property was found, or, in a union, a property has a private or protected declaration in one
44310                 // constituent, but is missing or has a different declaration in another constituent.
44311                 return undefined;
44312             }
44313             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
44314                 return singleProp;
44315             }
44316             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
44317             var declarations;
44318             var firstType;
44319             var nameType;
44320             var propTypes = [];
44321             var firstValueDeclaration;
44322             var hasNonUniformValueDeclaration = false;
44323             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
44324                 var prop = props_1[_b];
44325                 if (!firstValueDeclaration) {
44326                     firstValueDeclaration = prop.valueDeclaration;
44327                 }
44328                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
44329                     hasNonUniformValueDeclaration = true;
44330                 }
44331                 declarations = ts.addRange(declarations, prop.declarations);
44332                 var type = getTypeOfSymbol(prop);
44333                 if (!firstType) {
44334                     firstType = type;
44335                     nameType = getSymbolLinks(prop).nameType;
44336                 }
44337                 else if (type !== firstType) {
44338                     checkFlags |= 64 /* HasNonUniformType */;
44339                 }
44340                 if (isLiteralType(type)) {
44341                     checkFlags |= 128 /* HasLiteralType */;
44342                 }
44343                 if (type.flags & 131072 /* Never */) {
44344                     checkFlags |= 131072 /* HasNeverType */;
44345                 }
44346                 propTypes.push(type);
44347             }
44348             ts.addRange(propTypes, indexTypes);
44349             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
44350             result.containingType = containingType;
44351             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
44352                 result.valueDeclaration = firstValueDeclaration;
44353                 // Inherit information about parent type.
44354                 if (firstValueDeclaration.symbol.parent) {
44355                     result.parent = firstValueDeclaration.symbol.parent;
44356                 }
44357             }
44358             result.declarations = declarations;
44359             result.nameType = nameType;
44360             if (propTypes.length > 2) {
44361                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
44362                 result.checkFlags |= 65536 /* DeferredType */;
44363                 result.deferralParent = containingType;
44364                 result.deferralConstituents = propTypes;
44365             }
44366             else {
44367                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
44368             }
44369             return result;
44370         }
44371         // Return the symbol for a given property in a union or intersection type, or undefined if the property
44372         // does not exist in any constituent type. Note that the returned property may only be present in some
44373         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
44374         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
44375         // and do not appear to be present in the union type.
44376         function getUnionOrIntersectionProperty(type, name) {
44377             var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
44378             var property = properties.get(name);
44379             if (!property) {
44380                 property = createUnionOrIntersectionProperty(type, name);
44381                 if (property) {
44382                     properties.set(name, property);
44383                 }
44384             }
44385             return property;
44386         }
44387         function getPropertyOfUnionOrIntersectionType(type, name) {
44388             var property = getUnionOrIntersectionProperty(type, name);
44389             // We need to filter out partial properties in union types
44390             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
44391         }
44392         /**
44393          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
44394          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
44395          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
44396          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
44397          */
44398         function getReducedType(type) {
44399             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
44400                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
44401             }
44402             else if (type.flags & 2097152 /* Intersection */) {
44403                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
44404                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
44405                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
44406                 }
44407                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
44408             }
44409             return type;
44410         }
44411         function getReducedUnionType(unionType) {
44412             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
44413             if (reducedTypes === unionType.types) {
44414                 return unionType;
44415             }
44416             var reduced = getUnionType(reducedTypes);
44417             if (reduced.flags & 1048576 /* Union */) {
44418                 reduced.resolvedReducedType = reduced;
44419             }
44420             return reduced;
44421         }
44422         function isNeverReducedProperty(prop) {
44423             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
44424         }
44425         function isDiscriminantWithNeverType(prop) {
44426             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
44427             // a literal type and none is never, that reduces to never.
44428             return !(prop.flags & 16777216 /* Optional */) &&
44429                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
44430                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
44431         }
44432         function isConflictingPrivateProperty(prop) {
44433             // Return true for a synthetic property with multiple declarations, at least one of which is private.
44434             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
44435         }
44436         function elaborateNeverIntersection(errorInfo, type) {
44437             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
44438                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
44439                 if (neverProp) {
44440                     return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp));
44441                 }
44442                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
44443                 if (privateProp) {
44444                     return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(privateProp));
44445                 }
44446             }
44447             return errorInfo;
44448         }
44449         /**
44450          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
44451          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
44452          * Object and Function as appropriate.
44453          *
44454          * @param type a type to look up property from
44455          * @param name a name of property to look up in a given type
44456          */
44457         function getPropertyOfType(type, name) {
44458             type = getReducedApparentType(type);
44459             if (type.flags & 524288 /* Object */) {
44460                 var resolved = resolveStructuredTypeMembers(type);
44461                 var symbol = resolved.members.get(name);
44462                 if (symbol && symbolIsValue(symbol)) {
44463                     return symbol;
44464                 }
44465                 var functionType = resolved === anyFunctionType ? globalFunctionType :
44466                     resolved.callSignatures.length ? globalCallableFunctionType :
44467                         resolved.constructSignatures.length ? globalNewableFunctionType :
44468                             undefined;
44469                 if (functionType) {
44470                     var symbol_1 = getPropertyOfObjectType(functionType, name);
44471                     if (symbol_1) {
44472                         return symbol_1;
44473                     }
44474                 }
44475                 return getPropertyOfObjectType(globalObjectType, name);
44476             }
44477             if (type.flags & 3145728 /* UnionOrIntersection */) {
44478                 return getPropertyOfUnionOrIntersectionType(type, name);
44479             }
44480             return undefined;
44481         }
44482         function getSignaturesOfStructuredType(type, kind) {
44483             if (type.flags & 3670016 /* StructuredType */) {
44484                 var resolved = resolveStructuredTypeMembers(type);
44485                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
44486             }
44487             return ts.emptyArray;
44488         }
44489         /**
44490          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
44491          * maps primitive types and type parameters are to their apparent types.
44492          */
44493         function getSignaturesOfType(type, kind) {
44494             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
44495         }
44496         function getIndexInfoOfStructuredType(type, kind) {
44497             if (type.flags & 3670016 /* StructuredType */) {
44498                 var resolved = resolveStructuredTypeMembers(type);
44499                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
44500             }
44501         }
44502         function getIndexTypeOfStructuredType(type, kind) {
44503             var info = getIndexInfoOfStructuredType(type, kind);
44504             return info && info.type;
44505         }
44506         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
44507         // maps primitive types and type parameters are to their apparent types.
44508         function getIndexInfoOfType(type, kind) {
44509             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
44510         }
44511         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
44512         // maps primitive types and type parameters are to their apparent types.
44513         function getIndexTypeOfType(type, kind) {
44514             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
44515         }
44516         function getImplicitIndexTypeOfType(type, kind) {
44517             if (isObjectTypeWithInferableIndex(type)) {
44518                 var propTypes = [];
44519                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
44520                     var prop = _a[_i];
44521                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
44522                         propTypes.push(getTypeOfSymbol(prop));
44523                     }
44524                 }
44525                 if (kind === 0 /* String */) {
44526                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
44527                 }
44528                 if (propTypes.length) {
44529                     return getUnionType(propTypes);
44530                 }
44531             }
44532             return undefined;
44533         }
44534         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
44535         // type checking functions).
44536         function getTypeParametersFromDeclaration(declaration) {
44537             var result;
44538             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
44539                 var node = _a[_i];
44540                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
44541             }
44542             return result;
44543         }
44544         function symbolsToArray(symbols) {
44545             var result = [];
44546             symbols.forEach(function (symbol, id) {
44547                 if (!isReservedMemberName(id)) {
44548                     result.push(symbol);
44549                 }
44550             });
44551             return result;
44552         }
44553         function isJSDocOptionalParameter(node) {
44554             return ts.isInJSFile(node) && (
44555             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
44556             node.type && node.type.kind === 299 /* JSDocOptionalType */
44557                 || ts.getJSDocParameterTags(node).some(function (_a) {
44558                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
44559                     return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44560                 }));
44561         }
44562         function tryFindAmbientModule(moduleName, withAugmentations) {
44563             if (ts.isExternalModuleNameRelative(moduleName)) {
44564                 return undefined;
44565             }
44566             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
44567             // merged symbol is module declaration symbol combined with all augmentations
44568             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
44569         }
44570         function isOptionalParameter(node) {
44571             if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
44572                 return true;
44573             }
44574             if (node.initializer) {
44575                 var signature = getSignatureFromDeclaration(node.parent);
44576                 var parameterIndex = node.parent.parameters.indexOf(node);
44577                 ts.Debug.assert(parameterIndex >= 0);
44578                 return parameterIndex >= getMinArgumentCount(signature, /*strongArityForUntypedJS*/ true);
44579             }
44580             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
44581             if (iife) {
44582                 return !node.type &&
44583                     !node.dotDotDotToken &&
44584                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
44585             }
44586             return false;
44587         }
44588         function isOptionalJSDocParameterTag(node) {
44589             if (!ts.isJSDocParameterTag(node)) {
44590                 return false;
44591             }
44592             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
44593             return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44594         }
44595         function createTypePredicate(kind, parameterName, parameterIndex, type) {
44596             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
44597         }
44598         /**
44599          * Gets the minimum number of type arguments needed to satisfy all non-optional type
44600          * parameters.
44601          */
44602         function getMinTypeArgumentCount(typeParameters) {
44603             var minTypeArgumentCount = 0;
44604             if (typeParameters) {
44605                 for (var i = 0; i < typeParameters.length; i++) {
44606                     if (!hasTypeParameterDefault(typeParameters[i])) {
44607                         minTypeArgumentCount = i + 1;
44608                     }
44609                 }
44610             }
44611             return minTypeArgumentCount;
44612         }
44613         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
44614             var numTypeParameters = ts.length(typeParameters);
44615             if (!numTypeParameters) {
44616                 return [];
44617             }
44618             var numTypeArguments = ts.length(typeArguments);
44619             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
44620                 var result = typeArguments ? typeArguments.slice() : [];
44621                 // Map invalid forward references in default types to the error type
44622                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44623                     result[i] = errorType;
44624                 }
44625                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
44626                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44627                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
44628                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
44629                         defaultType = anyType;
44630                     }
44631                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
44632                 }
44633                 result.length = typeParameters.length;
44634                 return result;
44635             }
44636             return typeArguments && typeArguments.slice();
44637         }
44638         function getSignatureFromDeclaration(declaration) {
44639             var links = getNodeLinks(declaration);
44640             if (!links.resolvedSignature) {
44641                 var parameters = [];
44642                 var flags = 0 /* None */;
44643                 var minArgumentCount = 0;
44644                 var thisParameter = void 0;
44645                 var hasThisParameter = false;
44646                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
44647                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
44648                 var isUntypedSignatureInJSFile = !iife &&
44649                     ts.isInJSFile(declaration) &&
44650                     ts.isValueSignatureDeclaration(declaration) &&
44651                     !ts.hasJSDocParameterTags(declaration) &&
44652                     !ts.getJSDocType(declaration);
44653                 if (isUntypedSignatureInJSFile) {
44654                     flags |= 16 /* IsUntypedSignatureInJSFile */;
44655                 }
44656                 // If this is a JSDoc construct signature, then skip the first parameter in the
44657                 // parameter list.  The first parameter represents the return type of the construct
44658                 // signature.
44659                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
44660                     var param = declaration.parameters[i];
44661                     var paramSymbol = param.symbol;
44662                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
44663                     // Include parameter symbol instead of property symbol in the signature
44664                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
44665                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
44666                         paramSymbol = resolvedSymbol;
44667                     }
44668                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
44669                         hasThisParameter = true;
44670                         thisParameter = param.symbol;
44671                     }
44672                     else {
44673                         parameters.push(paramSymbol);
44674                     }
44675                     if (type && type.kind === 187 /* LiteralType */) {
44676                         flags |= 2 /* HasLiteralTypes */;
44677                     }
44678                     // Record a new minimum argument count if this is not an optional parameter
44679                     var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
44680                         param.initializer || param.questionToken || param.dotDotDotToken ||
44681                         iife && parameters.length > iife.arguments.length && !type ||
44682                         isJSDocOptionalParameter(param);
44683                     if (!isOptionalParameter_1) {
44684                         minArgumentCount = parameters.length;
44685                     }
44686                 }
44687                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
44688                 if ((declaration.kind === 163 /* GetAccessor */ || declaration.kind === 164 /* SetAccessor */) &&
44689                     !hasNonBindableDynamicName(declaration) &&
44690                     (!hasThisParameter || !thisParameter)) {
44691                     var otherKind = declaration.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
44692                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
44693                     if (other) {
44694                         thisParameter = getAnnotatedAccessorThisParameter(other);
44695                     }
44696                 }
44697                 var classType = declaration.kind === 162 /* Constructor */ ?
44698                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
44699                     : undefined;
44700                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
44701                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
44702                     flags |= 1 /* HasRestParameter */;
44703                 }
44704                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
44705                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
44706             }
44707             return links.resolvedSignature;
44708         }
44709         /**
44710          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
44711          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
44712          * OR
44713          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
44714          */
44715         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
44716             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
44717                 return false;
44718             }
44719             var lastParam = ts.lastOrUndefined(declaration.parameters);
44720             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
44721             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
44722                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
44723             });
44724             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
44725             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
44726             if (lastParamVariadicType) {
44727                 // Replace the last parameter with a rest parameter.
44728                 parameters.pop();
44729             }
44730             parameters.push(syntheticArgsSymbol);
44731             return true;
44732         }
44733         function getSignatureOfTypeTag(node) {
44734             // should be attached to a function declaration or expression
44735             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
44736                 return undefined;
44737             var typeTag = ts.getJSDocTypeTag(node);
44738             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
44739             return signature && getErasedSignature(signature);
44740         }
44741         function getReturnTypeOfTypeTag(node) {
44742             var signature = getSignatureOfTypeTag(node);
44743             return signature && getReturnTypeOfSignature(signature);
44744         }
44745         function containsArgumentsReference(declaration) {
44746             var links = getNodeLinks(declaration);
44747             if (links.containsArgumentsReference === undefined) {
44748                 if (links.flags & 8192 /* CaptureArguments */) {
44749                     links.containsArgumentsReference = true;
44750                 }
44751                 else {
44752                     links.containsArgumentsReference = traverse(declaration.body);
44753                 }
44754             }
44755             return links.containsArgumentsReference;
44756             function traverse(node) {
44757                 if (!node)
44758                     return false;
44759                 switch (node.kind) {
44760                     case 75 /* Identifier */:
44761                         return node.escapedText === "arguments" && ts.isExpressionNode(node);
44762                     case 159 /* PropertyDeclaration */:
44763                     case 161 /* MethodDeclaration */:
44764                     case 163 /* GetAccessor */:
44765                     case 164 /* SetAccessor */:
44766                         return node.name.kind === 154 /* ComputedPropertyName */
44767                             && traverse(node.name);
44768                     default:
44769                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
44770                 }
44771             }
44772         }
44773         function getSignaturesOfSymbol(symbol) {
44774             if (!symbol)
44775                 return ts.emptyArray;
44776             var result = [];
44777             for (var i = 0; i < symbol.declarations.length; i++) {
44778                 var decl = symbol.declarations[i];
44779                 if (!ts.isFunctionLike(decl))
44780                     continue;
44781                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
44782                 // an implementation node if it has a body and the previous node is of the same kind and immediately
44783                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
44784                 if (i > 0 && decl.body) {
44785                     var previous = symbol.declarations[i - 1];
44786                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
44787                         continue;
44788                     }
44789                 }
44790                 result.push(getSignatureFromDeclaration(decl));
44791             }
44792             return result;
44793         }
44794         function resolveExternalModuleTypeByLiteral(name) {
44795             var moduleSym = resolveExternalModuleName(name, name);
44796             if (moduleSym) {
44797                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
44798                 if (resolvedModuleSymbol) {
44799                     return getTypeOfSymbol(resolvedModuleSymbol);
44800                 }
44801             }
44802             return anyType;
44803         }
44804         function getThisTypeOfSignature(signature) {
44805             if (signature.thisParameter) {
44806                 return getTypeOfSymbol(signature.thisParameter);
44807             }
44808         }
44809         function getTypePredicateOfSignature(signature) {
44810             if (!signature.resolvedTypePredicate) {
44811                 if (signature.target) {
44812                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
44813                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
44814                 }
44815                 else if (signature.unionSignatures) {
44816                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
44817                 }
44818                 else {
44819                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
44820                     var jsdocPredicate = void 0;
44821                     if (!type && ts.isInJSFile(signature.declaration)) {
44822                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
44823                         if (jsdocSignature && signature !== jsdocSignature) {
44824                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
44825                         }
44826                     }
44827                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
44828                         createTypePredicateFromTypePredicateNode(type, signature) :
44829                         jsdocPredicate || noTypePredicate;
44830                 }
44831                 ts.Debug.assert(!!signature.resolvedTypePredicate);
44832             }
44833             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
44834         }
44835         function createTypePredicateFromTypePredicateNode(node, signature) {
44836             var parameterName = node.parameterName;
44837             var type = node.type && getTypeFromTypeNode(node.type);
44838             return parameterName.kind === 183 /* ThisType */ ?
44839                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
44840                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
44841         }
44842         function getReturnTypeOfSignature(signature) {
44843             if (!signature.resolvedReturnType) {
44844                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
44845                     return errorType;
44846                 }
44847                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
44848                     signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
44849                         getReturnTypeFromAnnotation(signature.declaration) ||
44850                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
44851                 if (signature.flags & 4 /* IsInnerCallChain */) {
44852                     type = addOptionalTypeMarker(type);
44853                 }
44854                 else if (signature.flags & 8 /* IsOuterCallChain */) {
44855                     type = getOptionalType(type);
44856                 }
44857                 if (!popTypeResolution()) {
44858                     if (signature.declaration) {
44859                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
44860                         if (typeNode) {
44861                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
44862                         }
44863                         else if (noImplicitAny) {
44864                             var declaration = signature.declaration;
44865                             var name = ts.getNameOfDeclaration(declaration);
44866                             if (name) {
44867                                 error(name, ts.Diagnostics._0_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, ts.declarationNameToString(name));
44868                             }
44869                             else {
44870                                 error(declaration, ts.Diagnostics.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);
44871                             }
44872                         }
44873                     }
44874                     type = anyType;
44875                 }
44876                 signature.resolvedReturnType = type;
44877             }
44878             return signature.resolvedReturnType;
44879         }
44880         function getReturnTypeFromAnnotation(declaration) {
44881             if (declaration.kind === 162 /* Constructor */) {
44882                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
44883             }
44884             if (ts.isJSDocConstructSignature(declaration)) {
44885                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
44886             }
44887             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
44888             if (typeNode) {
44889                 return getTypeFromTypeNode(typeNode);
44890             }
44891             if (declaration.kind === 163 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
44892                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
44893                 if (jsDocType) {
44894                     return jsDocType;
44895                 }
44896                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 164 /* SetAccessor */);
44897                 var setterType = getAnnotatedAccessorType(setter);
44898                 if (setterType) {
44899                     return setterType;
44900                 }
44901             }
44902             return getReturnTypeOfTypeTag(declaration);
44903         }
44904         function isResolvingReturnTypeOfSignature(signature) {
44905             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
44906         }
44907         function getRestTypeOfSignature(signature) {
44908             return tryGetRestTypeOfSignature(signature) || anyType;
44909         }
44910         function tryGetRestTypeOfSignature(signature) {
44911             if (signatureHasRestParameter(signature)) {
44912                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
44913                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
44914                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
44915             }
44916             return undefined;
44917         }
44918         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
44919             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
44920             if (inferredTypeParameters) {
44921                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
44922                 if (returnSignature) {
44923                     var newReturnSignature = cloneSignature(returnSignature);
44924                     newReturnSignature.typeParameters = inferredTypeParameters;
44925                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
44926                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
44927                     return newInstantiatedSignature;
44928                 }
44929             }
44930             return instantiatedSignature;
44931         }
44932         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
44933             var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
44934             var id = getTypeListId(typeArguments);
44935             var instantiation = instantiations.get(id);
44936             if (!instantiation) {
44937                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
44938             }
44939             return instantiation;
44940         }
44941         function createSignatureInstantiation(signature, typeArguments) {
44942             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
44943         }
44944         function createSignatureTypeMapper(signature, typeArguments) {
44945             return createTypeMapper(signature.typeParameters, typeArguments);
44946         }
44947         function getErasedSignature(signature) {
44948             return signature.typeParameters ?
44949                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
44950                 signature;
44951         }
44952         function createErasedSignature(signature) {
44953             // Create an instantiation of the signature where all type arguments are the any type.
44954             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
44955         }
44956         function getCanonicalSignature(signature) {
44957             return signature.typeParameters ?
44958                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
44959                 signature;
44960         }
44961         function createCanonicalSignature(signature) {
44962             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
44963             // its original. When a generic class or interface is instantiated, each generic method in the class or
44964             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
44965             // where different generations of the same type parameter are in scope). This leads to a lot of new type
44966             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
44967             // that uses the original type identities for all unconstrained type parameters.
44968             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
44969         }
44970         function getBaseSignature(signature) {
44971             var typeParameters = signature.typeParameters;
44972             if (typeParameters) {
44973                 var typeEraser_1 = createTypeEraser(typeParameters);
44974                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
44975                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
44976             }
44977             return signature;
44978         }
44979         function getOrCreateTypeFromSignature(signature) {
44980             // There are two ways to declare a construct signature, one is by declaring a class constructor
44981             // using the constructor keyword, and the other is declaring a bare construct signature in an
44982             // object type literal or interface (using the new keyword). Each way of declaring a constructor
44983             // will result in a different declaration kind.
44984             if (!signature.isolatedSignatureType) {
44985                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
44986                 var isConstructor = kind === 162 /* Constructor */ || kind === 166 /* ConstructSignature */ || kind === 171 /* ConstructorType */;
44987                 var type = createObjectType(16 /* Anonymous */);
44988                 type.members = emptySymbols;
44989                 type.properties = ts.emptyArray;
44990                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
44991                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
44992                 signature.isolatedSignatureType = type;
44993             }
44994             return signature.isolatedSignatureType;
44995         }
44996         function getIndexSymbol(symbol) {
44997             return symbol.members.get("__index" /* Index */);
44998         }
44999         function getIndexDeclarationOfSymbol(symbol, kind) {
45000             var syntaxKind = kind === 1 /* Number */ ? 140 /* NumberKeyword */ : 143 /* StringKeyword */;
45001             var indexSymbol = getIndexSymbol(symbol);
45002             if (indexSymbol) {
45003                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
45004                     var decl = _a[_i];
45005                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
45006                     if (node.parameters.length === 1) {
45007                         var parameter = node.parameters[0];
45008                         if (parameter.type && parameter.type.kind === syntaxKind) {
45009                             return node;
45010                         }
45011                     }
45012                 }
45013             }
45014             return undefined;
45015         }
45016         function createIndexInfo(type, isReadonly, declaration) {
45017             return { type: type, isReadonly: isReadonly, declaration: declaration };
45018         }
45019         function getIndexInfoOfSymbol(symbol, kind) {
45020             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
45021             if (declaration) {
45022                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
45023             }
45024             return undefined;
45025         }
45026         function getConstraintDeclaration(type) {
45027             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
45028         }
45029         function getInferredTypeParameterConstraint(typeParameter) {
45030             var inferences;
45031             if (typeParameter.symbol) {
45032                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
45033                     var declaration = _a[_i];
45034                     if (declaration.parent.kind === 181 /* InferType */) {
45035                         // When an 'infer T' declaration is immediately contained in a type reference node
45036                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
45037                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
45038                         // present, we form an intersection of the inferred constraint types.
45039                         var grandParent = declaration.parent.parent;
45040                         if (grandParent.kind === 169 /* TypeReference */) {
45041                             var typeReference = grandParent;
45042                             var typeParameters = getTypeParametersForTypeReference(typeReference);
45043                             if (typeParameters) {
45044                                 var index = typeReference.typeArguments.indexOf(declaration.parent);
45045                                 if (index < typeParameters.length) {
45046                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
45047                                     if (declaredConstraint) {
45048                                         // Type parameter constraints can reference other type parameters so
45049                                         // constraints need to be instantiated. If instantiation produces the
45050                                         // type parameter itself, we discard that inference. For example, in
45051                                         //   type Foo<T extends string, U extends T> = [T, U];
45052                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
45053                                         // the instantiated constraint for U is X, so we discard that inference.
45054                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
45055                                         var constraint = instantiateType(declaredConstraint, mapper);
45056                                         if (constraint !== typeParameter) {
45057                                             inferences = ts.append(inferences, constraint);
45058                                         }
45059                                     }
45060                                 }
45061                             }
45062                         }
45063                         // When an 'infer T' declaration is immediately contained in a rest parameter
45064                         // declaration, we infer an 'unknown[]' constraint.
45065                         else if (grandParent.kind === 156 /* Parameter */ && grandParent.dotDotDotToken) {
45066                             inferences = ts.append(inferences, createArrayType(unknownType));
45067                         }
45068                     }
45069                 }
45070             }
45071             return inferences && getIntersectionType(inferences);
45072         }
45073         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
45074         function getConstraintFromTypeParameter(typeParameter) {
45075             if (!typeParameter.constraint) {
45076                 if (typeParameter.target) {
45077                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
45078                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
45079                 }
45080                 else {
45081                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
45082                     if (!constraintDeclaration) {
45083                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
45084                     }
45085                     else {
45086                         var type = getTypeFromTypeNode(constraintDeclaration);
45087                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
45088                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
45089                             // use unknown otherwise
45090                             type = constraintDeclaration.parent.parent.kind === 186 /* MappedType */ ? keyofConstraintType : unknownType;
45091                         }
45092                         typeParameter.constraint = type;
45093                     }
45094                 }
45095             }
45096             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
45097         }
45098         function getParentSymbolOfTypeParameter(typeParameter) {
45099             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 155 /* TypeParameter */);
45100             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
45101             return host && getSymbolOfNode(host);
45102         }
45103         function getTypeListId(types) {
45104             var result = "";
45105             if (types) {
45106                 var length_4 = types.length;
45107                 var i = 0;
45108                 while (i < length_4) {
45109                     var startId = types[i].id;
45110                     var count = 1;
45111                     while (i + count < length_4 && types[i + count].id === startId + count) {
45112                         count++;
45113                     }
45114                     if (result.length) {
45115                         result += ",";
45116                     }
45117                     result += startId;
45118                     if (count > 1) {
45119                         result += ":" + count;
45120                     }
45121                     i += count;
45122                 }
45123             }
45124             return result;
45125         }
45126         // This function is used to propagate certain flags when creating new object type references and union types.
45127         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
45128         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
45129         // that care about the presence of such types at arbitrary depth in a containing type.
45130         function getPropagatingFlagsOfTypes(types, excludeKinds) {
45131             var result = 0;
45132             for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
45133                 var type = types_8[_i];
45134                 if (!(type.flags & excludeKinds)) {
45135                     result |= ts.getObjectFlags(type);
45136                 }
45137             }
45138             return result & 3670016 /* PropagatingFlags */;
45139         }
45140         function createTypeReference(target, typeArguments) {
45141             var id = getTypeListId(typeArguments);
45142             var type = target.instantiations.get(id);
45143             if (!type) {
45144                 type = createObjectType(4 /* Reference */, target.symbol);
45145                 target.instantiations.set(id, type);
45146                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
45147                 type.target = target;
45148                 type.resolvedTypeArguments = typeArguments;
45149             }
45150             return type;
45151         }
45152         function cloneTypeReference(source) {
45153             var type = createType(source.flags);
45154             type.symbol = source.symbol;
45155             type.objectFlags = source.objectFlags;
45156             type.target = source.target;
45157             type.resolvedTypeArguments = source.resolvedTypeArguments;
45158             return type;
45159         }
45160         function createDeferredTypeReference(target, node, mapper) {
45161             var aliasSymbol = getAliasSymbolForTypeNode(node);
45162             var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
45163             var type = createObjectType(4 /* Reference */, target.symbol);
45164             type.target = target;
45165             type.node = node;
45166             type.mapper = mapper;
45167             type.aliasSymbol = aliasSymbol;
45168             type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
45169             return type;
45170         }
45171         function getTypeArguments(type) {
45172             var _a, _b;
45173             if (!type.resolvedTypeArguments) {
45174                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
45175                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
45176                 }
45177                 var node = type.node;
45178                 var typeArguments = !node ? ts.emptyArray :
45179                     node.kind === 169 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
45180                         node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
45181                             ts.map(node.elementTypes, getTypeFromTypeNode);
45182                 if (popTypeResolution()) {
45183                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
45184                 }
45185                 else {
45186                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
45187                     error(type.node || currentNode, type.target.symbol
45188                         ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves
45189                         : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
45190                 }
45191             }
45192             return type.resolvedTypeArguments;
45193         }
45194         function getTypeReferenceArity(type) {
45195             return ts.length(type.target.typeParameters);
45196         }
45197         /**
45198          * Get type from type-reference that reference to class or interface
45199          */
45200         function getTypeFromClassOrInterfaceReference(node, symbol) {
45201             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
45202             var typeParameters = type.localTypeParameters;
45203             if (typeParameters) {
45204                 var numTypeArguments = ts.length(node.typeArguments);
45205                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45206                 var isJs = ts.isInJSFile(node);
45207                 var isJsImplicitAny = !noImplicitAny && isJs;
45208                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
45209                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
45210                     var diag = minTypeArgumentCount === typeParameters.length ?
45211                         missingAugmentsTag ?
45212                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
45213                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45214                         missingAugmentsTag ?
45215                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
45216                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
45217                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
45218                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
45219                     if (!isJs) {
45220                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
45221                         return errorType;
45222                     }
45223                 }
45224                 if (node.kind === 169 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
45225                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
45226                 }
45227                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
45228                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
45229                 // of the class or interface.
45230                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
45231                 return createTypeReference(type, typeArguments);
45232             }
45233             return checkNoTypeArguments(node, symbol) ? type : errorType;
45234         }
45235         function getTypeAliasInstantiation(symbol, typeArguments) {
45236             var type = getDeclaredTypeOfSymbol(symbol);
45237             var links = getSymbolLinks(symbol);
45238             var typeParameters = links.typeParameters;
45239             var id = getTypeListId(typeArguments);
45240             var instantiation = links.instantiations.get(id);
45241             if (!instantiation) {
45242                 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
45243             }
45244             return instantiation;
45245         }
45246         /**
45247          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
45248          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
45249          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
45250          */
45251         function getTypeFromTypeAliasReference(node, symbol) {
45252             var type = getDeclaredTypeOfSymbol(symbol);
45253             var typeParameters = getSymbolLinks(symbol).typeParameters;
45254             if (typeParameters) {
45255                 var numTypeArguments = ts.length(node.typeArguments);
45256                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45257                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
45258                     error(node, minTypeArgumentCount === typeParameters.length ?
45259                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45260                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
45261                     return errorType;
45262                 }
45263                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
45264             }
45265             return checkNoTypeArguments(node, symbol) ? type : errorType;
45266         }
45267         function getTypeReferenceName(node) {
45268             switch (node.kind) {
45269                 case 169 /* TypeReference */:
45270                     return node.typeName;
45271                 case 216 /* ExpressionWithTypeArguments */:
45272                     // We only support expressions that are simple qualified names. For other
45273                     // expressions this produces undefined.
45274                     var expr = node.expression;
45275                     if (ts.isEntityNameExpression(expr)) {
45276                         return expr;
45277                     }
45278                 // fall through;
45279             }
45280             return undefined;
45281         }
45282         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
45283             if (!typeReferenceName) {
45284                 return unknownSymbol;
45285             }
45286             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
45287         }
45288         function getTypeReferenceType(node, symbol) {
45289             if (symbol === unknownSymbol) {
45290                 return errorType;
45291             }
45292             symbol = getExpandoSymbol(symbol) || symbol;
45293             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
45294                 return getTypeFromClassOrInterfaceReference(node, symbol);
45295             }
45296             if (symbol.flags & 524288 /* TypeAlias */) {
45297                 return getTypeFromTypeAliasReference(node, symbol);
45298             }
45299             // Get type from reference to named type that cannot be generic (enum or type parameter)
45300             var res = tryGetDeclaredTypeOfSymbol(symbol);
45301             if (res) {
45302                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
45303             }
45304             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
45305                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
45306                 if (jsdocType) {
45307                     return jsdocType;
45308                 }
45309                 else {
45310                     // Resolve the type reference as a Type for the purpose of reporting errors.
45311                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
45312                     return getTypeOfSymbol(symbol);
45313                 }
45314             }
45315             return errorType;
45316         }
45317         /**
45318          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
45319          * Note: If the value is imported from commonjs, it should really be an alias,
45320          * but this function's special-case code fakes alias resolution as well.
45321          */
45322         function getTypeFromJSDocValueReference(node, symbol) {
45323             var links = getNodeLinks(node);
45324             if (!links.resolvedJSDocType) {
45325                 var valueType = getTypeOfSymbol(symbol);
45326                 var typeType = valueType;
45327                 if (symbol.valueDeclaration) {
45328                     var decl = ts.getRootDeclaration(symbol.valueDeclaration);
45329                     var isRequireAlias = false;
45330                     if (ts.isVariableDeclaration(decl) && decl.initializer) {
45331                         var expr = decl.initializer;
45332                         // skip past entity names, eg `require("x").a.b.c`
45333                         while (ts.isPropertyAccessExpression(expr)) {
45334                             expr = expr.expression;
45335                         }
45336                         isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol;
45337                     }
45338                     var isImportTypeWithQualifier = node.kind === 188 /* ImportType */ && node.qualifier;
45339                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
45340                     if (valueType.symbol && (isRequireAlias || isImportTypeWithQualifier)) {
45341                         typeType = getTypeReferenceType(node, valueType.symbol);
45342                     }
45343                 }
45344                 links.resolvedJSDocType = typeType;
45345             }
45346             return links.resolvedJSDocType;
45347         }
45348         function getSubstitutionType(baseType, substitute) {
45349             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
45350                 return baseType;
45351             }
45352             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
45353             var cached = substitutionTypes.get(id);
45354             if (cached) {
45355                 return cached;
45356             }
45357             var result = createType(33554432 /* Substitution */);
45358             result.baseType = baseType;
45359             result.substitute = substitute;
45360             substitutionTypes.set(id, result);
45361             return result;
45362         }
45363         function isUnaryTupleTypeNode(node) {
45364             return node.kind === 175 /* TupleType */ && node.elementTypes.length === 1;
45365         }
45366         function getImpliedConstraint(type, checkNode, extendsNode) {
45367             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
45368                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
45369                     undefined;
45370         }
45371         function getConditionalFlowTypeOfType(type, node) {
45372             var constraints;
45373             while (node && !ts.isStatement(node) && node.kind !== 303 /* JSDocComment */) {
45374                 var parent = node.parent;
45375                 if (parent.kind === 180 /* ConditionalType */ && node === parent.trueType) {
45376                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
45377                     if (constraint) {
45378                         constraints = ts.append(constraints, constraint);
45379                     }
45380                 }
45381                 node = parent;
45382             }
45383             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
45384         }
45385         function isJSDocTypeReference(node) {
45386             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 169 /* TypeReference */ || node.kind === 188 /* ImportType */);
45387         }
45388         function checkNoTypeArguments(node, symbol) {
45389             if (node.typeArguments) {
45390                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
45391                 return false;
45392             }
45393             return true;
45394         }
45395         function getIntendedTypeFromJSDocTypeReference(node) {
45396             if (ts.isIdentifier(node.typeName)) {
45397                 var typeArgs = node.typeArguments;
45398                 switch (node.typeName.escapedText) {
45399                     case "String":
45400                         checkNoTypeArguments(node);
45401                         return stringType;
45402                     case "Number":
45403                         checkNoTypeArguments(node);
45404                         return numberType;
45405                     case "Boolean":
45406                         checkNoTypeArguments(node);
45407                         return booleanType;
45408                     case "Void":
45409                         checkNoTypeArguments(node);
45410                         return voidType;
45411                     case "Undefined":
45412                         checkNoTypeArguments(node);
45413                         return undefinedType;
45414                     case "Null":
45415                         checkNoTypeArguments(node);
45416                         return nullType;
45417                     case "Function":
45418                     case "function":
45419                         checkNoTypeArguments(node);
45420                         return globalFunctionType;
45421                     case "array":
45422                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
45423                     case "promise":
45424                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
45425                     case "Object":
45426                         if (typeArgs && typeArgs.length === 2) {
45427                             if (ts.isJSDocIndexSignature(node)) {
45428                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
45429                                 var target = getTypeFromTypeNode(typeArgs[1]);
45430                                 var index = createIndexInfo(target, /*isReadonly*/ false);
45431                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
45432                             }
45433                             return anyType;
45434                         }
45435                         checkNoTypeArguments(node);
45436                         return !noImplicitAny ? anyType : undefined;
45437                 }
45438             }
45439         }
45440         function getTypeFromJSDocNullableTypeNode(node) {
45441             var type = getTypeFromTypeNode(node.type);
45442             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
45443         }
45444         function getTypeFromTypeReference(node) {
45445             var links = getNodeLinks(node);
45446             if (!links.resolvedType) {
45447                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
45448                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
45449                     links.resolvedSymbol = unknownSymbol;
45450                     return links.resolvedType = checkExpressionCached(node.parent.expression);
45451                 }
45452                 var symbol = void 0;
45453                 var type = void 0;
45454                 var meaning = 788968 /* Type */;
45455                 if (isJSDocTypeReference(node)) {
45456                     type = getIntendedTypeFromJSDocTypeReference(node);
45457                     if (!type) {
45458                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
45459                         if (symbol === unknownSymbol) {
45460                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
45461                         }
45462                         else {
45463                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
45464                         }
45465                         type = getTypeReferenceType(node, symbol);
45466                     }
45467                 }
45468                 if (!type) {
45469                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
45470                     type = getTypeReferenceType(node, symbol);
45471                 }
45472                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
45473                 // type reference in checkTypeReferenceNode.
45474                 links.resolvedSymbol = symbol;
45475                 links.resolvedType = type;
45476             }
45477             return links.resolvedType;
45478         }
45479         function typeArgumentsFromTypeReferenceNode(node) {
45480             return ts.map(node.typeArguments, getTypeFromTypeNode);
45481         }
45482         function getTypeFromTypeQueryNode(node) {
45483             var links = getNodeLinks(node);
45484             if (!links.resolvedType) {
45485                 // TypeScript 1.0 spec (April 2014): 3.6.3
45486                 // The expression is processed as an identifier expression (section 4.3)
45487                 // or property access expression(section 4.10),
45488                 // the widened type(section 3.9) of which becomes the result.
45489                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
45490             }
45491             return links.resolvedType;
45492         }
45493         function getTypeOfGlobalSymbol(symbol, arity) {
45494             function getTypeDeclaration(symbol) {
45495                 var declarations = symbol.declarations;
45496                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
45497                     var declaration = declarations_3[_i];
45498                     switch (declaration.kind) {
45499                         case 245 /* ClassDeclaration */:
45500                         case 246 /* InterfaceDeclaration */:
45501                         case 248 /* EnumDeclaration */:
45502                             return declaration;
45503                     }
45504                 }
45505             }
45506             if (!symbol) {
45507                 return arity ? emptyGenericType : emptyObjectType;
45508             }
45509             var type = getDeclaredTypeOfSymbol(symbol);
45510             if (!(type.flags & 524288 /* Object */)) {
45511                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
45512                 return arity ? emptyGenericType : emptyObjectType;
45513             }
45514             if (ts.length(type.typeParameters) !== arity) {
45515                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
45516                 return arity ? emptyGenericType : emptyObjectType;
45517             }
45518             return type;
45519         }
45520         function getGlobalValueSymbol(name, reportErrors) {
45521             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
45522         }
45523         function getGlobalTypeSymbol(name, reportErrors) {
45524             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
45525         }
45526         function getGlobalSymbol(name, meaning, diagnostic) {
45527             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
45528             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
45529         }
45530         function getGlobalType(name, arity, reportErrors) {
45531             var symbol = getGlobalTypeSymbol(name, reportErrors);
45532             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
45533         }
45534         function getGlobalTypedPropertyDescriptorType() {
45535             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
45536         }
45537         function getGlobalTemplateStringsArrayType() {
45538             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45539         }
45540         function getGlobalImportMetaType() {
45541             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45542         }
45543         function getGlobalESSymbolConstructorSymbol(reportErrors) {
45544             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
45545         }
45546         function getGlobalESSymbolType(reportErrors) {
45547             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
45548         }
45549         function getGlobalPromiseType(reportErrors) {
45550             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
45551         }
45552         function getGlobalPromiseLikeType(reportErrors) {
45553             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
45554         }
45555         function getGlobalPromiseConstructorSymbol(reportErrors) {
45556             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
45557         }
45558         function getGlobalPromiseConstructorLikeType(reportErrors) {
45559             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
45560         }
45561         function getGlobalAsyncIterableType(reportErrors) {
45562             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45563         }
45564         function getGlobalAsyncIteratorType(reportErrors) {
45565             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45566         }
45567         function getGlobalAsyncIterableIteratorType(reportErrors) {
45568             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45569         }
45570         function getGlobalAsyncGeneratorType(reportErrors) {
45571             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45572         }
45573         function getGlobalIterableType(reportErrors) {
45574             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45575         }
45576         function getGlobalIteratorType(reportErrors) {
45577             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45578         }
45579         function getGlobalIterableIteratorType(reportErrors) {
45580             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45581         }
45582         function getGlobalGeneratorType(reportErrors) {
45583             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45584         }
45585         function getGlobalIteratorYieldResultType(reportErrors) {
45586             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45587         }
45588         function getGlobalIteratorReturnResultType(reportErrors) {
45589             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45590         }
45591         function getGlobalTypeOrUndefined(name, arity) {
45592             if (arity === void 0) { arity = 0; }
45593             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
45594             return symbol && getTypeOfGlobalSymbol(symbol, arity);
45595         }
45596         function getGlobalExtractSymbol() {
45597             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45598         }
45599         function getGlobalOmitSymbol() {
45600             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45601         }
45602         function getGlobalBigIntType(reportErrors) {
45603             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
45604         }
45605         /**
45606          * Instantiates a global type that is generic with some element type, and returns that instantiation.
45607          */
45608         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
45609             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
45610         }
45611         function createTypedPropertyDescriptorType(propertyType) {
45612             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
45613         }
45614         function createIterableType(iteratedType) {
45615             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
45616         }
45617         function createArrayType(elementType, readonly) {
45618             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
45619         }
45620         function getArrayOrTupleTargetType(node) {
45621             var readonly = isReadonlyTypeOperator(node.parent);
45622             if (node.kind === 174 /* ArrayType */ || node.elementTypes.length === 1 && node.elementTypes[0].kind === 177 /* RestType */) {
45623                 return readonly ? globalReadonlyArrayType : globalArrayType;
45624             }
45625             var lastElement = ts.lastOrUndefined(node.elementTypes);
45626             var restElement = lastElement && lastElement.kind === 177 /* RestType */ ? lastElement : undefined;
45627             var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 176 /* OptionalType */ && n !== restElement; }) + 1;
45628             return getTupleTypeOfArity(node.elementTypes.length, minLength, !!restElement, readonly, /*associatedNames*/ undefined);
45629         }
45630         // Return true if the given type reference node is directly aliased or if it needs to be deferred
45631         // because it is possibly contained in a circular chain of eagerly resolved types.
45632         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
45633             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 174 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
45634                 node.kind === 175 /* TupleType */ ? ts.some(node.elementTypes, mayResolveTypeAlias) :
45635                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
45636         }
45637         // Return true when the given node is transitively contained in type constructs that eagerly
45638         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
45639         // of type aliases are eagerly resolved.
45640         function isResolvedByTypeAlias(node) {
45641             var parent = node.parent;
45642             switch (parent.kind) {
45643                 case 182 /* ParenthesizedType */:
45644                 case 169 /* TypeReference */:
45645                 case 178 /* UnionType */:
45646                 case 179 /* IntersectionType */:
45647                 case 185 /* IndexedAccessType */:
45648                 case 180 /* ConditionalType */:
45649                 case 184 /* TypeOperator */:
45650                 case 174 /* ArrayType */:
45651                 case 175 /* TupleType */:
45652                     return isResolvedByTypeAlias(parent);
45653                 case 247 /* TypeAliasDeclaration */:
45654                     return true;
45655             }
45656             return false;
45657         }
45658         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
45659         // of a type alias.
45660         function mayResolveTypeAlias(node) {
45661             switch (node.kind) {
45662                 case 169 /* TypeReference */:
45663                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
45664                 case 172 /* TypeQuery */:
45665                     return true;
45666                 case 184 /* TypeOperator */:
45667                     return node.operator !== 147 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
45668                 case 182 /* ParenthesizedType */:
45669                 case 176 /* OptionalType */:
45670                 case 299 /* JSDocOptionalType */:
45671                 case 297 /* JSDocNullableType */:
45672                 case 298 /* JSDocNonNullableType */:
45673                 case 294 /* JSDocTypeExpression */:
45674                     return mayResolveTypeAlias(node.type);
45675                 case 177 /* RestType */:
45676                     return node.type.kind !== 174 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
45677                 case 178 /* UnionType */:
45678                 case 179 /* IntersectionType */:
45679                     return ts.some(node.types, mayResolveTypeAlias);
45680                 case 185 /* IndexedAccessType */:
45681                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
45682                 case 180 /* ConditionalType */:
45683                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
45684                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
45685             }
45686             return false;
45687         }
45688         function getTypeFromArrayOrTupleTypeNode(node) {
45689             var links = getNodeLinks(node);
45690             if (!links.resolvedType) {
45691                 var target = getArrayOrTupleTargetType(node);
45692                 if (target === emptyGenericType) {
45693                     links.resolvedType = emptyObjectType;
45694                 }
45695                 else if (isDeferredTypeReferenceNode(node)) {
45696                     links.resolvedType = node.kind === 175 /* TupleType */ && node.elementTypes.length === 0 ? target :
45697                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
45698                 }
45699                 else {
45700                     var elementTypes = node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode);
45701                     links.resolvedType = createTypeReference(target, elementTypes);
45702                 }
45703             }
45704             return links.resolvedType;
45705         }
45706         function isReadonlyTypeOperator(node) {
45707             return ts.isTypeOperatorNode(node) && node.operator === 138 /* ReadonlyKeyword */;
45708         }
45709         // We represent tuple types as type references to synthesized generic interface types created by
45710         // this function. The types are of the form:
45711         //
45712         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
45713         //
45714         // Note that the generic type created by this function has no symbol associated with it. The same
45715         // is true for each of the synthesized type parameters.
45716         function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45717             var typeParameters;
45718             var properties = [];
45719             var maxLength = hasRestElement ? arity - 1 : arity;
45720             if (arity) {
45721                 typeParameters = new Array(arity);
45722                 for (var i = 0; i < arity; i++) {
45723                     var typeParameter = typeParameters[i] = createTypeParameter();
45724                     if (i < maxLength) {
45725                         var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
45726                         property.type = typeParameter;
45727                         properties.push(property);
45728                     }
45729                 }
45730             }
45731             var literalTypes = [];
45732             for (var i = minLength; i <= maxLength; i++)
45733                 literalTypes.push(getLiteralType(i));
45734             var lengthSymbol = createSymbol(4 /* Property */, "length");
45735             lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
45736             properties.push(lengthSymbol);
45737             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
45738             type.typeParameters = typeParameters;
45739             type.outerTypeParameters = undefined;
45740             type.localTypeParameters = typeParameters;
45741             type.instantiations = ts.createMap();
45742             type.instantiations.set(getTypeListId(type.typeParameters), type);
45743             type.target = type;
45744             type.resolvedTypeArguments = type.typeParameters;
45745             type.thisType = createTypeParameter();
45746             type.thisType.isThisType = true;
45747             type.thisType.constraint = type;
45748             type.declaredProperties = properties;
45749             type.declaredCallSignatures = ts.emptyArray;
45750             type.declaredConstructSignatures = ts.emptyArray;
45751             type.declaredStringIndexInfo = undefined;
45752             type.declaredNumberIndexInfo = undefined;
45753             type.minLength = minLength;
45754             type.hasRestElement = hasRestElement;
45755             type.readonly = readonly;
45756             type.associatedNames = associatedNames;
45757             return type;
45758         }
45759         function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45760             var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
45761             var type = tupleTypes.get(key);
45762             if (!type) {
45763                 tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
45764             }
45765             return type;
45766         }
45767         function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
45768             if (minLength === void 0) { minLength = elementTypes.length; }
45769             if (hasRestElement === void 0) { hasRestElement = false; }
45770             if (readonly === void 0) { readonly = false; }
45771             var arity = elementTypes.length;
45772             if (arity === 1 && hasRestElement) {
45773                 return createArrayType(elementTypes[0], readonly);
45774             }
45775             var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
45776             return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
45777         }
45778         function sliceTupleType(type, index) {
45779             var tuple = type.target;
45780             if (tuple.hasRestElement) {
45781                 // don't slice off rest element
45782                 index = Math.min(index, getTypeReferenceArity(type) - 1);
45783             }
45784             return createTupleType(getTypeArguments(type).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
45785         }
45786         function getTypeFromOptionalTypeNode(node) {
45787             var type = getTypeFromTypeNode(node.type);
45788             return strictNullChecks ? getOptionalType(type) : type;
45789         }
45790         function getTypeId(type) {
45791             return type.id;
45792         }
45793         function containsType(types, type) {
45794             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
45795         }
45796         function insertType(types, type) {
45797             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
45798             if (index < 0) {
45799                 types.splice(~index, 0, type);
45800                 return true;
45801             }
45802             return false;
45803         }
45804         function addTypeToUnion(typeSet, includes, type) {
45805             var flags = type.flags;
45806             if (flags & 1048576 /* Union */) {
45807                 return addTypesToUnion(typeSet, includes, type.types);
45808             }
45809             // We ignore 'never' types in unions
45810             if (!(flags & 131072 /* Never */)) {
45811                 includes |= flags & 71041023 /* IncludesMask */;
45812                 if (flags & 66846720 /* StructuredOrInstantiable */)
45813                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
45814                 if (type === wildcardType)
45815                     includes |= 8388608 /* IncludesWildcard */;
45816                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
45817                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
45818                         includes |= 4194304 /* IncludesNonWideningType */;
45819                 }
45820                 else {
45821                     var len = typeSet.length;
45822                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
45823                     if (index < 0) {
45824                         typeSet.splice(~index, 0, type);
45825                     }
45826                 }
45827             }
45828             return includes;
45829         }
45830         // Add the given types to the given type set. Order is preserved, duplicates are removed,
45831         // and nested types of the given kind are flattened into the set.
45832         function addTypesToUnion(typeSet, includes, types) {
45833             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
45834                 var type = types_9[_i];
45835                 includes = addTypeToUnion(typeSet, includes, type);
45836             }
45837             return includes;
45838         }
45839         function isSetOfLiteralsFromSameEnum(types) {
45840             var first = types[0];
45841             if (first.flags & 1024 /* EnumLiteral */) {
45842                 var firstEnum = getParentOfSymbol(first.symbol);
45843                 for (var i = 1; i < types.length; i++) {
45844                     var other = types[i];
45845                     if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
45846                         return false;
45847                     }
45848                 }
45849                 return true;
45850             }
45851             return false;
45852         }
45853         function removeSubtypes(types, primitivesOnly) {
45854             var len = types.length;
45855             if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
45856                 return true;
45857             }
45858             var i = len;
45859             var count = 0;
45860             while (i > 0) {
45861                 i--;
45862                 var source = types[i];
45863                 for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
45864                     var target = types_10[_i];
45865                     if (source !== target) {
45866                         if (count === 100000) {
45867                             // After 100000 subtype checks we estimate the remaining amount of work by assuming the
45868                             // same ratio of checks per element. If the estimated number of remaining type checks is
45869                             // greater than an upper limit we deem the union type too complex to represent. The
45870                             // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
45871                             // caps union types at 5000 unique literal types and 1000 unique object types.
45872                             var estimatedCount = (count / (len - i)) * len;
45873                             if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
45874                                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
45875                                 return false;
45876                             }
45877                         }
45878                         count++;
45879                         if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
45880                             !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
45881                             isTypeDerivedFrom(source, target))) {
45882                             ts.orderedRemoveItemAt(types, i);
45883                             break;
45884                         }
45885                     }
45886                 }
45887             }
45888             return true;
45889         }
45890         function removeRedundantLiteralTypes(types, includes) {
45891             var i = types.length;
45892             while (i > 0) {
45893                 i--;
45894                 var t = types[i];
45895                 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
45896                     t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
45897                     t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
45898                     t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
45899                     isFreshLiteralType(t) && containsType(types, t.regularType);
45900                 if (remove) {
45901                     ts.orderedRemoveItemAt(types, i);
45902                 }
45903             }
45904         }
45905         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
45906         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
45907         // of other types. Subtype reduction is expensive for large union types and is possible only when union
45908         // types are known not to circularly reference themselves (as is the case with union types created by
45909         // expression constructs such as array literals and the || and ?: operators). Named types can
45910         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
45911         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
45912         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
45913             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
45914             if (types.length === 0) {
45915                 return neverType;
45916             }
45917             if (types.length === 1) {
45918                 return types[0];
45919             }
45920             var typeSet = [];
45921             var includes = addTypesToUnion(typeSet, 0, types);
45922             if (unionReduction !== 0 /* None */) {
45923                 if (includes & 3 /* AnyOrUnknown */) {
45924                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
45925                 }
45926                 switch (unionReduction) {
45927                     case 1 /* Literal */:
45928                         if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
45929                             removeRedundantLiteralTypes(typeSet, includes);
45930                         }
45931                         break;
45932                     case 2 /* Subtype */:
45933                         if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
45934                             return errorType;
45935                         }
45936                         break;
45937                 }
45938                 if (typeSet.length === 0) {
45939                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
45940                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
45941                             neverType;
45942                 }
45943             }
45944             var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
45945                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
45946             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
45947         }
45948         function getUnionTypePredicate(signatures) {
45949             var first;
45950             var types = [];
45951             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
45952                 var sig = signatures_6[_i];
45953                 var pred = getTypePredicateOfSignature(sig);
45954                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
45955                     continue;
45956                 }
45957                 if (first) {
45958                     if (!typePredicateKindsMatch(first, pred)) {
45959                         // No common type predicate.
45960                         return undefined;
45961                     }
45962                 }
45963                 else {
45964                     first = pred;
45965                 }
45966                 types.push(pred.type);
45967             }
45968             if (!first) {
45969                 // No union signatures had a type predicate.
45970                 return undefined;
45971             }
45972             var unionType = getUnionType(types);
45973             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
45974         }
45975         function typePredicateKindsMatch(a, b) {
45976             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
45977         }
45978         // This function assumes the constituent type list is sorted and deduplicated.
45979         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
45980             if (types.length === 0) {
45981                 return neverType;
45982             }
45983             if (types.length === 1) {
45984                 return types[0];
45985             }
45986             var id = getTypeListId(types);
45987             var type = unionTypes.get(id);
45988             if (!type) {
45989                 type = createType(1048576 /* Union */);
45990                 unionTypes.set(id, type);
45991                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
45992                 type.types = types;
45993                 /*
45994                 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
45995                 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
45996                 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
45997                 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
45998                 */
45999                 type.aliasSymbol = aliasSymbol;
46000                 type.aliasTypeArguments = aliasTypeArguments;
46001             }
46002             return type;
46003         }
46004         function getTypeFromUnionTypeNode(node) {
46005             var links = getNodeLinks(node);
46006             if (!links.resolvedType) {
46007                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46008                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46009             }
46010             return links.resolvedType;
46011         }
46012         function addTypeToIntersection(typeSet, includes, type) {
46013             var flags = type.flags;
46014             if (flags & 2097152 /* Intersection */) {
46015                 return addTypesToIntersection(typeSet, includes, type.types);
46016             }
46017             if (isEmptyAnonymousObjectType(type)) {
46018                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
46019                     includes |= 16777216 /* IncludesEmptyObject */;
46020                     typeSet.set(type.id.toString(), type);
46021                 }
46022             }
46023             else {
46024                 if (flags & 3 /* AnyOrUnknown */) {
46025                     if (type === wildcardType)
46026                         includes |= 8388608 /* IncludesWildcard */;
46027                 }
46028                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
46029                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
46030                         // We have seen two distinct unit types which means we should reduce to an
46031                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
46032                         includes |= 67108864 /* NonPrimitive */;
46033                     }
46034                     typeSet.set(type.id.toString(), type);
46035                 }
46036                 includes |= flags & 71041023 /* IncludesMask */;
46037             }
46038             return includes;
46039         }
46040         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
46041         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
46042         function addTypesToIntersection(typeSet, includes, types) {
46043             for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
46044                 var type = types_11[_i];
46045                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
46046             }
46047             return includes;
46048         }
46049         function removeRedundantPrimitiveTypes(types, includes) {
46050             var i = types.length;
46051             while (i > 0) {
46052                 i--;
46053                 var t = types[i];
46054                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46055                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46056                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46057                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
46058                 if (remove) {
46059                     ts.orderedRemoveItemAt(types, i);
46060                 }
46061             }
46062         }
46063         // Check that the given type has a match in every union. A given type is matched by
46064         // an identical type, and a literal type is additionally matched by its corresponding
46065         // primitive type.
46066         function eachUnionContains(unionTypes, type) {
46067             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
46068                 var u = unionTypes_1[_i];
46069                 if (!containsType(u.types, type)) {
46070                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
46071                         type.flags & 256 /* NumberLiteral */ ? numberType :
46072                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
46073                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
46074                                     undefined;
46075                     if (!primitive || !containsType(u.types, primitive)) {
46076                         return false;
46077                     }
46078                 }
46079             }
46080             return true;
46081         }
46082         function extractIrreducible(types, flag) {
46083             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
46084                 for (var i = 0; i < types.length; i++) {
46085                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
46086                 }
46087                 return true;
46088             }
46089             return false;
46090         }
46091         // If the given list of types contains more than one union of primitive types, replace the
46092         // first with a union containing an intersection of those primitive types, then remove the
46093         // other unions and return true. Otherwise, do nothing and return false.
46094         function intersectUnionsOfPrimitiveTypes(types) {
46095             var unionTypes;
46096             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
46097             if (index < 0) {
46098                 return false;
46099             }
46100             var i = index + 1;
46101             // Remove all but the first union of primitive types and collect them in
46102             // the unionTypes array.
46103             while (i < types.length) {
46104                 var t = types[i];
46105                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
46106                     (unionTypes || (unionTypes = [types[index]])).push(t);
46107                     ts.orderedRemoveItemAt(types, i);
46108                 }
46109                 else {
46110                     i++;
46111                 }
46112             }
46113             // Return false if there was only one union of primitive types
46114             if (!unionTypes) {
46115                 return false;
46116             }
46117             // We have more than one union of primitive types, now intersect them. For each
46118             // type in each union we check if the type is matched in every union and if so
46119             // we include it in the result.
46120             var checked = [];
46121             var result = [];
46122             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
46123                 var u = unionTypes_2[_i];
46124                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
46125                     var t = _b[_a];
46126                     if (insertType(checked, t)) {
46127                         if (eachUnionContains(unionTypes, t)) {
46128                             insertType(result, t);
46129                         }
46130                     }
46131                 }
46132             }
46133             // Finally replace the first union with the result
46134             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
46135             return true;
46136         }
46137         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46138             var result = createType(2097152 /* Intersection */);
46139             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
46140             result.types = types;
46141             result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
46142             result.aliasTypeArguments = aliasTypeArguments;
46143             return result;
46144         }
46145         // We normalize combinations of intersection and union types based on the distributive property of the '&'
46146         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
46147         // types with union type constituents into equivalent union types with intersection type constituents and
46148         // effectively ensure that union types are always at the top level in type representations.
46149         //
46150         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
46151         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
46152         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
46153         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
46154         // for intersections of types with signatures can be deterministic.
46155         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46156             var typeMembershipMap = ts.createMap();
46157             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
46158             var typeSet = ts.arrayFrom(typeMembershipMap.values());
46159             // An intersection type is considered empty if it contains
46160             // the type never, or
46161             // more than one unit type or,
46162             // an object type and a nullable type (null or undefined), or
46163             // a string-like type and a type known to be non-string-like, or
46164             // a number-like type and a type known to be non-number-like, or
46165             // a symbol-like type and a type known to be non-symbol-like, or
46166             // a void-like type and a type known to be non-void-like, or
46167             // a non-primitive type and a type known to be primitive.
46168             if (includes & 131072 /* Never */ ||
46169                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
46170                 includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
46171                 includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
46172                 includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
46173                 includes & 2112 /* BigIntLike */ && includes & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
46174                 includes & 12288 /* ESSymbolLike */ && includes & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
46175                 includes & 49152 /* VoidLike */ && includes & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
46176                 return neverType;
46177             }
46178             if (includes & 1 /* Any */) {
46179                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
46180             }
46181             if (!strictNullChecks && includes & 98304 /* Nullable */) {
46182                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
46183             }
46184             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46185                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46186                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46187                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
46188                 removeRedundantPrimitiveTypes(typeSet, includes);
46189             }
46190             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
46191                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
46192             }
46193             if (typeSet.length === 0) {
46194                 return unknownType;
46195             }
46196             if (typeSet.length === 1) {
46197                 return typeSet[0];
46198             }
46199             var id = getTypeListId(typeSet);
46200             var result = intersectionTypes.get(id);
46201             if (!result) {
46202                 if (includes & 1048576 /* Union */) {
46203                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
46204                         // When the intersection creates a reduced set (which might mean that *all* union types have
46205                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
46206                         // reduced we'll never reduce again, so this occurs at most once.
46207                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46208                     }
46209                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
46210                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46211                     }
46212                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
46213                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46214                     }
46215                     else {
46216                         // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
46217                         // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
46218                         // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
46219                         var size = ts.reduceLeft(typeSet, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : 1); }, 1);
46220                         if (size >= 100000) {
46221                             error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
46222                             return errorType;
46223                         }
46224                         var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
46225                         var unionType = typeSet[unionIndex_1];
46226                         result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46227                     }
46228                 }
46229                 else {
46230                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46231                 }
46232                 intersectionTypes.set(id, result);
46233             }
46234             return result;
46235         }
46236         function getTypeFromIntersectionTypeNode(node) {
46237             var links = getNodeLinks(node);
46238             if (!links.resolvedType) {
46239                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46240                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46241             }
46242             return links.resolvedType;
46243         }
46244         function createIndexType(type, stringsOnly) {
46245             var result = createType(4194304 /* Index */);
46246             result.type = type;
46247             result.stringsOnly = stringsOnly;
46248             return result;
46249         }
46250         function getIndexTypeForGenericType(type, stringsOnly) {
46251             return stringsOnly ?
46252                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
46253                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
46254         }
46255         function getLiteralTypeFromPropertyName(name) {
46256             if (ts.isPrivateIdentifier(name)) {
46257                 return neverType;
46258             }
46259             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
46260                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
46261         }
46262         function getBigIntLiteralType(node) {
46263             return getLiteralType({
46264                 negative: false,
46265                 base10Value: ts.parsePseudoBigInt(node.text)
46266             });
46267         }
46268         function getLiteralTypeFromProperty(prop, include) {
46269             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
46270                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
46271                 if (!type && !ts.isKnownSymbol(prop)) {
46272                     if (prop.escapedName === "default" /* Default */) {
46273                         type = getLiteralType("default");
46274                     }
46275                     else {
46276                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
46277                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
46278                     }
46279                 }
46280                 if (type && type.flags & include) {
46281                     return type;
46282                 }
46283             }
46284             return neverType;
46285         }
46286         function getLiteralTypeFromProperties(type, include) {
46287             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
46288         }
46289         function getNonEnumNumberIndexInfo(type) {
46290             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
46291             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
46292         }
46293         function getIndexType(type, stringsOnly, noIndexSignatures) {
46294             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
46295             type = getReducedType(type);
46296             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46297                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46298                     maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
46299                         ts.getObjectFlags(type) & 32 /* Mapped */ ? filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }) :
46300                             type === wildcardType ? wildcardType :
46301                                 type.flags & 2 /* Unknown */ ? neverType :
46302                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
46303                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
46304                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
46305                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
46306                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
46307         }
46308         function getExtractStringType(type) {
46309             if (keyofStringsOnly) {
46310                 return type;
46311             }
46312             var extractTypeAlias = getGlobalExtractSymbol();
46313             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
46314         }
46315         function getIndexTypeOrString(type) {
46316             var indexType = getExtractStringType(getIndexType(type));
46317             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
46318         }
46319         function getTypeFromTypeOperatorNode(node) {
46320             var links = getNodeLinks(node);
46321             if (!links.resolvedType) {
46322                 switch (node.operator) {
46323                     case 134 /* KeyOfKeyword */:
46324                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
46325                         break;
46326                     case 147 /* UniqueKeyword */:
46327                         links.resolvedType = node.type.kind === 144 /* SymbolKeyword */
46328                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
46329                             : errorType;
46330                         break;
46331                     case 138 /* ReadonlyKeyword */:
46332                         links.resolvedType = getTypeFromTypeNode(node.type);
46333                         break;
46334                     default:
46335                         throw ts.Debug.assertNever(node.operator);
46336                 }
46337             }
46338             return links.resolvedType;
46339         }
46340         function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments) {
46341             var type = createType(8388608 /* IndexedAccess */);
46342             type.objectType = objectType;
46343             type.indexType = indexType;
46344             type.aliasSymbol = aliasSymbol;
46345             type.aliasTypeArguments = aliasTypeArguments;
46346             return type;
46347         }
46348         /**
46349          * Returns if a type is or consists of a JSLiteral object type
46350          * In addition to objects which are directly literals,
46351          * * unions where every element is a jsliteral
46352          * * intersections where at least one element is a jsliteral
46353          * * and instantiable types constrained to a jsliteral
46354          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
46355          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
46356          */
46357         function isJSLiteralType(type) {
46358             if (noImplicitAny) {
46359                 return false; // Flag is meaningless under `noImplicitAny` mode
46360             }
46361             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
46362                 return true;
46363             }
46364             if (type.flags & 1048576 /* Union */) {
46365                 return ts.every(type.types, isJSLiteralType);
46366             }
46367             if (type.flags & 2097152 /* Intersection */) {
46368                 return ts.some(type.types, isJSLiteralType);
46369             }
46370             if (type.flags & 63176704 /* Instantiable */) {
46371                 return isJSLiteralType(getResolvedBaseConstraint(type));
46372             }
46373             return false;
46374         }
46375         function getPropertyNameFromIndex(indexType, accessNode) {
46376             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46377             return isTypeUsableAsPropertyName(indexType) ?
46378                 getPropertyNameFromType(indexType) :
46379                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
46380                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
46381                     accessNode && ts.isPropertyName(accessNode) ?
46382                         // late bound names are handled in the first branch, so here we only need to handle normal names
46383                         ts.getPropertyNameForPropertyNameNode(accessNode) :
46384                         undefined;
46385         }
46386         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags) {
46387             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46388             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
46389             if (propName !== undefined) {
46390                 var prop = getPropertyOfType(objectType, propName);
46391                 if (prop) {
46392                     if (accessExpression) {
46393                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 104 /* ThisKeyword */);
46394                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
46395                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
46396                             return undefined;
46397                         }
46398                         if (accessFlags & 4 /* CacheSymbol */) {
46399                             getNodeLinks(accessNode).resolvedSymbol = prop;
46400                         }
46401                     }
46402                     var propType = getTypeOfSymbol(prop);
46403                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
46404                         getFlowTypeOfReference(accessExpression, propType) :
46405                         propType;
46406                 }
46407                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
46408                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
46409                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46410                         if (isTupleType(objectType)) {
46411                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
46412                         }
46413                         else {
46414                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46415                         }
46416                     }
46417                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
46418                     return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
46419                 }
46420             }
46421             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
46422                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
46423                     return objectType;
46424                 }
46425                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
46426                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
46427                 if (indexInfo) {
46428                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
46429                         if (accessExpression) {
46430                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
46431                         }
46432                         return undefined;
46433                     }
46434                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46435                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46436                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46437                         return indexInfo.type;
46438                     }
46439                     errorIfWritingToReadonlyIndex(indexInfo);
46440                     return indexInfo.type;
46441                 }
46442                 if (indexType.flags & 131072 /* Never */) {
46443                     return neverType;
46444                 }
46445                 if (isJSLiteralType(objectType)) {
46446                     return anyType;
46447                 }
46448                 if (accessExpression && !isConstEnumObjectType(objectType)) {
46449                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
46450                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46451                     }
46452                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
46453                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
46454                             error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
46455                         }
46456                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
46457                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
46458                         }
46459                         else {
46460                             var suggestion = void 0;
46461                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
46462                                 if (suggestion !== undefined) {
46463                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
46464                                 }
46465                             }
46466                             else {
46467                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
46468                                 if (suggestion_1 !== undefined) {
46469                                     error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion_1);
46470                                 }
46471                                 else {
46472                                     var errorInfo = void 0;
46473                                     if (indexType.flags & 1024 /* EnumLiteral */) {
46474                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
46475                                     }
46476                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
46477                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
46478                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
46479                                     }
46480                                     else if (indexType.flags & 128 /* StringLiteral */) {
46481                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46482                                     }
46483                                     else if (indexType.flags & 256 /* NumberLiteral */) {
46484                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46485                                     }
46486                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
46487                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, typeToString(indexType), typeToString(objectType));
46488                                     }
46489                                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, typeToString(fullIndexType), typeToString(objectType));
46490                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
46491                                 }
46492                             }
46493                         }
46494                     }
46495                     return undefined;
46496                 }
46497             }
46498             if (isJSLiteralType(objectType)) {
46499                 return anyType;
46500             }
46501             if (accessNode) {
46502                 var indexNode = getIndexNodeForAccessExpression(accessNode);
46503                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
46504                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
46505                 }
46506                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
46507                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
46508                 }
46509                 else {
46510                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46511                 }
46512             }
46513             if (isTypeAny(indexType)) {
46514                 return indexType;
46515             }
46516             return undefined;
46517             function errorIfWritingToReadonlyIndex(indexInfo) {
46518                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
46519                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
46520                 }
46521             }
46522         }
46523         function getIndexNodeForAccessExpression(accessNode) {
46524             return accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode.argumentExpression :
46525                 accessNode.kind === 185 /* IndexedAccessType */ ? accessNode.indexType :
46526                     accessNode.kind === 154 /* ComputedPropertyName */ ? accessNode.expression :
46527                         accessNode;
46528         }
46529         function isGenericObjectType(type) {
46530             if (type.flags & 3145728 /* UnionOrIntersection */) {
46531                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
46532                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
46533                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
46534                 }
46535                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
46536             }
46537             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type);
46538         }
46539         function isGenericIndexType(type) {
46540             if (type.flags & 3145728 /* UnionOrIntersection */) {
46541                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
46542                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
46543                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
46544                 }
46545                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
46546             }
46547             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */));
46548         }
46549         function isThisTypeParameter(type) {
46550             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
46551         }
46552         function getSimplifiedType(type, writing) {
46553             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
46554                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
46555                     type;
46556         }
46557         function distributeIndexOverObjectType(objectType, indexType, writing) {
46558             // (T | U)[K] -> T[K] | U[K] (reading)
46559             // (T | U)[K] -> T[K] & U[K] (writing)
46560             // (T & U)[K] -> T[K] & U[K]
46561             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
46562                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
46563                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
46564             }
46565         }
46566         function distributeObjectOverIndexType(objectType, indexType, writing) {
46567             // T[A | B] -> T[A] | T[B] (reading)
46568             // T[A | B] -> T[A] & T[B] (writing)
46569             if (indexType.flags & 1048576 /* Union */) {
46570                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
46571                 return writing ? getIntersectionType(types) : getUnionType(types);
46572             }
46573         }
46574         function unwrapSubstitution(type) {
46575             if (type.flags & 33554432 /* Substitution */) {
46576                 return type.substitute;
46577             }
46578             return type;
46579         }
46580         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
46581         // the type itself if no transformation is possible. The writing flag indicates that the type is
46582         // the target of an assignment.
46583         function getSimplifiedIndexedAccessType(type, writing) {
46584             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
46585             if (type[cache]) {
46586                 return type[cache] === circularConstraintType ? type : type[cache];
46587             }
46588             type[cache] = circularConstraintType;
46589             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
46590             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
46591             var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
46592             var indexType = getSimplifiedType(type.indexType, writing);
46593             // T[A | B] -> T[A] | T[B] (reading)
46594             // T[A | B] -> T[A] & T[B] (writing)
46595             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
46596             if (distributedOverIndex) {
46597                 return type[cache] = distributedOverIndex;
46598             }
46599             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
46600             if (!(indexType.flags & 63176704 /* Instantiable */)) {
46601                 // (T | U)[K] -> T[K] | U[K] (reading)
46602                 // (T | U)[K] -> T[K] & U[K] (writing)
46603                 // (T & U)[K] -> T[K] & U[K]
46604                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
46605                 if (distributedOverObject) {
46606                     return type[cache] = distributedOverObject;
46607                 }
46608             }
46609             // So ultimately (reading):
46610             // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2]
46611             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
46612             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
46613             // construct the type Box<T[X]>.
46614             if (isGenericMappedType(objectType)) {
46615                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
46616             }
46617             return type[cache] = type;
46618         }
46619         function getSimplifiedConditionalType(type, writing) {
46620             var checkType = type.checkType;
46621             var extendsType = type.extendsType;
46622             var trueType = getTrueTypeFromConditionalType(type);
46623             var falseType = getFalseTypeFromConditionalType(type);
46624             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
46625             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
46626                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46627                     return getSimplifiedType(trueType, writing);
46628                 }
46629                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
46630                     return neverType;
46631                 }
46632             }
46633             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
46634                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46635                     return neverType;
46636                 }
46637                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
46638                     return getSimplifiedType(falseType, writing);
46639                 }
46640             }
46641             return type;
46642         }
46643         /**
46644          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
46645          */
46646         function isIntersectionEmpty(type1, type2) {
46647             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
46648         }
46649         function substituteIndexedMappedType(objectType, index) {
46650             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
46651             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
46652             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
46653         }
46654         function getIndexedAccessType(objectType, indexType, accessNode, aliasSymbol, aliasTypeArguments) {
46655             return getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, 0 /* None */, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
46656         }
46657         function getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
46658             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
46659             if (objectType === wildcardType || indexType === wildcardType) {
46660                 return wildcardType;
46661             }
46662             // If the object type has a string index signature and no other members we know that the result will
46663             // always be the type of that index signature and we can simplify accordingly.
46664             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46665                 indexType = stringType;
46666             }
46667             // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
46668             // we are performing a higher-order index access where we cannot meaningfully access the properties of the
46669             // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
46670             // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
46671             // has always been resolved eagerly using the constraint type of 'this' at the given location.
46672             if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 185 /* IndexedAccessType */) && isGenericObjectType(objectType)) {
46673                 if (objectType.flags & 3 /* AnyOrUnknown */) {
46674                     return objectType;
46675                 }
46676                 // Defer the operation by creating an indexed access type.
46677                 var id = objectType.id + "," + indexType.id;
46678                 var type = indexedAccessTypes.get(id);
46679                 if (!type) {
46680                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments));
46681                 }
46682                 return type;
46683             }
46684             // In the following we resolve T[K] to the type of the property in T selected by K.
46685             // We treat boolean as different from other unions to improve errors;
46686             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
46687             var apparentObjectType = getReducedApparentType(objectType);
46688             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
46689                 var propTypes = [];
46690                 var wasMissingProp = false;
46691                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
46692                     var t = _a[_i];
46693                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
46694                     if (propType) {
46695                         propTypes.push(propType);
46696                     }
46697                     else if (!accessNode) {
46698                         // If there's no error node, we can immeditely stop, since error reporting is off
46699                         return undefined;
46700                     }
46701                     else {
46702                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
46703                         wasMissingProp = true;
46704                     }
46705                 }
46706                 if (wasMissingProp) {
46707                     return undefined;
46708                 }
46709                 return accessFlags & 2 /* Writing */ ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46710             }
46711             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */);
46712         }
46713         function getTypeFromIndexedAccessTypeNode(node) {
46714             var links = getNodeLinks(node);
46715             if (!links.resolvedType) {
46716                 var objectType = getTypeFromTypeNode(node.objectType);
46717                 var indexType = getTypeFromTypeNode(node.indexType);
46718                 var potentialAlias = getAliasSymbolForTypeNode(node);
46719                 var resolved = getIndexedAccessType(objectType, indexType, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
46720                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
46721                     resolved.objectType === objectType &&
46722                     resolved.indexType === indexType ?
46723                     getConditionalFlowTypeOfType(resolved, node) : resolved;
46724             }
46725             return links.resolvedType;
46726         }
46727         function getTypeFromMappedTypeNode(node) {
46728             var links = getNodeLinks(node);
46729             if (!links.resolvedType) {
46730                 var type = createObjectType(32 /* Mapped */, node.symbol);
46731                 type.declaration = node;
46732                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
46733                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
46734                 links.resolvedType = type;
46735                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
46736                 // references itself through one or more type aliases.
46737                 getConstraintTypeFromMappedType(type);
46738             }
46739             return links.resolvedType;
46740         }
46741         function getActualTypeVariable(type) {
46742             if (type.flags & 33554432 /* Substitution */) {
46743                 return type.baseType;
46744             }
46745             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
46746                 type.indexType.flags & 33554432 /* Substitution */)) {
46747                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
46748             }
46749             return type;
46750         }
46751         function getConditionalType(root, mapper) {
46752             var result;
46753             var extraTypes;
46754             var _loop_12 = function () {
46755                 var checkType = instantiateType(root.checkType, mapper);
46756                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
46757                 var extendsType = instantiateType(root.extendsType, mapper);
46758                 if (checkType === wildcardType || extendsType === wildcardType) {
46759                     return { value: wildcardType };
46760                 }
46761                 var combinedMapper = void 0;
46762                 if (root.inferTypeParameters) {
46763                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
46764                     // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
46765                     // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
46766                     // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
46767                     // so in those cases we refain from performing inference and retain the uninfered type parameter
46768                     if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
46769                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
46770                         // conditional type instead of deferring resolution. Also, we always want strict function
46771                         // types rules (i.e. proper contravariance) for inferences.
46772                         inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
46773                     }
46774                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
46775                 }
46776                 // Instantiate the extends type including inferences for 'infer T' type parameters
46777                 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
46778                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
46779                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
46780                     // Return falseType for a definitely false extends check. We check an instantiations of the two
46781                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
46782                     // possible (the wildcard type is assignable to and from all types). If those are not related,
46783                     // then no instantiations will be and we can just return the false branch type.
46784                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
46785                         // Return union of trueType and falseType for 'any' since it matches anything
46786                         if (checkType.flags & 1 /* Any */) {
46787                             (extraTypes || (extraTypes = [])).push(instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper));
46788                         }
46789                         // If falseType is an immediately nested conditional type that isn't distributive or has an
46790                         // identical checkType, switch to that type and loop.
46791                         var falseType_1 = root.falseType;
46792                         if (falseType_1.flags & 16777216 /* Conditional */) {
46793                             var newRoot = falseType_1.root;
46794                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
46795                                 root = newRoot;
46796                                 return "continue";
46797                             }
46798                         }
46799                         result = instantiateTypeWithoutDepthIncrease(falseType_1, mapper);
46800                         return "break";
46801                     }
46802                     // Return trueType for a definitely true extends check. We check instantiations of the two
46803                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
46804                     // that has no constraint. This ensures that, for example, the type
46805                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
46806                     // doesn't immediately resolve to 'string' instead of being deferred.
46807                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
46808                         result = instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper);
46809                         return "break";
46810                     }
46811                 }
46812                 // Return a deferred type for a check that is neither definitely true nor definitely false
46813                 var erasedCheckType = getActualTypeVariable(checkType);
46814                 result = createType(16777216 /* Conditional */);
46815                 result.root = root;
46816                 result.checkType = erasedCheckType;
46817                 result.extendsType = extendsType;
46818                 result.mapper = mapper;
46819                 result.combinedMapper = combinedMapper;
46820                 result.aliasSymbol = root.aliasSymbol;
46821                 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
46822                 return "break";
46823             };
46824             // We loop here for an immediately nested conditional type in the false position, effectively treating
46825             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
46826             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
46827             while (true) {
46828                 var state_4 = _loop_12();
46829                 if (typeof state_4 === "object")
46830                     return state_4.value;
46831                 if (state_4 === "break")
46832                     break;
46833             }
46834             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
46835         }
46836         function getTrueTypeFromConditionalType(type) {
46837             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
46838         }
46839         function getFalseTypeFromConditionalType(type) {
46840             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
46841         }
46842         function getInferredTrueTypeFromConditionalType(type) {
46843             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(type.root.trueType, type.combinedMapper) : getTrueTypeFromConditionalType(type));
46844         }
46845         function getInferTypeParameters(node) {
46846             var result;
46847             if (node.locals) {
46848                 node.locals.forEach(function (symbol) {
46849                     if (symbol.flags & 262144 /* TypeParameter */) {
46850                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
46851                     }
46852                 });
46853             }
46854             return result;
46855         }
46856         function getTypeFromConditionalTypeNode(node) {
46857             var links = getNodeLinks(node);
46858             if (!links.resolvedType) {
46859                 var checkType = getTypeFromTypeNode(node.checkType);
46860                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46861                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46862                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
46863                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
46864                 var root = {
46865                     node: node,
46866                     checkType: checkType,
46867                     extendsType: getTypeFromTypeNode(node.extendsType),
46868                     trueType: getTypeFromTypeNode(node.trueType),
46869                     falseType: getTypeFromTypeNode(node.falseType),
46870                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
46871                     inferTypeParameters: getInferTypeParameters(node),
46872                     outerTypeParameters: outerTypeParameters,
46873                     instantiations: undefined,
46874                     aliasSymbol: aliasSymbol,
46875                     aliasTypeArguments: aliasTypeArguments
46876                 };
46877                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
46878                 if (outerTypeParameters) {
46879                     root.instantiations = ts.createMap();
46880                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
46881                 }
46882             }
46883             return links.resolvedType;
46884         }
46885         function getTypeFromInferTypeNode(node) {
46886             var links = getNodeLinks(node);
46887             if (!links.resolvedType) {
46888                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
46889             }
46890             return links.resolvedType;
46891         }
46892         function getIdentifierChain(node) {
46893             if (ts.isIdentifier(node)) {
46894                 return [node];
46895             }
46896             else {
46897                 return ts.append(getIdentifierChain(node.left), node.right);
46898             }
46899         }
46900         function getTypeFromImportTypeNode(node) {
46901             var links = getNodeLinks(node);
46902             if (!links.resolvedType) {
46903                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
46904                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
46905                     links.resolvedSymbol = unknownSymbol;
46906                     return links.resolvedType = errorType;
46907                 }
46908                 if (!ts.isLiteralImportTypeNode(node)) {
46909                     error(node.argument, ts.Diagnostics.String_literal_expected);
46910                     links.resolvedSymbol = unknownSymbol;
46911                     return links.resolvedType = errorType;
46912                 }
46913                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
46914                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
46915                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
46916                 if (!innerModuleSymbol) {
46917                     links.resolvedSymbol = unknownSymbol;
46918                     return links.resolvedType = errorType;
46919                 }
46920                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
46921                 if (!ts.nodeIsMissing(node.qualifier)) {
46922                     var nameStack = getIdentifierChain(node.qualifier);
46923                     var currentNamespace = moduleSymbol;
46924                     var current = void 0;
46925                     while (current = nameStack.shift()) {
46926                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
46927                         var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
46928                         if (!next) {
46929                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
46930                             return links.resolvedType = errorType;
46931                         }
46932                         getNodeLinks(current).resolvedSymbol = next;
46933                         getNodeLinks(current.parent).resolvedSymbol = next;
46934                         currentNamespace = next;
46935                     }
46936                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
46937                 }
46938                 else {
46939                     if (moduleSymbol.flags & targetMeaning) {
46940                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
46941                     }
46942                     else {
46943                         var errorMessage = targetMeaning === 111551 /* Value */
46944                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
46945                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
46946                         error(node, errorMessage, node.argument.literal.text);
46947                         links.resolvedSymbol = unknownSymbol;
46948                         links.resolvedType = errorType;
46949                     }
46950                 }
46951             }
46952             return links.resolvedType;
46953         }
46954         function resolveImportSymbolType(node, links, symbol, meaning) {
46955             var resolvedSymbol = resolveSymbol(symbol);
46956             links.resolvedSymbol = resolvedSymbol;
46957             if (meaning === 111551 /* Value */) {
46958                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
46959             }
46960             else {
46961                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
46962             }
46963         }
46964         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
46965             var links = getNodeLinks(node);
46966             if (!links.resolvedType) {
46967                 // Deferred resolution of members is handled by resolveObjectTypeMembers
46968                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46969                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
46970                     links.resolvedType = emptyTypeLiteralType;
46971                 }
46972                 else {
46973                     var type = createObjectType(16 /* Anonymous */, node.symbol);
46974                     type.aliasSymbol = aliasSymbol;
46975                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46976                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
46977                         type = createArrayType(type);
46978                     }
46979                     links.resolvedType = type;
46980                 }
46981             }
46982             return links.resolvedType;
46983         }
46984         function getAliasSymbolForTypeNode(node) {
46985             var host = node.parent;
46986             while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 138 /* ReadonlyKeyword */) {
46987                 host = host.parent;
46988             }
46989             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
46990         }
46991         function getTypeArgumentsForAliasSymbol(symbol) {
46992             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
46993         }
46994         function isNonGenericObjectType(type) {
46995             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
46996         }
46997         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
46998             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
46999         }
47000         function isSinglePropertyAnonymousObjectType(type) {
47001             return !!(type.flags & 524288 /* Object */) &&
47002                 !!(ts.getObjectFlags(type) & 16 /* Anonymous */) &&
47003                 (ts.length(getPropertiesOfType(type)) === 1 || ts.every(getPropertiesOfType(type), function (p) { return !!(p.flags & 16777216 /* Optional */); }));
47004         }
47005         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
47006             if (type.types.length === 2) {
47007                 var firstType = type.types[0];
47008                 var secondType = type.types[1];
47009                 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
47010                     return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
47011                 }
47012                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType) && isSinglePropertyAnonymousObjectType(secondType)) {
47013                     return getAnonymousPartialType(secondType);
47014                 }
47015                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType) && isSinglePropertyAnonymousObjectType(firstType)) {
47016                     return getAnonymousPartialType(firstType);
47017                 }
47018             }
47019             function getAnonymousPartialType(type) {
47020                 // gets the type as if it had been spread, but where everything in the spread is made optional
47021                 var members = ts.createSymbolTable();
47022                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
47023                     var prop = _a[_i];
47024                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
47025                         // do nothing, skip privates
47026                     }
47027                     else if (isSpreadableProperty(prop)) {
47028                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47029                         var flags = 4 /* Property */ | 16777216 /* Optional */;
47030                         var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47031                         result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47032                         result.declarations = prop.declarations;
47033                         result.nameType = getSymbolLinks(prop).nameType;
47034                         result.syntheticOrigin = prop;
47035                         members.set(prop.escapedName, result);
47036                     }
47037                 }
47038                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
47039                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
47040                 return spread;
47041             }
47042         }
47043         /**
47044          * Since the source of spread types are object literals, which are not binary,
47045          * this function should be called in a left folding style, with left = previous result of getSpreadType
47046          * and right = the new element to be spread.
47047          */
47048         function getSpreadType(left, right, symbol, objectFlags, readonly) {
47049             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
47050                 return anyType;
47051             }
47052             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
47053                 return unknownType;
47054             }
47055             if (left.flags & 131072 /* Never */) {
47056                 return right;
47057             }
47058             if (right.flags & 131072 /* Never */) {
47059                 return left;
47060             }
47061             if (left.flags & 1048576 /* Union */) {
47062                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
47063                 if (merged) {
47064                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
47065                 }
47066                 return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
47067             }
47068             if (right.flags & 1048576 /* Union */) {
47069                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
47070                 if (merged) {
47071                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
47072                 }
47073                 return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
47074             }
47075             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
47076                 return left;
47077             }
47078             if (isGenericObjectType(left) || isGenericObjectType(right)) {
47079                 if (isEmptyObjectType(left)) {
47080                     return right;
47081                 }
47082                 // When the left type is an intersection, we may need to merge the last constituent of the
47083                 // intersection with the right type. For example when the left type is 'T & { a: string }'
47084                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
47085                 if (left.flags & 2097152 /* Intersection */) {
47086                     var types = left.types;
47087                     var lastLeft = types[types.length - 1];
47088                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
47089                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
47090                     }
47091                 }
47092                 return getIntersectionType([left, right]);
47093             }
47094             var members = ts.createSymbolTable();
47095             var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
47096             var stringIndexInfo;
47097             var numberIndexInfo;
47098             if (left === emptyObjectType) {
47099                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
47100                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
47101                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
47102             }
47103             else {
47104                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
47105                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
47106             }
47107             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
47108                 var rightProp = _a[_i];
47109                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
47110                     skippedPrivateMembers.set(rightProp.escapedName, true);
47111                 }
47112                 else if (isSpreadableProperty(rightProp)) {
47113                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
47114                 }
47115             }
47116             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
47117                 var leftProp = _c[_b];
47118                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
47119                     continue;
47120                 }
47121                 if (members.has(leftProp.escapedName)) {
47122                     var rightProp = members.get(leftProp.escapedName);
47123                     var rightType = getTypeOfSymbol(rightProp);
47124                     if (rightProp.flags & 16777216 /* Optional */) {
47125                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
47126                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
47127                         var result = createSymbol(flags, leftProp.escapedName);
47128                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
47129                         result.leftSpread = leftProp;
47130                         result.rightSpread = rightProp;
47131                         result.declarations = declarations;
47132                         result.nameType = getSymbolLinks(leftProp).nameType;
47133                         members.set(leftProp.escapedName, result);
47134                     }
47135                 }
47136                 else {
47137                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
47138                 }
47139             }
47140             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
47141             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
47142             return spread;
47143         }
47144         /** We approximate own properties as non-methods plus methods that are inside the object literal */
47145         function isSpreadableProperty(prop) {
47146             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
47147                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
47148                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
47149         }
47150         function getSpreadSymbol(prop, readonly) {
47151             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47152             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
47153                 return prop;
47154             }
47155             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
47156             var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47157             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47158             result.declarations = prop.declarations;
47159             result.nameType = getSymbolLinks(prop).nameType;
47160             result.syntheticOrigin = prop;
47161             return result;
47162         }
47163         function getIndexInfoWithReadonly(info, readonly) {
47164             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
47165         }
47166         function createLiteralType(flags, value, symbol) {
47167             var type = createType(flags);
47168             type.symbol = symbol;
47169             type.value = value;
47170             return type;
47171         }
47172         function getFreshTypeOfLiteralType(type) {
47173             if (type.flags & 2944 /* Literal */) {
47174                 if (!type.freshType) {
47175                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
47176                     freshType.regularType = type;
47177                     freshType.freshType = freshType;
47178                     type.freshType = freshType;
47179                 }
47180                 return type.freshType;
47181             }
47182             return type;
47183         }
47184         function getRegularTypeOfLiteralType(type) {
47185             return type.flags & 2944 /* Literal */ ? type.regularType :
47186                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
47187                     type;
47188         }
47189         function isFreshLiteralType(type) {
47190             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
47191         }
47192         function getLiteralType(value, enumId, symbol) {
47193             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
47194             // where NNN is the text representation of a numeric literal and SSS are the characters
47195             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
47196             // EEE is a unique id for the containing enum type.
47197             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
47198             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
47199             var type = literalTypes.get(key);
47200             if (!type) {
47201                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
47202                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
47203                     (enumId ? 1024 /* EnumLiteral */ : 0);
47204                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
47205                 type.regularType = type;
47206             }
47207             return type;
47208         }
47209         function getTypeFromLiteralTypeNode(node) {
47210             var links = getNodeLinks(node);
47211             if (!links.resolvedType) {
47212                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
47213             }
47214             return links.resolvedType;
47215         }
47216         function createUniqueESSymbolType(symbol) {
47217             var type = createType(8192 /* UniqueESSymbol */);
47218             type.symbol = symbol;
47219             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
47220             return type;
47221         }
47222         function getESSymbolLikeTypeForNode(node) {
47223             if (ts.isValidESSymbolDeclaration(node)) {
47224                 var symbol = getSymbolOfNode(node);
47225                 var links = getSymbolLinks(symbol);
47226                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
47227             }
47228             return esSymbolType;
47229         }
47230         function getThisType(node) {
47231             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
47232             var parent = container && container.parent;
47233             if (parent && (ts.isClassLike(parent) || parent.kind === 246 /* InterfaceDeclaration */)) {
47234                 if (!ts.hasModifier(container, 32 /* Static */) &&
47235                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
47236                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
47237                 }
47238             }
47239             // inside x.prototype = { ... }
47240             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
47241                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
47242             }
47243             // /** @return {this} */
47244             // x.prototype.m = function() { ... }
47245             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
47246             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
47247                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
47248             }
47249             // inside constructor function C() { ... }
47250             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
47251                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
47252             }
47253             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
47254             return errorType;
47255         }
47256         function getTypeFromThisTypeNode(node) {
47257             var links = getNodeLinks(node);
47258             if (!links.resolvedType) {
47259                 links.resolvedType = getThisType(node);
47260             }
47261             return links.resolvedType;
47262         }
47263         function getTypeFromTypeNode(node) {
47264             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
47265         }
47266         function getTypeFromTypeNodeWorker(node) {
47267             switch (node.kind) {
47268                 case 125 /* AnyKeyword */:
47269                 case 295 /* JSDocAllType */:
47270                 case 296 /* JSDocUnknownType */:
47271                     return anyType;
47272                 case 148 /* UnknownKeyword */:
47273                     return unknownType;
47274                 case 143 /* StringKeyword */:
47275                     return stringType;
47276                 case 140 /* NumberKeyword */:
47277                     return numberType;
47278                 case 151 /* BigIntKeyword */:
47279                     return bigintType;
47280                 case 128 /* BooleanKeyword */:
47281                     return booleanType;
47282                 case 144 /* SymbolKeyword */:
47283                     return esSymbolType;
47284                 case 110 /* VoidKeyword */:
47285                     return voidType;
47286                 case 146 /* UndefinedKeyword */:
47287                     return undefinedType;
47288                 case 100 /* NullKeyword */:
47289                     return nullType;
47290                 case 137 /* NeverKeyword */:
47291                     return neverType;
47292                 case 141 /* ObjectKeyword */:
47293                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
47294                 case 183 /* ThisType */:
47295                 case 104 /* ThisKeyword */:
47296                     return getTypeFromThisTypeNode(node);
47297                 case 187 /* LiteralType */:
47298                     return getTypeFromLiteralTypeNode(node);
47299                 case 169 /* TypeReference */:
47300                     return getTypeFromTypeReference(node);
47301                 case 168 /* TypePredicate */:
47302                     return node.assertsModifier ? voidType : booleanType;
47303                 case 216 /* ExpressionWithTypeArguments */:
47304                     return getTypeFromTypeReference(node);
47305                 case 172 /* TypeQuery */:
47306                     return getTypeFromTypeQueryNode(node);
47307                 case 174 /* ArrayType */:
47308                 case 175 /* TupleType */:
47309                     return getTypeFromArrayOrTupleTypeNode(node);
47310                 case 176 /* OptionalType */:
47311                     return getTypeFromOptionalTypeNode(node);
47312                 case 178 /* UnionType */:
47313                     return getTypeFromUnionTypeNode(node);
47314                 case 179 /* IntersectionType */:
47315                     return getTypeFromIntersectionTypeNode(node);
47316                 case 297 /* JSDocNullableType */:
47317                     return getTypeFromJSDocNullableTypeNode(node);
47318                 case 299 /* JSDocOptionalType */:
47319                     return addOptionality(getTypeFromTypeNode(node.type));
47320                 case 182 /* ParenthesizedType */:
47321                 case 298 /* JSDocNonNullableType */:
47322                 case 294 /* JSDocTypeExpression */:
47323                     return getTypeFromTypeNode(node.type);
47324                 case 177 /* RestType */:
47325                     return getElementTypeOfArrayType(getTypeFromTypeNode(node.type)) || errorType;
47326                 case 301 /* JSDocVariadicType */:
47327                     return getTypeFromJSDocVariadicType(node);
47328                 case 170 /* FunctionType */:
47329                 case 171 /* ConstructorType */:
47330                 case 173 /* TypeLiteral */:
47331                 case 304 /* JSDocTypeLiteral */:
47332                 case 300 /* JSDocFunctionType */:
47333                 case 305 /* JSDocSignature */:
47334                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
47335                 case 184 /* TypeOperator */:
47336                     return getTypeFromTypeOperatorNode(node);
47337                 case 185 /* IndexedAccessType */:
47338                     return getTypeFromIndexedAccessTypeNode(node);
47339                 case 186 /* MappedType */:
47340                     return getTypeFromMappedTypeNode(node);
47341                 case 180 /* ConditionalType */:
47342                     return getTypeFromConditionalTypeNode(node);
47343                 case 181 /* InferType */:
47344                     return getTypeFromInferTypeNode(node);
47345                 case 188 /* ImportType */:
47346                     return getTypeFromImportTypeNode(node);
47347                 // This function assumes that an identifier or qualified name is a type expression
47348                 // Callers should first ensure this by calling isTypeNode
47349                 case 75 /* Identifier */:
47350                 case 153 /* QualifiedName */:
47351                     var symbol = getSymbolAtLocation(node);
47352                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
47353                 default:
47354                     return errorType;
47355             }
47356         }
47357         function instantiateList(items, mapper, instantiator) {
47358             if (items && items.length) {
47359                 for (var i = 0; i < items.length; i++) {
47360                     var item = items[i];
47361                     var mapped = instantiator(item, mapper);
47362                     if (item !== mapped) {
47363                         var result = i === 0 ? [] : items.slice(0, i);
47364                         result.push(mapped);
47365                         for (i++; i < items.length; i++) {
47366                             result.push(instantiator(items[i], mapper));
47367                         }
47368                         return result;
47369                     }
47370                 }
47371             }
47372             return items;
47373         }
47374         function instantiateTypes(types, mapper) {
47375             return instantiateList(types, mapper, instantiateType);
47376         }
47377         function instantiateSignatures(signatures, mapper) {
47378             return instantiateList(signatures, mapper, instantiateSignature);
47379         }
47380         function createTypeMapper(sources, targets) {
47381             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
47382         }
47383         function getMappedType(type, mapper) {
47384             switch (mapper.kind) {
47385                 case 0 /* Simple */:
47386                     return type === mapper.source ? mapper.target : type;
47387                 case 1 /* Array */:
47388                     var sources = mapper.sources;
47389                     var targets = mapper.targets;
47390                     for (var i = 0; i < sources.length; i++) {
47391                         if (type === sources[i]) {
47392                             return targets ? targets[i] : anyType;
47393                         }
47394                     }
47395                     return type;
47396                 case 2 /* Function */:
47397                     return mapper.func(type);
47398                 case 3 /* Composite */:
47399                 case 4 /* Merged */:
47400                     var t1 = getMappedType(type, mapper.mapper1);
47401                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
47402             }
47403         }
47404         function makeUnaryTypeMapper(source, target) {
47405             return { kind: 0 /* Simple */, source: source, target: target };
47406         }
47407         function makeArrayTypeMapper(sources, targets) {
47408             return { kind: 1 /* Array */, sources: sources, targets: targets };
47409         }
47410         function makeFunctionTypeMapper(func) {
47411             return { kind: 2 /* Function */, func: func };
47412         }
47413         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
47414             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
47415         }
47416         function createTypeEraser(sources) {
47417             return createTypeMapper(sources, /*targets*/ undefined);
47418         }
47419         /**
47420          * Maps forward-references to later types parameters to the empty object type.
47421          * This is used during inference when instantiating type parameter defaults.
47422          */
47423         function createBackreferenceMapper(context, index) {
47424             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
47425         }
47426         function combineTypeMappers(mapper1, mapper2) {
47427             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
47428         }
47429         function mergeTypeMappers(mapper1, mapper2) {
47430             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
47431         }
47432         function prependTypeMapping(source, target, mapper) {
47433             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
47434         }
47435         function appendTypeMapping(mapper, source, target) {
47436             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
47437         }
47438         function getRestrictiveTypeParameter(tp) {
47439             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
47440                 tp.restrictiveInstantiation.constraint = unknownType,
47441                 tp.restrictiveInstantiation);
47442         }
47443         function cloneTypeParameter(typeParameter) {
47444             var result = createTypeParameter(typeParameter.symbol);
47445             result.target = typeParameter;
47446             return result;
47447         }
47448         function instantiateTypePredicate(predicate, mapper) {
47449             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
47450         }
47451         function instantiateSignature(signature, mapper, eraseTypeParameters) {
47452             var freshTypeParameters;
47453             if (signature.typeParameters && !eraseTypeParameters) {
47454                 // First create a fresh set of type parameters, then include a mapping from the old to the
47455                 // new type parameters in the mapper function. Finally store this mapper in the new type
47456                 // parameters such that we can use it when instantiating constraints.
47457                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
47458                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
47459                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
47460                     var tp = freshTypeParameters_1[_i];
47461                     tp.mapper = mapper;
47462                 }
47463             }
47464             // Don't compute resolvedReturnType and resolvedTypePredicate now,
47465             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
47466             // See GH#17600.
47467             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
47468             /*resolvedReturnType*/ undefined, 
47469             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */);
47470             result.target = signature;
47471             result.mapper = mapper;
47472             return result;
47473         }
47474         function instantiateSymbol(symbol, mapper) {
47475             var links = getSymbolLinks(symbol);
47476             if (links.type && !couldContainTypeVariables(links.type)) {
47477                 // If the type of the symbol is already resolved, and if that type could not possibly
47478                 // be affected by instantiation, simply return the symbol itself.
47479                 return symbol;
47480             }
47481             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
47482                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
47483                 // type mappers. This ensures that original type identities are properly preserved and that aliases
47484                 // always reference a non-aliases.
47485                 symbol = links.target;
47486                 mapper = combineTypeMappers(links.mapper, mapper);
47487             }
47488             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
47489             // also transient so that we can just store data on it directly.
47490             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
47491             result.declarations = symbol.declarations;
47492             result.parent = symbol.parent;
47493             result.target = symbol;
47494             result.mapper = mapper;
47495             if (symbol.valueDeclaration) {
47496                 result.valueDeclaration = symbol.valueDeclaration;
47497             }
47498             if (links.nameType) {
47499                 result.nameType = links.nameType;
47500             }
47501             return result;
47502         }
47503         function getObjectTypeInstantiation(type, mapper) {
47504             var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
47505             var node = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
47506             var links = getNodeLinks(node);
47507             var typeParameters = links.outerTypeParameters;
47508             if (!typeParameters) {
47509                 // The first time an anonymous type is instantiated we compute and store a list of the type
47510                 // parameters that are in scope (and therefore potentially referenced). For type literals that
47511                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
47512                 // set of type parameters to those that are possibly referenced in the literal.
47513                 var declaration_1 = node;
47514                 if (ts.isInJSFile(declaration_1)) {
47515                     var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
47516                     if (paramTag) {
47517                         var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
47518                         if (paramSymbol) {
47519                             declaration_1 = paramSymbol.valueDeclaration;
47520                         }
47521                     }
47522                 }
47523                 var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
47524                 if (isJSConstructor(declaration_1)) {
47525                     var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
47526                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
47527                 }
47528                 typeParameters = outerTypeParameters || ts.emptyArray;
47529                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
47530                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
47531                     typeParameters;
47532                 links.outerTypeParameters = typeParameters;
47533                 if (typeParameters.length) {
47534                     links.instantiations = ts.createMap();
47535                     links.instantiations.set(getTypeListId(typeParameters), target);
47536                 }
47537             }
47538             if (typeParameters.length) {
47539                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
47540                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47541                 // instantiation cache key from the type IDs of the type arguments.
47542                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
47543                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
47544                 var id = getTypeListId(typeArguments);
47545                 var result = links.instantiations.get(id);
47546                 if (!result) {
47547                     var newMapper = createTypeMapper(typeParameters, typeArguments);
47548                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
47549                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
47550                             instantiateAnonymousType(target, newMapper);
47551                     links.instantiations.set(id, result);
47552                 }
47553                 return result;
47554             }
47555             return type;
47556         }
47557         function maybeTypeParameterReference(node) {
47558             return !(node.kind === 153 /* QualifiedName */ ||
47559                 node.parent.kind === 169 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
47560                 node.parent.kind === 188 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
47561         }
47562         function isTypeParameterPossiblyReferenced(tp, node) {
47563             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
47564             // between the node and the type parameter declaration, if the node contains actual references to the
47565             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
47566             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
47567                 var container = tp.symbol.declarations[0].parent;
47568                 for (var n = node; n !== container; n = n.parent) {
47569                     if (!n || n.kind === 223 /* Block */ || n.kind === 180 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
47570                         return true;
47571                     }
47572                 }
47573                 return !!ts.forEachChild(node, containsReference);
47574             }
47575             return true;
47576             function containsReference(node) {
47577                 switch (node.kind) {
47578                     case 183 /* ThisType */:
47579                         return !!tp.isThisType;
47580                     case 75 /* Identifier */:
47581                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
47582                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
47583                     case 172 /* TypeQuery */:
47584                         return true;
47585                 }
47586                 return !!ts.forEachChild(node, containsReference);
47587             }
47588         }
47589         function getHomomorphicTypeVariable(type) {
47590             var constraintType = getConstraintTypeFromMappedType(type);
47591             if (constraintType.flags & 4194304 /* Index */) {
47592                 var typeVariable = getActualTypeVariable(constraintType.type);
47593                 if (typeVariable.flags & 262144 /* TypeParameter */) {
47594                     return typeVariable;
47595                 }
47596             }
47597             return undefined;
47598         }
47599         function instantiateMappedType(type, mapper) {
47600             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
47601             // operation depends on T as follows:
47602             // * If T is a primitive type no mapping is performed and the result is simply T.
47603             // * If T is a union type we distribute the mapped type over the union.
47604             // * If T is an array we map to an array where the element type has been transformed.
47605             // * If T is a tuple we map to a tuple where the element types have been transformed.
47606             // * Otherwise we map to an object type where the type of each property has been transformed.
47607             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
47608             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
47609             // { [P in keyof A]: X } | undefined.
47610             var typeVariable = getHomomorphicTypeVariable(type);
47611             if (typeVariable) {
47612                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
47613                 if (typeVariable !== mappedTypeVariable) {
47614                     return mapType(getReducedType(mappedTypeVariable), function (t) {
47615                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
47616                             var replacementMapper = prependTypeMapping(typeVariable, t, mapper);
47617                             return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
47618                                 isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
47619                                     instantiateAnonymousType(type, replacementMapper);
47620                         }
47621                         return t;
47622                     });
47623                 }
47624             }
47625             return instantiateAnonymousType(type, mapper);
47626         }
47627         function getModifiedReadonlyState(state, modifiers) {
47628             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
47629         }
47630         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
47631             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
47632             return elementType === errorType ? errorType :
47633                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
47634         }
47635         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
47636             var minLength = tupleType.target.minLength;
47637             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
47638                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
47639             });
47640             var modifiers = getMappedTypeModifiers(mappedType);
47641             var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
47642                 modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
47643                     minLength;
47644             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
47645             return ts.contains(elementTypes, errorType) ? errorType :
47646                 createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
47647         }
47648         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
47649             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
47650             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
47651             var modifiers = getMappedTypeModifiers(type);
47652             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
47653                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
47654                     propType;
47655         }
47656         function instantiateAnonymousType(type, mapper) {
47657             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
47658             if (type.objectFlags & 32 /* Mapped */) {
47659                 result.declaration = type.declaration;
47660                 // C.f. instantiateSignature
47661                 var origTypeParameter = getTypeParameterFromMappedType(type);
47662                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
47663                 result.typeParameter = freshTypeParameter;
47664                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
47665                 freshTypeParameter.mapper = mapper;
47666             }
47667             result.target = type;
47668             result.mapper = mapper;
47669             result.aliasSymbol = type.aliasSymbol;
47670             result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
47671             return result;
47672         }
47673         function getConditionalTypeInstantiation(type, mapper) {
47674             var root = type.root;
47675             if (root.outerTypeParameters) {
47676                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
47677                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47678                 // instantiation cache key from the type IDs of the type arguments.
47679                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
47680                 var id = getTypeListId(typeArguments);
47681                 var result = root.instantiations.get(id);
47682                 if (!result) {
47683                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
47684                     result = instantiateConditionalType(root, newMapper);
47685                     root.instantiations.set(id, result);
47686                 }
47687                 return result;
47688             }
47689             return type;
47690         }
47691         function instantiateConditionalType(root, mapper) {
47692             // Check if we have a conditional type where the check type is a naked type parameter. If so,
47693             // the conditional type is distributive over union types and when T is instantiated to a union
47694             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
47695             if (root.isDistributive) {
47696                 var checkType_1 = root.checkType;
47697                 var instantiatedType = getMappedType(checkType_1, mapper);
47698                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
47699                     return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
47700                 }
47701             }
47702             return getConditionalType(root, mapper);
47703         }
47704         function instantiateType(type, mapper) {
47705             if (!type || !mapper) {
47706                 return type;
47707             }
47708             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
47709                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
47710                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
47711                 // the recursion here by yielding the error type.
47712                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
47713                 return errorType;
47714             }
47715             totalInstantiationCount++;
47716             instantiationCount++;
47717             instantiationDepth++;
47718             var result = instantiateTypeWorker(type, mapper);
47719             instantiationDepth--;
47720             return result;
47721         }
47722         /**
47723          * This can be used to avoid the penalty on instantiation depth for types which result from immediate
47724          * simplification. It essentially removes the depth increase done in `instantiateType`.
47725          */
47726         function instantiateTypeWithoutDepthIncrease(type, mapper) {
47727             instantiationDepth--;
47728             var result = instantiateType(type, mapper);
47729             instantiationDepth++;
47730             return result;
47731         }
47732         function instantiateTypeWorker(type, mapper) {
47733             var flags = type.flags;
47734             if (flags & 262144 /* TypeParameter */) {
47735                 return getMappedType(type, mapper);
47736             }
47737             if (flags & 524288 /* Object */) {
47738                 var objectFlags = type.objectFlags;
47739                 if (objectFlags & 16 /* Anonymous */) {
47740                     // If the anonymous type originates in a declaration of a function, method, class, or
47741                     // interface, in an object type literal, or in an object literal expression, we may need
47742                     // to instantiate the type because it might reference a type parameter.
47743                     return couldContainTypeVariables(type) ?
47744                         getObjectTypeInstantiation(type, mapper) : type;
47745                 }
47746                 if (objectFlags & 32 /* Mapped */) {
47747                     return getObjectTypeInstantiation(type, mapper);
47748                 }
47749                 if (objectFlags & 4 /* Reference */) {
47750                     if (type.node) {
47751                         return getObjectTypeInstantiation(type, mapper);
47752                     }
47753                     var resolvedTypeArguments = type.resolvedTypeArguments;
47754                     var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
47755                     return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type;
47756                 }
47757                 return type;
47758             }
47759             if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) {
47760                 if (!couldContainTypeVariables(type)) {
47761                     return type;
47762                 }
47763                 var types = type.types;
47764                 var newTypes = instantiateTypes(types, mapper);
47765                 return newTypes === types
47766                     ? type
47767                     : (flags & 2097152 /* Intersection */)
47768                         ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper))
47769                         : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47770             }
47771             if (flags & 4194304 /* Index */) {
47772                 return getIndexType(instantiateType(type.type, mapper));
47773             }
47774             if (flags & 8388608 /* IndexedAccess */) {
47775                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47776             }
47777             if (flags & 16777216 /* Conditional */) {
47778                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
47779             }
47780             if (flags & 33554432 /* Substitution */) {
47781                 var maybeVariable = instantiateType(type.baseType, mapper);
47782                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
47783                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
47784                 }
47785                 else {
47786                     var sub = instantiateType(type.substitute, mapper);
47787                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
47788                         return maybeVariable;
47789                     }
47790                     return sub;
47791                 }
47792             }
47793             return type;
47794         }
47795         function getPermissiveInstantiation(type) {
47796             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
47797                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
47798         }
47799         function getRestrictiveInstantiation(type) {
47800             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
47801                 return type;
47802             }
47803             if (type.restrictiveInstantiation) {
47804                 return type.restrictiveInstantiation;
47805             }
47806             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
47807             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
47808             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
47809             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
47810             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
47811             // are constrained to `unknown` and produce tons of false positives/negatives!
47812             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
47813             return type.restrictiveInstantiation;
47814         }
47815         function instantiateIndexInfo(info, mapper) {
47816             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
47817         }
47818         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
47819         // that is subject to contextual typing.
47820         function isContextSensitive(node) {
47821             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
47822             switch (node.kind) {
47823                 case 201 /* FunctionExpression */:
47824                 case 202 /* ArrowFunction */:
47825                 case 161 /* MethodDeclaration */:
47826                 case 244 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
47827                     return isContextSensitiveFunctionLikeDeclaration(node);
47828                 case 193 /* ObjectLiteralExpression */:
47829                     return ts.some(node.properties, isContextSensitive);
47830                 case 192 /* ArrayLiteralExpression */:
47831                     return ts.some(node.elements, isContextSensitive);
47832                 case 210 /* ConditionalExpression */:
47833                     return isContextSensitive(node.whenTrue) ||
47834                         isContextSensitive(node.whenFalse);
47835                 case 209 /* BinaryExpression */:
47836                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
47837                         (isContextSensitive(node.left) || isContextSensitive(node.right));
47838                 case 281 /* PropertyAssignment */:
47839                     return isContextSensitive(node.initializer);
47840                 case 200 /* ParenthesizedExpression */:
47841                     return isContextSensitive(node.expression);
47842                 case 274 /* JsxAttributes */:
47843                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
47844                 case 273 /* JsxAttribute */: {
47845                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
47846                     var initializer = node.initializer;
47847                     return !!initializer && isContextSensitive(initializer);
47848                 }
47849                 case 276 /* JsxExpression */: {
47850                     // It is possible to that node.expression is undefined (e.g <div x={} />)
47851                     var expression = node.expression;
47852                     return !!expression && isContextSensitive(expression);
47853                 }
47854             }
47855             return false;
47856         }
47857         function isContextSensitiveFunctionLikeDeclaration(node) {
47858             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
47859                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
47860         }
47861         function hasContextSensitiveParameters(node) {
47862             // Functions with type parameters are not context sensitive.
47863             if (!node.typeParameters) {
47864                 // Functions with any parameters that lack type annotations are context sensitive.
47865                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
47866                     return true;
47867                 }
47868                 if (node.kind !== 202 /* ArrowFunction */) {
47869                     // If the first parameter is not an explicit 'this' parameter, then the function has
47870                     // an implicit 'this' parameter which is subject to contextual typing.
47871                     var parameter = ts.firstOrUndefined(node.parameters);
47872                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
47873                         return true;
47874                     }
47875                 }
47876             }
47877             return false;
47878         }
47879         function hasContextSensitiveReturnExpression(node) {
47880             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
47881             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body);
47882         }
47883         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
47884             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
47885                 isContextSensitiveFunctionLikeDeclaration(func);
47886         }
47887         function getTypeWithoutSignatures(type) {
47888             if (type.flags & 524288 /* Object */) {
47889                 var resolved = resolveStructuredTypeMembers(type);
47890                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
47891                     var result = createObjectType(16 /* Anonymous */, type.symbol);
47892                     result.members = resolved.members;
47893                     result.properties = resolved.properties;
47894                     result.callSignatures = ts.emptyArray;
47895                     result.constructSignatures = ts.emptyArray;
47896                     return result;
47897                 }
47898             }
47899             else if (type.flags & 2097152 /* Intersection */) {
47900                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
47901             }
47902             return type;
47903         }
47904         // TYPE CHECKING
47905         function isTypeIdenticalTo(source, target) {
47906             return isTypeRelatedTo(source, target, identityRelation);
47907         }
47908         function compareTypesIdentical(source, target) {
47909             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
47910         }
47911         function compareTypesAssignable(source, target) {
47912             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
47913         }
47914         function compareTypesSubtypeOf(source, target) {
47915             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
47916         }
47917         function isTypeSubtypeOf(source, target) {
47918             return isTypeRelatedTo(source, target, subtypeRelation);
47919         }
47920         function isTypeAssignableTo(source, target) {
47921             return isTypeRelatedTo(source, target, assignableRelation);
47922         }
47923         // An object type S is considered to be derived from an object type T if
47924         // S is a union type and every constituent of S is derived from T,
47925         // T is a union type and S is derived from at least one constituent of T, or
47926         // S is a type variable with a base constraint that is derived from T,
47927         // T is one of the global types Object and Function and S is a subtype of T, or
47928         // T occurs directly or indirectly in an 'extends' clause of S.
47929         // Note that this check ignores type parameters and only considers the
47930         // inheritance hierarchy.
47931         function isTypeDerivedFrom(source, target) {
47932             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
47933                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
47934                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
47935                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
47936                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
47937                                 hasBaseType(source, getTargetType(target));
47938         }
47939         /**
47940          * This is *not* a bi-directional relationship.
47941          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
47942          *
47943          * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T.
47944          * It is used to check following cases:
47945          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
47946          *   - the types of `case` clause expressions and their respective `switch` expressions.
47947          *   - the type of an expression in a type assertion with the type being asserted.
47948          */
47949         function isTypeComparableTo(source, target) {
47950             return isTypeRelatedTo(source, target, comparableRelation);
47951         }
47952         function areTypesComparable(type1, type2) {
47953             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
47954         }
47955         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
47956             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
47957         }
47958         /**
47959          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
47960          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
47961          */
47962         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
47963             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
47964         }
47965         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
47966             if (isTypeRelatedTo(source, target, relation))
47967                 return true;
47968             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47969                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
47970             }
47971             return false;
47972         }
47973         function isOrHasGenericConditional(type) {
47974             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
47975         }
47976         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
47977             if (!node || isOrHasGenericConditional(target))
47978                 return false;
47979             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
47980                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47981                 return true;
47982             }
47983             switch (node.kind) {
47984                 case 276 /* JsxExpression */:
47985                 case 200 /* ParenthesizedExpression */:
47986                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47987                 case 209 /* BinaryExpression */:
47988                     switch (node.operatorToken.kind) {
47989                         case 62 /* EqualsToken */:
47990                         case 27 /* CommaToken */:
47991                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47992                     }
47993                     break;
47994                 case 193 /* ObjectLiteralExpression */:
47995                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
47996                 case 192 /* ArrayLiteralExpression */:
47997                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
47998                 case 274 /* JsxAttributes */:
47999                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
48000                 case 202 /* ArrowFunction */:
48001                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
48002             }
48003             return false;
48004         }
48005         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
48006             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
48007             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
48008             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
48009                 var signatures = _a[_i];
48010                 if (ts.some(signatures, function (s) {
48011                     var returnType = getReturnTypeOfSignature(s);
48012                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
48013                 })) {
48014                     var resultObj = errorOutputContainer || {};
48015                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
48016                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
48017                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
48018                     return true;
48019                 }
48020             }
48021             return false;
48022         }
48023         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48024             // Don't elaborate blocks
48025             if (ts.isBlock(node.body)) {
48026                 return false;
48027             }
48028             // Or functions with annotated parameter types
48029             if (ts.some(node.parameters, ts.hasType)) {
48030                 return false;
48031             }
48032             var sourceSig = getSingleCallSignature(source);
48033             if (!sourceSig) {
48034                 return false;
48035             }
48036             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
48037             if (!ts.length(targetSignatures)) {
48038                 return false;
48039             }
48040             var returnExpression = node.body;
48041             var sourceReturn = getReturnTypeOfSignature(sourceSig);
48042             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
48043             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
48044                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48045                 if (elaborated) {
48046                     return elaborated;
48047                 }
48048                 var resultObj = errorOutputContainer || {};
48049                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
48050                 if (resultObj.errors) {
48051                     if (target.symbol && ts.length(target.symbol.declarations)) {
48052                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
48053                     }
48054                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
48055                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
48056                         // an IPromise and a Promise that are slightly different
48057                         && !getTypeOfPropertyOfType(sourceReturn, "then")
48058                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
48059                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
48060                     }
48061                     return true;
48062                 }
48063             }
48064             return false;
48065         }
48066         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
48067             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
48068             if (idx) {
48069                 return idx;
48070             }
48071             if (target.flags & 1048576 /* Union */) {
48072                 var best = getBestMatchingType(source, target);
48073                 if (best) {
48074                     return getIndexedAccessTypeOrUndefined(best, nameType);
48075                 }
48076             }
48077         }
48078         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
48079             next.contextualType = sourcePropType;
48080             try {
48081                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
48082             }
48083             finally {
48084                 next.contextualType = undefined;
48085             }
48086         }
48087         /**
48088          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
48089          * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError`
48090          * Otherwise, we issue an error on _every_ element which fail the assignability check
48091          */
48092         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
48093             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
48094             var reportedError = false;
48095             for (var status = iterator.next(); !status.done; status = iterator.next()) {
48096                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
48097                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
48098                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
48099                     continue; // Don't elaborate on indexes on generic variables
48100                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
48101                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
48102                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48103                     if (elaborated) {
48104                         reportedError = true;
48105                     }
48106                     else {
48107                         // Issue error on the prop itself, since the prop couldn't elaborate the error
48108                         var resultObj = errorOutputContainer || {};
48109                         // Use the expression type, if available
48110                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
48111                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48112                         if (result && specificSource !== sourcePropType) {
48113                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
48114                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48115                         }
48116                         if (resultObj.errors) {
48117                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
48118                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
48119                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
48120                             var issuedElaboration = false;
48121                             if (!targetProp) {
48122                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
48123                                     getIndexInfoOfType(target, 0 /* String */) ||
48124                                     undefined;
48125                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
48126                                     issuedElaboration = true;
48127                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
48128                                 }
48129                             }
48130                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
48131                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
48132                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
48133                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
48134                                 }
48135                             }
48136                         }
48137                         reportedError = true;
48138                     }
48139                 }
48140             }
48141             return reportedError;
48142         }
48143         function generateJsxAttributes(node) {
48144             var _i, _a, prop;
48145             return __generator(this, function (_b) {
48146                 switch (_b.label) {
48147                     case 0:
48148                         if (!ts.length(node.properties))
48149                             return [2 /*return*/];
48150                         _i = 0, _a = node.properties;
48151                         _b.label = 1;
48152                     case 1:
48153                         if (!(_i < _a.length)) return [3 /*break*/, 4];
48154                         prop = _a[_i];
48155                         if (ts.isJsxSpreadAttribute(prop))
48156                             return [3 /*break*/, 3];
48157                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
48158                     case 2:
48159                         _b.sent();
48160                         _b.label = 3;
48161                     case 3:
48162                         _i++;
48163                         return [3 /*break*/, 1];
48164                     case 4: return [2 /*return*/];
48165                 }
48166             });
48167         }
48168         function generateJsxChildren(node, getInvalidTextDiagnostic) {
48169             var memberOffset, i, child, nameType, elem;
48170             return __generator(this, function (_a) {
48171                 switch (_a.label) {
48172                     case 0:
48173                         if (!ts.length(node.children))
48174                             return [2 /*return*/];
48175                         memberOffset = 0;
48176                         i = 0;
48177                         _a.label = 1;
48178                     case 1:
48179                         if (!(i < node.children.length)) return [3 /*break*/, 5];
48180                         child = node.children[i];
48181                         nameType = getLiteralType(i - memberOffset);
48182                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
48183                         if (!elem) return [3 /*break*/, 3];
48184                         return [4 /*yield*/, elem];
48185                     case 2:
48186                         _a.sent();
48187                         return [3 /*break*/, 4];
48188                     case 3:
48189                         memberOffset++;
48190                         _a.label = 4;
48191                     case 4:
48192                         i++;
48193                         return [3 /*break*/, 1];
48194                     case 5: return [2 /*return*/];
48195                 }
48196             });
48197         }
48198         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
48199             switch (child.kind) {
48200                 case 276 /* JsxExpression */:
48201                     // child is of the type of the expression
48202                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
48203                 case 11 /* JsxText */:
48204                     if (child.containsOnlyTriviaWhiteSpaces) {
48205                         break; // Whitespace only jsx text isn't real jsx text
48206                     }
48207                     // child is a string
48208                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
48209                 case 266 /* JsxElement */:
48210                 case 267 /* JsxSelfClosingElement */:
48211                 case 270 /* JsxFragment */:
48212                     // child is of type JSX.Element
48213                     return { errorNode: child, innerExpression: child, nameType: nameType };
48214                 default:
48215                     return ts.Debug.assertNever(child, "Found invalid jsx child");
48216             }
48217         }
48218         function getSemanticJsxChildren(children) {
48219             return ts.filter(children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
48220         }
48221         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48222             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
48223             var invalidTextDiagnostic;
48224             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
48225                 var containingElement = node.parent.parent;
48226                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48227                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48228                 var childrenNameType = getLiteralType(childrenPropName);
48229                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
48230                 var validChildren = getSemanticJsxChildren(containingElement.children);
48231                 if (!ts.length(validChildren)) {
48232                     return result;
48233                 }
48234                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
48235                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
48236                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
48237                 if (moreThanOneRealChildren) {
48238                     if (arrayLikeTargetParts !== neverType) {
48239                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
48240                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
48241                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
48242                     }
48243                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48244                         // arity mismatch
48245                         result = true;
48246                         var diag = error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType));
48247                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48248                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48249                         }
48250                     }
48251                 }
48252                 else {
48253                     if (nonArrayLikeTargetParts !== neverType) {
48254                         var child = validChildren[0];
48255                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
48256                         if (elem_1) {
48257                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
48258                                 switch (_a.label) {
48259                                     case 0: return [4 /*yield*/, elem_1];
48260                                     case 1:
48261                                         _a.sent();
48262                                         return [2 /*return*/];
48263                                 }
48264                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
48265                         }
48266                     }
48267                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48268                         // arity mismatch
48269                         result = true;
48270                         var diag = error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType));
48271                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48272                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48273                         }
48274                     }
48275                 }
48276             }
48277             return result;
48278             function getInvalidTextualChildDiagnostic() {
48279                 if (!invalidTextDiagnostic) {
48280                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
48281                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48282                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48283                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
48284                     var diagnostic = ts.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;
48285                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
48286                 }
48287                 return invalidTextDiagnostic;
48288             }
48289         }
48290         function generateLimitedTupleElements(node, target) {
48291             var len, i, elem, nameType;
48292             return __generator(this, function (_a) {
48293                 switch (_a.label) {
48294                     case 0:
48295                         len = ts.length(node.elements);
48296                         if (!len)
48297                             return [2 /*return*/];
48298                         i = 0;
48299                         _a.label = 1;
48300                     case 1:
48301                         if (!(i < len)) return [3 /*break*/, 4];
48302                         // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature
48303                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
48304                             return [3 /*break*/, 3];
48305                         elem = node.elements[i];
48306                         if (ts.isOmittedExpression(elem))
48307                             return [3 /*break*/, 3];
48308                         nameType = getLiteralType(i);
48309                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
48310                     case 2:
48311                         _a.sent();
48312                         _a.label = 3;
48313                     case 3:
48314                         i++;
48315                         return [3 /*break*/, 1];
48316                     case 4: return [2 /*return*/];
48317                 }
48318             });
48319         }
48320         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48321             if (target.flags & 131068 /* Primitive */)
48322                 return false;
48323             if (isTupleLikeType(source)) {
48324                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
48325             }
48326             // recreate a tuple from the elements, if possible
48327             // Since we're re-doing the expression type, we need to reapply the contextual type
48328             var oldContext = node.contextualType;
48329             node.contextualType = target;
48330             try {
48331                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
48332                 node.contextualType = oldContext;
48333                 if (isTupleLikeType(tupleizedType)) {
48334                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
48335                 }
48336                 return false;
48337             }
48338             finally {
48339                 node.contextualType = oldContext;
48340             }
48341         }
48342         function generateObjectLiteralElements(node) {
48343             var _i, _a, prop, type, _b;
48344             return __generator(this, function (_c) {
48345                 switch (_c.label) {
48346                     case 0:
48347                         if (!ts.length(node.properties))
48348                             return [2 /*return*/];
48349                         _i = 0, _a = node.properties;
48350                         _c.label = 1;
48351                     case 1:
48352                         if (!(_i < _a.length)) return [3 /*break*/, 8];
48353                         prop = _a[_i];
48354                         if (ts.isSpreadAssignment(prop))
48355                             return [3 /*break*/, 7];
48356                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
48357                         if (!type || (type.flags & 131072 /* Never */)) {
48358                             return [3 /*break*/, 7];
48359                         }
48360                         _b = prop.kind;
48361                         switch (_b) {
48362                             case 164 /* SetAccessor */: return [3 /*break*/, 2];
48363                             case 163 /* GetAccessor */: return [3 /*break*/, 2];
48364                             case 161 /* MethodDeclaration */: return [3 /*break*/, 2];
48365                             case 282 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
48366                             case 281 /* PropertyAssignment */: return [3 /*break*/, 4];
48367                         }
48368                         return [3 /*break*/, 6];
48369                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
48370                     case 3:
48371                         _c.sent();
48372                         return [3 /*break*/, 7];
48373                     case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }];
48374                     case 5:
48375                         _c.sent();
48376                         return [3 /*break*/, 7];
48377                     case 6:
48378                         ts.Debug.assertNever(prop);
48379                         _c.label = 7;
48380                     case 7:
48381                         _i++;
48382                         return [3 /*break*/, 1];
48383                     case 8: return [2 /*return*/];
48384                 }
48385             });
48386         }
48387         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48388             if (target.flags & 131068 /* Primitive */)
48389                 return false;
48390             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
48391         }
48392         /**
48393          * This is *not* a bi-directional relationship.
48394          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
48395          */
48396         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
48397             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
48398         }
48399         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
48400             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
48401             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
48402         }
48403         /**
48404          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
48405          */
48406         function isAnySignature(s) {
48407             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
48408                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
48409                 isTypeAny(getReturnTypeOfSignature(s));
48410         }
48411         /**
48412          * See signatureRelatedTo, compareSignaturesIdentical
48413          */
48414         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
48415             // TODO (drosen): De-duplicate code between related functions.
48416             if (source === target) {
48417                 return -1 /* True */;
48418             }
48419             if (isAnySignature(target)) {
48420                 return -1 /* True */;
48421             }
48422             var targetCount = getParameterCount(target);
48423             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
48424                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
48425             if (sourceHasMoreParameters) {
48426                 return 0 /* False */;
48427             }
48428             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
48429                 target = getCanonicalSignature(target);
48430                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
48431             }
48432             var sourceCount = getParameterCount(source);
48433             var sourceRestType = getNonArrayRestType(source);
48434             var targetRestType = getNonArrayRestType(target);
48435             if (sourceRestType || targetRestType) {
48436                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
48437             }
48438             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
48439                 // We're not able to relate misaligned complex rest parameters
48440                 return 0 /* False */;
48441             }
48442             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
48443             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 161 /* MethodDeclaration */ &&
48444                 kind !== 160 /* MethodSignature */ && kind !== 162 /* Constructor */;
48445             var result = -1 /* True */;
48446             var sourceThisType = getThisTypeOfSignature(source);
48447             if (sourceThisType && sourceThisType !== voidType) {
48448                 var targetThisType = getThisTypeOfSignature(target);
48449                 if (targetThisType) {
48450                     // void sources are assignable to anything.
48451                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
48452                         || compareTypes(targetThisType, sourceThisType, reportErrors);
48453                     if (!related) {
48454                         if (reportErrors) {
48455                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
48456                         }
48457                         return 0 /* False */;
48458                     }
48459                     result &= related;
48460                 }
48461             }
48462             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
48463             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
48464             for (var i = 0; i < paramCount; i++) {
48465                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
48466                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
48467                 // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
48468                 // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
48469                 // they naturally relate only contra-variantly). However, if the source and target parameters both have
48470                 // function types with a single call signature, we know we are relating two callback parameters. In
48471                 // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
48472                 // similar to return values, callback parameters are output positions. This means that a Promise<T>,
48473                 // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
48474                 // with respect to T.
48475                 var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
48476                 var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
48477                 var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
48478                     (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
48479                 var related = callbacks ?
48480                     compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
48481                     !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
48482                 // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
48483                 if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
48484                     related = 0 /* False */;
48485                 }
48486                 if (!related) {
48487                     if (reportErrors) {
48488                         errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
48489                     }
48490                     return 0 /* False */;
48491                 }
48492                 result &= related;
48493             }
48494             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
48495                 // If a signature resolution is already in-flight, skip issuing a circularity error
48496                 // here and just use the `any` type directly
48497                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
48498                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
48499                         : getReturnTypeOfSignature(target);
48500                 if (targetReturnType === voidType) {
48501                     return result;
48502                 }
48503                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
48504                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
48505                         : getReturnTypeOfSignature(source);
48506                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
48507                 var targetTypePredicate = getTypePredicateOfSignature(target);
48508                 if (targetTypePredicate) {
48509                     var sourceTypePredicate = getTypePredicateOfSignature(source);
48510                     if (sourceTypePredicate) {
48511                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
48512                     }
48513                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
48514                         if (reportErrors) {
48515                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
48516                         }
48517                         return 0 /* False */;
48518                     }
48519                 }
48520                 else {
48521                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
48522                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
48523                     // wouldn't be co-variant for T without this rule.
48524                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
48525                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
48526                     if (!result && reportErrors && incompatibleErrorReporter) {
48527                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
48528                     }
48529                 }
48530             }
48531             return result;
48532         }
48533         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
48534             if (source.kind !== target.kind) {
48535                 if (reportErrors) {
48536                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
48537                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48538                 }
48539                 return 0 /* False */;
48540             }
48541             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
48542                 if (source.parameterIndex !== target.parameterIndex) {
48543                     if (reportErrors) {
48544                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
48545                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48546                     }
48547                     return 0 /* False */;
48548                 }
48549             }
48550             var related = source.type === target.type ? -1 /* True */ :
48551                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
48552                     0 /* False */;
48553             if (related === 0 /* False */ && reportErrors) {
48554                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48555             }
48556             return related;
48557         }
48558         function isImplementationCompatibleWithOverload(implementation, overload) {
48559             var erasedSource = getErasedSignature(implementation);
48560             var erasedTarget = getErasedSignature(overload);
48561             // First see if the return types are compatible in either direction.
48562             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
48563             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
48564             if (targetReturnType === voidType
48565                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
48566                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
48567                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
48568             }
48569             return false;
48570         }
48571         function isEmptyResolvedType(t) {
48572             return t !== anyFunctionType &&
48573                 t.properties.length === 0 &&
48574                 t.callSignatures.length === 0 &&
48575                 t.constructSignatures.length === 0 &&
48576                 !t.stringIndexInfo &&
48577                 !t.numberIndexInfo;
48578         }
48579         function isEmptyObjectType(type) {
48580             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
48581                 type.flags & 67108864 /* NonPrimitive */ ? true :
48582                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
48583                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
48584                             false;
48585         }
48586         function isEmptyAnonymousObjectType(type) {
48587             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type);
48588         }
48589         function isStringIndexSignatureOnlyType(type) {
48590             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
48591                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
48592                 false;
48593         }
48594         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
48595             if (sourceSymbol === targetSymbol) {
48596                 return true;
48597             }
48598             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
48599             var entry = enumRelation.get(id);
48600             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
48601                 return !!(entry & 1 /* Succeeded */);
48602             }
48603             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
48604                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48605                 return false;
48606             }
48607             var targetEnumType = getTypeOfSymbol(targetSymbol);
48608             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
48609                 var property = _a[_i];
48610                 if (property.flags & 8 /* EnumMember */) {
48611                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
48612                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
48613                         if (errorReporter) {
48614                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
48615                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48616                         }
48617                         else {
48618                             enumRelation.set(id, 2 /* Failed */);
48619                         }
48620                         return false;
48621                     }
48622                 }
48623             }
48624             enumRelation.set(id, 1 /* Succeeded */);
48625             return true;
48626         }
48627         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
48628             var s = source.flags;
48629             var t = target.flags;
48630             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
48631                 return true;
48632             if (t & 131072 /* Never */)
48633                 return false;
48634             if (s & 132 /* StringLike */ && t & 4 /* String */)
48635                 return true;
48636             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
48637                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48638                 source.value === target.value)
48639                 return true;
48640             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
48641                 return true;
48642             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
48643                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48644                 source.value === target.value)
48645                 return true;
48646             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
48647                 return true;
48648             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
48649                 return true;
48650             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
48651                 return true;
48652             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48653                 return true;
48654             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
48655                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48656                     return true;
48657                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
48658                     source.value === target.value &&
48659                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
48660                     return true;
48661             }
48662             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
48663                 return true;
48664             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
48665                 return true;
48666             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
48667                 return true;
48668             if (relation === assignableRelation || relation === comparableRelation) {
48669                 if (s & 1 /* Any */)
48670                     return true;
48671                 // Type number or any numeric literal type is assignable to any numeric enum type or any
48672                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
48673                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
48674                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
48675                     return true;
48676             }
48677             return false;
48678         }
48679         function isTypeRelatedTo(source, target, relation) {
48680             if (isFreshLiteralType(source)) {
48681                 source = source.regularType;
48682             }
48683             if (isFreshLiteralType(target)) {
48684                 target = target.regularType;
48685             }
48686             if (source === target) {
48687                 return true;
48688             }
48689             if (relation !== identityRelation) {
48690                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
48691                     return true;
48692                 }
48693             }
48694             else {
48695                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
48696                     source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */))
48697                     return false;
48698             }
48699             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
48700                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
48701                 if (related !== undefined) {
48702                     return !!(related & 1 /* Succeeded */);
48703                 }
48704             }
48705             if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
48706                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
48707             }
48708             return false;
48709         }
48710         function isIgnoredJsxProperty(source, sourceProp) {
48711             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
48712         }
48713         function getNormalizedType(type, writing) {
48714             while (true) {
48715                 var t = isFreshLiteralType(type) ? type.regularType :
48716                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
48717                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
48718                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
48719                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
48720                                     type;
48721                 if (t === type)
48722                     break;
48723                 type = t;
48724             }
48725             return type;
48726         }
48727         /**
48728          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
48729          * @param source The left-hand-side of the relation.
48730          * @param target The right-hand-side of the relation.
48731          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
48732          * Used as both to determine which checks are performed and as a cache of previously computed results.
48733          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
48734          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
48735          * @param containingMessageChain A chain of errors to prepend any new errors found.
48736          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
48737          */
48738         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
48739             var errorInfo;
48740             var relatedInfo;
48741             var maybeKeys;
48742             var sourceStack;
48743             var targetStack;
48744             var maybeCount = 0;
48745             var depth = 0;
48746             var expandingFlags = 0 /* None */;
48747             var overflow = false;
48748             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
48749             var lastSkippedInfo;
48750             var incompatibleStack = [];
48751             var inPropertyCheck = false;
48752             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
48753             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
48754             if (incompatibleStack.length) {
48755                 reportIncompatibleStack();
48756             }
48757             if (overflow) {
48758                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
48759                 if (errorOutputContainer) {
48760                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48761                 }
48762             }
48763             else if (errorInfo) {
48764                 if (containingMessageChain) {
48765                     var chain = containingMessageChain();
48766                     if (chain) {
48767                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
48768                         errorInfo = chain;
48769                     }
48770                 }
48771                 var relatedInformation = void 0;
48772                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
48773                 if (headMessage && errorNode && !result && source.symbol) {
48774                     var links = getSymbolLinks(source.symbol);
48775                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
48776                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
48777                         if (helpfulRetry) {
48778                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
48779                             var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.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);
48780                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
48781                         }
48782                     }
48783                 }
48784                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
48785                 if (relatedInfo) {
48786                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
48787                 }
48788                 if (errorOutputContainer) {
48789                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48790                 }
48791                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
48792                     diagnostics.add(diag);
48793                 }
48794             }
48795             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
48796                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
48797             }
48798             return result !== 0 /* False */;
48799             function resetErrorInfo(saved) {
48800                 errorInfo = saved.errorInfo;
48801                 lastSkippedInfo = saved.lastSkippedInfo;
48802                 incompatibleStack = saved.incompatibleStack;
48803                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
48804                 relatedInfo = saved.relatedInfo;
48805             }
48806             function captureErrorCalculationState() {
48807                 return {
48808                     errorInfo: errorInfo,
48809                     lastSkippedInfo: lastSkippedInfo,
48810                     incompatibleStack: incompatibleStack.slice(),
48811                     overrideNextErrorInfo: overrideNextErrorInfo,
48812                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
48813                 };
48814             }
48815             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
48816                 overrideNextErrorInfo++; // Suppress the next relation error
48817                 lastSkippedInfo = undefined; // Reset skipped info cache
48818                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
48819             }
48820             function reportIncompatibleStack() {
48821                 var stack = incompatibleStack;
48822                 incompatibleStack = [];
48823                 var info = lastSkippedInfo;
48824                 lastSkippedInfo = undefined;
48825                 if (stack.length === 1) {
48826                     reportError.apply(void 0, stack[0]);
48827                     if (info) {
48828                         // Actually do the last relation error
48829                         reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48830                     }
48831                     return;
48832                 }
48833                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
48834                 // we can build from left to right
48835                 var path = "";
48836                 var secondaryRootErrors = [];
48837                 while (stack.length) {
48838                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
48839                     switch (msg.code) {
48840                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
48841                             // Parenthesize a `new` if there is one
48842                             if (path.indexOf("new ") === 0) {
48843                                 path = "(" + path + ")";
48844                             }
48845                             var str = "" + args[0];
48846                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
48847                             if (path.length === 0) {
48848                                 path = "" + str;
48849                             }
48850                             // Otherwise write a dotted name if possible
48851                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
48852                                 path = path + "." + str;
48853                             }
48854                             // Failing that, check if the name is already a computed name
48855                             else if (str[0] === "[" && str[str.length - 1] === "]") {
48856                                 path = "" + path + str;
48857                             }
48858                             // And finally write out a computed name as a last resort
48859                             else {
48860                                 path = path + "[" + str + "]";
48861                             }
48862                             break;
48863                         }
48864                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
48865                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
48866                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
48867                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
48868                             if (path.length === 0) {
48869                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
48870                                 // to unify (the with no arguments bit is excessive for printback) and print them back
48871                                 var mappedMsg = msg;
48872                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48873                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
48874                                 }
48875                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48876                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
48877                                 }
48878                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
48879                             }
48880                             else {
48881                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
48882                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48883                                     ? "new "
48884                                     : "";
48885                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
48886                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48887                                     ? ""
48888                                     : "...";
48889                                 path = "" + prefix + path + "(" + params + ")";
48890                             }
48891                             break;
48892                         }
48893                         default:
48894                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
48895                     }
48896                 }
48897                 if (path) {
48898                     reportError(path[path.length - 1] === ")"
48899                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
48900                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
48901                 }
48902                 else {
48903                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
48904                     secondaryRootErrors.shift();
48905                 }
48906                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
48907                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
48908                     var originalValue = msg.elidedInCompatabilityPyramid;
48909                     msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
48910                     reportError.apply(void 0, __spreadArrays([msg], args));
48911                     msg.elidedInCompatabilityPyramid = originalValue;
48912                 }
48913                 if (info) {
48914                     // Actually do the last relation error
48915                     reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48916                 }
48917             }
48918             function reportError(message, arg0, arg1, arg2, arg3) {
48919                 ts.Debug.assert(!!errorNode);
48920                 if (incompatibleStack.length)
48921                     reportIncompatibleStack();
48922                 if (message.elidedInCompatabilityPyramid)
48923                     return;
48924                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
48925             }
48926             function associateRelatedInfo(info) {
48927                 ts.Debug.assert(!!errorInfo);
48928                 if (!relatedInfo) {
48929                     relatedInfo = [info];
48930                 }
48931                 else {
48932                     relatedInfo.push(info);
48933                 }
48934             }
48935             function reportRelationError(message, source, target) {
48936                 if (incompatibleStack.length)
48937                     reportIncompatibleStack();
48938                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
48939                 if (target.flags & 262144 /* TypeParameter */) {
48940                     var constraint = getBaseConstraintOfType(target);
48941                     var constraintElab = constraint && isTypeAssignableTo(source, constraint);
48942                     if (constraintElab) {
48943                         reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, sourceType, targetType, typeToString(constraint));
48944                     }
48945                     else {
48946                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, sourceType);
48947                     }
48948                 }
48949                 if (!message) {
48950                     if (relation === comparableRelation) {
48951                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
48952                     }
48953                     else if (sourceType === targetType) {
48954                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
48955                     }
48956                     else {
48957                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
48958                     }
48959                 }
48960                 reportError(message, sourceType, targetType);
48961             }
48962             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
48963                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
48964                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
48965                 if ((globalStringType === source && stringType === target) ||
48966                     (globalNumberType === source && numberType === target) ||
48967                     (globalBooleanType === source && booleanType === target) ||
48968                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
48969                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
48970                 }
48971             }
48972             /**
48973              * Try and elaborate array and tuple errors. Returns false
48974              * if we have found an elaboration, or we should ignore
48975              * any other elaborations when relating the `source` and
48976              * `target` types.
48977              */
48978             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
48979                 /**
48980                  * The spec for elaboration is:
48981                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48982                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
48983                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48984                  * - If the source an array then skip property elaborations if the target is a tuple.
48985                  */
48986                 if (isTupleType(source)) {
48987                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
48988                         if (reportErrors) {
48989                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48990                         }
48991                         return false;
48992                     }
48993                     return isTupleType(target) || isArrayType(target);
48994                 }
48995                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
48996                     if (reportErrors) {
48997                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48998                     }
48999                     return false;
49000                 }
49001                 if (isTupleType(target)) {
49002                     return isArrayType(source);
49003                 }
49004                 return true;
49005             }
49006             /**
49007              * Compare two types and return
49008              * * Ternary.True if they are related with no assumptions,
49009              * * Ternary.Maybe if they are related with assumptions of other relationships, or
49010              * * Ternary.False if they are not related.
49011              */
49012             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
49013                 if (reportErrors === void 0) { reportErrors = false; }
49014                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
49015                 // Before normalization: if `source` is type an object type, and `target` is primitive,
49016                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
49017                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
49018                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
49019                         return -1 /* True */;
49020                     }
49021                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
49022                     return 0 /* False */;
49023                 }
49024                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
49025                 // turn deferred type references into regular type references, simplify indexed access and
49026                 // conditional types, and resolve substitution types to either the substitution (on the source
49027                 // side) or the type variable (on the target side).
49028                 var source = getNormalizedType(originalSource, /*writing*/ false);
49029                 var target = getNormalizedType(originalTarget, /*writing*/ true);
49030                 if (source === target)
49031                     return -1 /* True */;
49032                 if (relation === identityRelation) {
49033                     return isIdenticalTo(source, target);
49034                 }
49035                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
49036                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
49037                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
49038                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
49039                 // the target is exactly the constraint.
49040                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
49041                     return -1 /* True */;
49042                 }
49043                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
49044                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
49045                 // First, see if we're even relating an object type to a union.
49046                 // Then see if the target is stripped down to a single non-union type.
49047                 // Note
49048                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
49049                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
49050                 //    when dealing with generics.
49051                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
49052                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
49053                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
49054                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
49055                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
49056                         if (source === nullStrippedTarget)
49057                             return -1 /* True */;
49058                         target = nullStrippedTarget;
49059                     }
49060                 }
49061                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
49062                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
49063                     return -1 /* True */;
49064                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49065                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
49066                 if (isPerformingExcessPropertyChecks) {
49067                     if (hasExcessProperties(source, target, reportErrors)) {
49068                         if (reportErrors) {
49069                             reportRelationError(headMessage, source, target);
49070                         }
49071                         return 0 /* False */;
49072                     }
49073                 }
49074                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
49075                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
49076                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
49077                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
49078                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
49079                     if (reportErrors) {
49080                         var calls = getSignaturesOfType(source, 0 /* Call */);
49081                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
49082                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
49083                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
49084                             reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target));
49085                         }
49086                         else {
49087                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
49088                         }
49089                     }
49090                     return 0 /* False */;
49091                 }
49092                 var result = 0 /* False */;
49093                 var saveErrorInfo = captureErrorCalculationState();
49094                 // Note that these checks are specifically ordered to produce correct results. In particular,
49095                 // we need to deconstruct unions before intersections (because unions are always at the top),
49096                 // and we need to handle "each" relations before "some" relations for the same kind of type.
49097                 if (source.flags & 1048576 /* Union */) {
49098                     result = relation === comparableRelation ?
49099                         someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
49100                         eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
49101                 }
49102                 else {
49103                     if (target.flags & 1048576 /* Union */) {
49104                         result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
49105                     }
49106                     else if (target.flags & 2097152 /* Intersection */) {
49107                         result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
49108                     }
49109                     else if (source.flags & 2097152 /* Intersection */) {
49110                         // Check to see if any constituents of the intersection are immediately related to the target.
49111                         //
49112                         // Don't report errors though. Checking whether a constituent is related to the source is not actually
49113                         // useful and leads to some confusing error messages. Instead it is better to let the below checks
49114                         // take care of this, or to not elaborate at all. For instance,
49115                         //
49116                         //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
49117                         //
49118                         //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
49119                         //          than to report that 'D' is not assignable to 'A' or 'B'.
49120                         //
49121                         //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
49122                         //          breaking the intersection apart.
49123                         result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
49124                     }
49125                     if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
49126                         if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
49127                             resetErrorInfo(saveErrorInfo);
49128                         }
49129                     }
49130                 }
49131                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
49132                     // The combined constraint of an intersection type is the intersection of the constraints of
49133                     // the constituents. When an intersection type contains instantiable types with union type
49134                     // constraints, there are situations where we need to examine the combined constraint. One is
49135                     // when the target is a union type. Another is when the intersection contains types belonging
49136                     // to one of the disjoint domains. For example, given type variables T and U, each with the
49137                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
49138                     // we need to check this constraint against a union on the target side. Also, given a type
49139                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
49140                     // 'string & number | number & number' which reduces to just 'number'.
49141                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
49142                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
49143                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
49144                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
49145                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
49146                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
49147                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
49148                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
49149                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49150                                 resetErrorInfo(saveErrorInfo);
49151                             }
49152                         }
49153                     }
49154                 }
49155                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
49156                 // an extra property check where the intersection is viewed as a single object. The following are motivating
49157                 // examples that all should be errors, but aren't without this extra property check:
49158                 //
49159                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
49160                 //
49161                 //   declare let wrong: { a: { y: string } };
49162                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
49163                 //
49164                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
49165                 //     x = y;  // Mismatched property in source intersection
49166                 //   }
49167                 //
49168                 // We suppress recursive intersection property checks because they can generate lots of work when relating
49169                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
49170                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
49171                     isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) {
49172                     inPropertyCheck = true;
49173                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
49174                     inPropertyCheck = false;
49175                 }
49176                 reportErrorResults(source, target, result, isComparingJsxAttributes);
49177                 return result;
49178                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
49179                     if (!result && reportErrors) {
49180                         source = originalSource.aliasSymbol ? originalSource : source;
49181                         target = originalTarget.aliasSymbol ? originalTarget : target;
49182                         var maybeSuppress = overrideNextErrorInfo > 0;
49183                         if (maybeSuppress) {
49184                             overrideNextErrorInfo--;
49185                         }
49186                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
49187                             var currentError = errorInfo;
49188                             tryElaborateArrayLikeErrors(source, target, reportErrors);
49189                             if (errorInfo !== currentError) {
49190                                 maybeSuppress = !!errorInfo;
49191                             }
49192                         }
49193                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
49194                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
49195                         }
49196                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
49197                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
49198                         }
49199                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
49200                             var targetTypes = target.types;
49201                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
49202                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
49203                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
49204                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
49205                                 // do not report top error
49206                                 return result;
49207                             }
49208                         }
49209                         else {
49210                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
49211                         }
49212                         if (!headMessage && maybeSuppress) {
49213                             lastSkippedInfo = [source, target];
49214                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
49215                             return result;
49216                         }
49217                         reportRelationError(headMessage, source, target);
49218                     }
49219                 }
49220             }
49221             function isIdenticalTo(source, target) {
49222                 var flags = source.flags & target.flags;
49223                 if (!(flags & 66584576 /* Substructure */)) {
49224                     return 0 /* False */;
49225                 }
49226                 if (flags & 3145728 /* UnionOrIntersection */) {
49227                     var result_5 = eachTypeRelatedToSomeType(source, target);
49228                     if (result_5) {
49229                         result_5 &= eachTypeRelatedToSomeType(target, source);
49230                     }
49231                     return result_5;
49232                 }
49233                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
49234             }
49235             function getTypeOfPropertyInTypes(types, name) {
49236                 var appendPropType = function (propTypes, type) {
49237                     type = getApparentType(type);
49238                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
49239                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
49240                     return ts.append(propTypes, propType);
49241                 };
49242                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
49243             }
49244             function hasExcessProperties(source, target, reportErrors) {
49245                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
49246                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
49247                 }
49248                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49249                 if ((relation === assignableRelation || relation === comparableRelation) &&
49250                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
49251                     return false;
49252                 }
49253                 var reducedTarget = target;
49254                 var checkTypes;
49255                 if (target.flags & 1048576 /* Union */) {
49256                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
49257                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
49258                 }
49259                 var _loop_13 = function (prop) {
49260                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
49261                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
49262                             if (reportErrors) {
49263                                 // Report error in terms of object types in the target as those are the only ones
49264                                 // we check in isKnownProperty.
49265                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
49266                                 // We know *exactly* where things went wrong when comparing the types.
49267                                 // Use this property as the error node as this will be more helpful in
49268                                 // reasoning about what went wrong.
49269                                 if (!errorNode)
49270                                     return { value: ts.Debug.fail() };
49271                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
49272                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
49273                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
49274                                     // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages)
49275                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
49276                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
49277                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
49278                                         errorNode = prop.valueDeclaration.name;
49279                                     }
49280                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget));
49281                                 }
49282                                 else {
49283                                     // use the property's value declaration if the property is assigned inside the literal itself
49284                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
49285                                     var suggestion = void 0;
49286                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
49287                                         var propDeclaration = prop.valueDeclaration;
49288                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
49289                                         errorNode = propDeclaration;
49290                                         var name = propDeclaration.name;
49291                                         if (ts.isIdentifier(name)) {
49292                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
49293                                         }
49294                                     }
49295                                     if (suggestion !== undefined) {
49296                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion);
49297                                     }
49298                                     else {
49299                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
49300                                     }
49301                                 }
49302                             }
49303                             return { value: true };
49304                         }
49305                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
49306                             if (reportErrors) {
49307                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
49308                             }
49309                             return { value: true };
49310                         }
49311                     }
49312                 };
49313                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
49314                     var prop = _a[_i];
49315                     var state_5 = _loop_13(prop);
49316                     if (typeof state_5 === "object")
49317                         return state_5.value;
49318                 }
49319                 return false;
49320             }
49321             function shouldCheckAsExcessProperty(prop, container) {
49322                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
49323             }
49324             function eachTypeRelatedToSomeType(source, target) {
49325                 var result = -1 /* True */;
49326                 var sourceTypes = source.types;
49327                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
49328                     var sourceType = sourceTypes_1[_i];
49329                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
49330                     if (!related) {
49331                         return 0 /* False */;
49332                     }
49333                     result &= related;
49334                 }
49335                 return result;
49336             }
49337             function typeRelatedToSomeType(source, target, reportErrors) {
49338                 var targetTypes = target.types;
49339                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
49340                     return -1 /* True */;
49341                 }
49342                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
49343                     var type = targetTypes_1[_i];
49344                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
49345                     if (related) {
49346                         return related;
49347                     }
49348                 }
49349                 if (reportErrors) {
49350                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
49351                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
49352                 }
49353                 return 0 /* False */;
49354             }
49355             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
49356                 var result = -1 /* True */;
49357                 var targetTypes = target.types;
49358                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
49359                     var targetType = targetTypes_2[_i];
49360                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
49361                     if (!related) {
49362                         return 0 /* False */;
49363                     }
49364                     result &= related;
49365                 }
49366                 return result;
49367             }
49368             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
49369                 var sourceTypes = source.types;
49370                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
49371                     return -1 /* True */;
49372                 }
49373                 var len = sourceTypes.length;
49374                 for (var i = 0; i < len; i++) {
49375                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
49376                     if (related) {
49377                         return related;
49378                     }
49379                 }
49380                 return 0 /* False */;
49381             }
49382             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
49383                 var result = -1 /* True */;
49384                 var sourceTypes = source.types;
49385                 for (var i = 0; i < sourceTypes.length; i++) {
49386                     var sourceType = sourceTypes[i];
49387                     if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
49388                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
49389                         var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
49390                         if (related_1) {
49391                             result &= related_1;
49392                             continue;
49393                         }
49394                     }
49395                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
49396                     if (!related) {
49397                         return 0 /* False */;
49398                     }
49399                     result &= related;
49400                 }
49401                 return result;
49402             }
49403             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
49404                 if (sources === void 0) { sources = ts.emptyArray; }
49405                 if (targets === void 0) { targets = ts.emptyArray; }
49406                 if (variances === void 0) { variances = ts.emptyArray; }
49407                 if (sources.length !== targets.length && relation === identityRelation) {
49408                     return 0 /* False */;
49409                 }
49410                 var length = sources.length <= targets.length ? sources.length : targets.length;
49411                 var result = -1 /* True */;
49412                 for (var i = 0; i < length; i++) {
49413                     // When variance information isn't available we default to covariance. This happens
49414                     // in the process of computing variance information for recursive types and when
49415                     // comparing 'this' type arguments.
49416                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
49417                     var variance = varianceFlags & 7 /* VarianceMask */;
49418                     // We ignore arguments for independent type parameters (because they're never witnessed).
49419                     if (variance !== 4 /* Independent */) {
49420                         var s = sources[i];
49421                         var t = targets[i];
49422                         var related = -1 /* True */;
49423                         if (varianceFlags & 8 /* Unmeasurable */) {
49424                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
49425                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
49426                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
49427                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
49428                         }
49429                         else if (variance === 1 /* Covariant */) {
49430                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49431                         }
49432                         else if (variance === 2 /* Contravariant */) {
49433                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49434                         }
49435                         else if (variance === 3 /* Bivariant */) {
49436                             // In the bivariant case we first compare contravariantly without reporting
49437                             // errors. Then, if that doesn't succeed, we compare covariantly with error
49438                             // reporting. Thus, error elaboration will be based on the the covariant check,
49439                             // which is generally easier to reason about.
49440                             related = isRelatedTo(t, s, /*reportErrors*/ false);
49441                             if (!related) {
49442                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49443                             }
49444                         }
49445                         else {
49446                             // In the invariant case we first compare covariantly, and only when that
49447                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
49448                             // will typically be based on the covariant check.
49449                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49450                             if (related) {
49451                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49452                             }
49453                         }
49454                         if (!related) {
49455                             return 0 /* False */;
49456                         }
49457                         result &= related;
49458                     }
49459                 }
49460                 return result;
49461             }
49462             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
49463             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
49464             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
49465             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
49466             // and issue an error. Otherwise, actually compare the structure of the two types.
49467             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
49468                 if (overflow) {
49469                     return 0 /* False */;
49470                 }
49471                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
49472                 var entry = relation.get(id);
49473                 if (entry !== undefined) {
49474                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
49475                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
49476                         // as a failure, and should be updated as a reported failure by the bottom of this function.
49477                     }
49478                     else {
49479                         if (outofbandVarianceMarkerHandler) {
49480                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
49481                             var saved = entry & 24 /* ReportsMask */;
49482                             if (saved & 8 /* ReportsUnmeasurable */) {
49483                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
49484                             }
49485                             if (saved & 16 /* ReportsUnreliable */) {
49486                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
49487                             }
49488                         }
49489                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
49490                     }
49491                 }
49492                 if (!maybeKeys) {
49493                     maybeKeys = [];
49494                     sourceStack = [];
49495                     targetStack = [];
49496                 }
49497                 else {
49498                     for (var i = 0; i < maybeCount; i++) {
49499                         // If source and target are already being compared, consider them related with assumptions
49500                         if (id === maybeKeys[i]) {
49501                             return 1 /* Maybe */;
49502                         }
49503                     }
49504                     if (depth === 100) {
49505                         overflow = true;
49506                         return 0 /* False */;
49507                     }
49508                 }
49509                 var maybeStart = maybeCount;
49510                 maybeKeys[maybeCount] = id;
49511                 maybeCount++;
49512                 sourceStack[depth] = source;
49513                 targetStack[depth] = target;
49514                 depth++;
49515                 var saveExpandingFlags = expandingFlags;
49516                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
49517                     expandingFlags |= 1 /* Source */;
49518                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
49519                     expandingFlags |= 2 /* Target */;
49520                 var originalHandler;
49521                 var propagatingVarianceFlags = 0;
49522                 if (outofbandVarianceMarkerHandler) {
49523                     originalHandler = outofbandVarianceMarkerHandler;
49524                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
49525                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
49526                         return originalHandler(onlyUnreliable);
49527                     };
49528                 }
49529                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 1 /* Maybe */;
49530                 if (outofbandVarianceMarkerHandler) {
49531                     outofbandVarianceMarkerHandler = originalHandler;
49532                 }
49533                 expandingFlags = saveExpandingFlags;
49534                 depth--;
49535                 if (result) {
49536                     if (result === -1 /* True */ || depth === 0) {
49537                         // If result is definitely true, record all maybe keys as having succeeded
49538                         for (var i = maybeStart; i < maybeCount; i++) {
49539                             relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
49540                         }
49541                         maybeCount = maybeStart;
49542                     }
49543                 }
49544                 else {
49545                     // A false result goes straight into global cache (when something is false under
49546                     // assumptions it will also be false without assumptions)
49547                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
49548                     maybeCount = maybeStart;
49549                 }
49550                 return result;
49551             }
49552             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
49553                 if (intersectionState & 4 /* PropertyCheck */) {
49554                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
49555                 }
49556                 var flags = source.flags & target.flags;
49557                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
49558                     if (flags & 4194304 /* Index */) {
49559                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
49560                     }
49561                     var result_6 = 0 /* False */;
49562                     if (flags & 8388608 /* IndexedAccess */) {
49563                         if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
49564                             if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
49565                                 return result_6;
49566                             }
49567                         }
49568                     }
49569                     if (flags & 16777216 /* Conditional */) {
49570                         if (source.root.isDistributive === target.root.isDistributive) {
49571                             if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
49572                                 if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
49573                                     if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
49574                                         if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
49575                                             return result_6;
49576                                         }
49577                                     }
49578                                 }
49579                             }
49580                         }
49581                     }
49582                     if (flags & 33554432 /* Substitution */) {
49583                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
49584                     }
49585                     return 0 /* False */;
49586                 }
49587                 var result;
49588                 var originalErrorInfo;
49589                 var varianceCheckFailed = false;
49590                 var saveErrorInfo = captureErrorCalculationState();
49591                 // We limit alias variance probing to only object and conditional types since their alias behavior
49592                 // is more predictable than other, interned types, which may or may not have an alias depending on
49593                 // the order in which things were checked.
49594                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
49595                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
49596                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
49597                     var variances = getAliasVariances(source.aliasSymbol);
49598                     if (variances === ts.emptyArray) {
49599                         return 1 /* Maybe */;
49600                     }
49601                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
49602                     if (varianceResult !== undefined) {
49603                         return varianceResult;
49604                     }
49605                 }
49606                 if (target.flags & 262144 /* TypeParameter */) {
49607                     // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
49608                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
49609                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
49610                             var templateType = getTemplateTypeFromMappedType(source);
49611                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
49612                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
49613                                 return result;
49614                             }
49615                         }
49616                     }
49617                 }
49618                 else if (target.flags & 4194304 /* Index */) {
49619                     // A keyof S is related to a keyof T if T is related to S.
49620                     if (source.flags & 4194304 /* Index */) {
49621                         if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
49622                             return result;
49623                         }
49624                     }
49625                     // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
49626                     // simplified form of T or, if T doesn't simplify, the constraint of T.
49627                     var constraint = getSimplifiedTypeOrConstraint(target.type);
49628                     if (constraint) {
49629                         // We require Ternary.True here such that circular constraints don't cause
49630                         // false positives. For example, given 'T extends { [K in keyof T]: string }',
49631                         // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
49632                         // related to other types.
49633                         if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
49634                             return -1 /* True */;
49635                         }
49636                     }
49637                 }
49638                 else if (target.flags & 8388608 /* IndexedAccess */) {
49639                     // A type S is related to a type T[K] if S is related to C, where C is the base
49640                     // constraint of T[K] for writing.
49641                     if (relation !== identityRelation) {
49642                         var objectType = target.objectType;
49643                         var indexType = target.indexType;
49644                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
49645                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
49646                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
49647                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
49648                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, accessFlags);
49649                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
49650                                 return result;
49651                             }
49652                         }
49653                     }
49654                 }
49655                 else if (isGenericMappedType(target)) {
49656                     // A source type T is related to a target type { [P in X]: T[P] }
49657                     var template = getTemplateTypeFromMappedType(target);
49658                     var modifiers = getMappedTypeModifiers(target);
49659                     if (!(modifiers & 8 /* ExcludeOptional */)) {
49660                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
49661                             template.indexType === getTypeParameterFromMappedType(target)) {
49662                             return -1 /* True */;
49663                         }
49664                         if (!isGenericMappedType(source)) {
49665                             var targetConstraint = getConstraintTypeFromMappedType(target);
49666                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
49667                             var includeOptional = modifiers & 4 /* IncludeOptional */;
49668                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
49669                             // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
49670                             // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
49671                             if (includeOptional
49672                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
49673                                 : isRelatedTo(targetConstraint, sourceKeys)) {
49674                                 var typeParameter = getTypeParameterFromMappedType(target);
49675                                 var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
49676                                 var indexedAccessType = getIndexedAccessType(source, indexingType);
49677                                 var templateType = getTemplateTypeFromMappedType(target);
49678                                 if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
49679                                     return result;
49680                                 }
49681                             }
49682                             originalErrorInfo = errorInfo;
49683                             resetErrorInfo(saveErrorInfo);
49684                         }
49685                     }
49686                 }
49687                 if (source.flags & 8650752 /* TypeVariable */) {
49688                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
49689                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
49690                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
49691                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
49692                         }
49693                         if (result) {
49694                             resetErrorInfo(saveErrorInfo);
49695                             return result;
49696                         }
49697                     }
49698                     else {
49699                         var constraint = getConstraintOfType(source);
49700                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
49701                             // A type variable with no constraint is not related to the non-primitive object type.
49702                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
49703                                 resetErrorInfo(saveErrorInfo);
49704                                 return result;
49705                             }
49706                         }
49707                         // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed
49708                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49709                             resetErrorInfo(saveErrorInfo);
49710                             return result;
49711                         }
49712                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
49713                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
49714                             resetErrorInfo(saveErrorInfo);
49715                             return result;
49716                         }
49717                     }
49718                 }
49719                 else if (source.flags & 4194304 /* Index */) {
49720                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
49721                         resetErrorInfo(saveErrorInfo);
49722                         return result;
49723                     }
49724                 }
49725                 else if (source.flags & 16777216 /* Conditional */) {
49726                     if (target.flags & 16777216 /* Conditional */) {
49727                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
49728                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
49729                         // and Y1 is related to Y2.
49730                         var sourceParams = source.root.inferTypeParameters;
49731                         var sourceExtends = source.extendsType;
49732                         var mapper = void 0;
49733                         if (sourceParams) {
49734                             // If the source has infer type parameters, we instantiate them in the context of the target
49735                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
49736                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
49737                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
49738                             mapper = ctx.mapper;
49739                         }
49740                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
49741                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
49742                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
49743                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
49744                             }
49745                             if (result) {
49746                                 resetErrorInfo(saveErrorInfo);
49747                                 return result;
49748                             }
49749                         }
49750                     }
49751                     else {
49752                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
49753                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
49754                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
49755                         if (distributiveConstraint) {
49756                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
49757                                 resetErrorInfo(saveErrorInfo);
49758                                 return result;
49759                             }
49760                         }
49761                     }
49762                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
49763                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
49764                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
49765                     if (defaultConstraint) {
49766                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
49767                             resetErrorInfo(saveErrorInfo);
49768                             return result;
49769                         }
49770                     }
49771                 }
49772                 else {
49773                     // An empty object type is related to any mapped type that includes a '?' modifier.
49774                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
49775                         return -1 /* True */;
49776                     }
49777                     if (isGenericMappedType(target)) {
49778                         if (isGenericMappedType(source)) {
49779                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
49780                                 resetErrorInfo(saveErrorInfo);
49781                                 return result;
49782                             }
49783                         }
49784                         return 0 /* False */;
49785                     }
49786                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
49787                     if (relation !== identityRelation) {
49788                         source = getApparentType(source);
49789                     }
49790                     else if (isGenericMappedType(source)) {
49791                         return 0 /* False */;
49792                     }
49793                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
49794                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
49795                         // We have type references to the same generic type, and the type references are not marker
49796                         // type references (which are intended by be compared structurally). Obtain the variance
49797                         // information for the type parameters and relate the type arguments accordingly.
49798                         var variances = getVariances(source.target);
49799                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
49800                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
49801                         // recursive instantiations of the generic type.
49802                         if (variances === ts.emptyArray) {
49803                             return 1 /* Maybe */;
49804                         }
49805                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
49806                         if (varianceResult !== undefined) {
49807                             return varianceResult;
49808                         }
49809                     }
49810                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
49811                         if (relation !== identityRelation) {
49812                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
49813                         }
49814                         else {
49815                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
49816                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
49817                             return 0 /* False */;
49818                         }
49819                     }
49820                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
49821                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
49822                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
49823                         return 0 /* False */;
49824                     }
49825                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
49826                     // it may hold in a structural comparison.
49827                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
49828                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
49829                     // relates to X. Thus, we include intersection types on the source side here.
49830                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
49831                         // Report structural errors only if we haven't reported any errors yet
49832                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
49833                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
49834                         if (result) {
49835                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
49836                             if (result) {
49837                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
49838                                 if (result) {
49839                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49840                                     if (result) {
49841                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49842                                     }
49843                                 }
49844                             }
49845                         }
49846                         if (varianceCheckFailed && result) {
49847                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
49848                         }
49849                         else if (result) {
49850                             return result;
49851                         }
49852                     }
49853                     // If S is an object type and T is a discriminated union, S may be related to T if
49854                     // there exists a constituent of T for every combination of the discriminants of S
49855                     // with respect to T. We do not report errors here, as we will use the existing
49856                     // error result from checking each constituent of the union.
49857                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
49858                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
49859                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
49860                             var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
49861                             if (result_7) {
49862                                 return result_7;
49863                             }
49864                         }
49865                     }
49866                 }
49867                 return 0 /* False */;
49868                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
49869                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
49870                         return result;
49871                     }
49872                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
49873                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
49874                         // have to allow a structural fallback check
49875                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
49876                         // be assuming identity of the type parameter.
49877                         originalErrorInfo = undefined;
49878                         resetErrorInfo(saveErrorInfo);
49879                         return undefined;
49880                     }
49881                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
49882                     varianceCheckFailed = !allowStructuralFallback;
49883                     // The type arguments did not relate appropriately, but it may be because we have no variance
49884                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
49885                     // arguments). It might also be the case that the target type has a 'void' type argument for
49886                     // a covariant type parameter that is only used in return positions within the generic type
49887                     // (in which case any type argument is permitted on the source side). In those cases we proceed
49888                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
49889                     // related and we can return here.
49890                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
49891                         // In some cases generic types that are covariant in regular type checking mode become
49892                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
49893                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
49894                         // types are invariant, if any of the type parameters are invariant we reset the reported
49895                         // errors and instead force a structural comparison (which will include elaborations that
49896                         // reveal the reason).
49897                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
49898                         // we can return `False` early here to skip calculating the structural error message we don't need.
49899                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
49900                             return 0 /* False */;
49901                         }
49902                         // We remember the original error information so we can restore it in case the structural
49903                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
49904                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
49905                         originalErrorInfo = errorInfo;
49906                         resetErrorInfo(saveErrorInfo);
49907                     }
49908                 }
49909             }
49910             function reportUnmeasurableMarkers(p) {
49911                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49912                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
49913                 }
49914                 return p;
49915             }
49916             function reportUnreliableMarkers(p) {
49917                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49918                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
49919                 }
49920                 return p;
49921             }
49922             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
49923             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
49924             // that S and T are contra-variant whereas X and Y are co-variant.
49925             function mappedTypeRelatedTo(source, target, reportErrors) {
49926                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
49927                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
49928                 if (modifiersRelated) {
49929                     var result_8;
49930                     var targetConstraint = getConstraintTypeFromMappedType(target);
49931                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
49932                     if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
49933                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
49934                         return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
49935                     }
49936                 }
49937                 return 0 /* False */;
49938             }
49939             function typeRelatedToDiscriminatedType(source, target) {
49940                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
49941                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
49942                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
49943                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
49944                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
49945                 //    'target' are related to a property in 'source'.
49946                 //
49947                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
49948                 //       for examples.
49949                 var sourceProperties = getPropertiesOfType(source);
49950                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
49951                 if (!sourcePropertiesFiltered)
49952                     return 0 /* False */;
49953                 // Though we could compute the number of combinations as we generate
49954                 // the matrix, this would incur additional memory overhead due to
49955                 // array allocations. To reduce this overhead, we first compute
49956                 // the number of combinations to ensure we will not surpass our
49957                 // fixed limit before incurring the cost of any allocations:
49958                 var numCombinations = 1;
49959                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
49960                     var sourceProperty = sourcePropertiesFiltered_1[_i];
49961                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
49962                     if (numCombinations > 25) {
49963                         // We've reached the complexity limit.
49964                         return 0 /* False */;
49965                     }
49966                 }
49967                 // Compute the set of types for each discriminant property.
49968                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
49969                 var excludedProperties = ts.createUnderscoreEscapedMap();
49970                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
49971                     var sourceProperty = sourcePropertiesFiltered[i];
49972                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
49973                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
49974                         ? sourcePropertyType.types
49975                         : [sourcePropertyType];
49976                     excludedProperties.set(sourceProperty.escapedName, true);
49977                 }
49978                 // Match each combination of the cartesian product of discriminant properties to one or more
49979                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
49980                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
49981                 var matchingTypes = [];
49982                 var _loop_14 = function (combination) {
49983                     var hasMatch = false;
49984                     outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
49985                         var type = _a[_i];
49986                         var _loop_15 = function (i) {
49987                             var sourceProperty = sourcePropertiesFiltered[i];
49988                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
49989                             if (!targetProperty)
49990                                 return "continue-outer";
49991                             if (sourceProperty === targetProperty)
49992                                 return "continue";
49993                             // We compare the source property to the target in the context of a single discriminant type.
49994                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
49995                             // If the target property could not be found, or if the properties were not related,
49996                             // then this constituent is not a match.
49997                             if (!related) {
49998                                 return "continue-outer";
49999                             }
50000                         };
50001                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
50002                             var state_7 = _loop_15(i);
50003                             switch (state_7) {
50004                                 case "continue-outer": continue outer;
50005                             }
50006                         }
50007                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
50008                         hasMatch = true;
50009                     }
50010                     if (!hasMatch) {
50011                         return { value: 0 /* False */ };
50012                     }
50013                 };
50014                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
50015                     var combination = discriminantCombinations_1[_a];
50016                     var state_6 = _loop_14(combination);
50017                     if (typeof state_6 === "object")
50018                         return state_6.value;
50019                 }
50020                 // Compare the remaining non-discriminant properties of each match.
50021                 var result = -1 /* True */;
50022                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
50023                     var type = matchingTypes_1[_b];
50024                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
50025                     if (result) {
50026                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
50027                         if (result) {
50028                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
50029                             if (result) {
50030                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50031                                 if (result) {
50032                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50033                                 }
50034                             }
50035                         }
50036                     }
50037                     if (!result) {
50038                         return result;
50039                     }
50040                 }
50041                 return result;
50042             }
50043             function excludeProperties(properties, excludedProperties) {
50044                 if (!excludedProperties || properties.length === 0)
50045                     return properties;
50046                 var result;
50047                 for (var i = 0; i < properties.length; i++) {
50048                     if (!excludedProperties.has(properties[i].escapedName)) {
50049                         if (result) {
50050                             result.push(properties[i]);
50051                         }
50052                     }
50053                     else if (!result) {
50054                         result = properties.slice(0, i);
50055                     }
50056                 }
50057                 return result || properties;
50058             }
50059             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
50060                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
50061                 var source = getTypeOfSourceProperty(sourceProp);
50062                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
50063                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
50064                     var links = getSymbolLinks(targetProp);
50065                     ts.Debug.assertIsDefined(links.deferralParent);
50066                     ts.Debug.assertIsDefined(links.deferralConstituents);
50067                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
50068                     var result_9 = unionParent ? 0 /* False */ : -1 /* True */;
50069                     var targetTypes = links.deferralConstituents;
50070                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
50071                         var targetType = targetTypes_3[_i];
50072                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
50073                         if (!unionParent) {
50074                             if (!related) {
50075                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
50076                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50077                             }
50078                             result_9 &= related;
50079                         }
50080                         else {
50081                             if (related) {
50082                                 return related;
50083                             }
50084                         }
50085                     }
50086                     if (unionParent && !result_9 && targetIsOptional) {
50087                         result_9 = isRelatedTo(source, undefinedType);
50088                     }
50089                     if (unionParent && !result_9 && reportErrors) {
50090                         // The easiest way to get the right errors here is to un-defer (which may be costly)
50091                         // If it turns out this is too costly too often, we can replicate the error handling logic within
50092                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
50093                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
50094                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50095                     }
50096                     return result_9;
50097                 }
50098                 else {
50099                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
50100                 }
50101             }
50102             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
50103                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
50104                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
50105                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
50106                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
50107                         if (reportErrors) {
50108                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
50109                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
50110                             }
50111                             else {
50112                                 reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source));
50113                             }
50114                         }
50115                         return 0 /* False */;
50116                     }
50117                 }
50118                 else if (targetPropFlags & 16 /* Protected */) {
50119                     if (!isValidOverrideOf(sourceProp, targetProp)) {
50120                         if (reportErrors) {
50121                             reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target));
50122                         }
50123                         return 0 /* False */;
50124                     }
50125                 }
50126                 else if (sourcePropFlags & 16 /* Protected */) {
50127                     if (reportErrors) {
50128                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50129                     }
50130                     return 0 /* False */;
50131                 }
50132                 // If the target comes from a partial union prop, allow `undefined` in the target type
50133                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
50134                 if (!related) {
50135                     if (reportErrors) {
50136                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
50137                     }
50138                     return 0 /* False */;
50139                 }
50140                 // When checking for comparability, be more lenient with optional properties.
50141                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
50142                     // TypeScript 1.0 spec (April 2014): 3.8.3
50143                     // S is a subtype of a type T, and T is a supertype of S if ...
50144                     // S' and T are object types and, for each member M in T..
50145                     // M is a property and S' contains a property N where
50146                     // if M is a required property, N is also a required property
50147                     // (M - property in T)
50148                     // (N - property in S)
50149                     if (reportErrors) {
50150                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50151                     }
50152                     return 0 /* False */;
50153                 }
50154                 return related;
50155             }
50156             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
50157                 var shouldSkipElaboration = false;
50158                 // give specific error in case where private names have the same description
50159                 if (unmatchedProperty.valueDeclaration
50160                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
50161                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
50162                     && source.symbol
50163                     && source.symbol.flags & 32 /* Class */) {
50164                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
50165                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
50166                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
50167                         var sourceName = ts.getDeclarationName(source.symbol.valueDeclaration);
50168                         var targetName = ts.getDeclarationName(target.symbol.valueDeclaration);
50169                         reportError(ts.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));
50170                         return;
50171                     }
50172                 }
50173                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
50174                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
50175                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
50176                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
50177                 }
50178                 if (props.length === 1) {
50179                     var propName = symbolToString(unmatchedProperty);
50180                     reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
50181                     if (ts.length(unmatchedProperty.declarations)) {
50182                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
50183                     }
50184                     if (shouldSkipElaboration && errorInfo) {
50185                         overrideNextErrorInfo++;
50186                     }
50187                 }
50188                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
50189                     if (props.length > 5) { // arbitrary cutoff for too-long list form
50190                         reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4);
50191                     }
50192                     else {
50193                         reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", "));
50194                     }
50195                     if (shouldSkipElaboration && errorInfo) {
50196                         overrideNextErrorInfo++;
50197                     }
50198                 }
50199                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
50200             }
50201             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
50202                 if (relation === identityRelation) {
50203                     return propertiesIdenticalTo(source, target, excludedProperties);
50204                 }
50205                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
50206                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
50207                 if (unmatchedProperty) {
50208                     if (reportErrors) {
50209                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
50210                     }
50211                     return 0 /* False */;
50212                 }
50213                 if (isObjectLiteralType(target)) {
50214                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
50215                         var sourceProp = _a[_i];
50216                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
50217                             var sourceType = getTypeOfSymbol(sourceProp);
50218                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
50219                                 if (reportErrors) {
50220                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
50221                                 }
50222                                 return 0 /* False */;
50223                             }
50224                         }
50225                     }
50226                 }
50227                 var result = -1 /* True */;
50228                 if (isTupleType(target)) {
50229                     var targetRestType = getRestTypeOfTupleType(target);
50230                     if (targetRestType) {
50231                         if (!isTupleType(source)) {
50232                             return 0 /* False */;
50233                         }
50234                         var sourceRestType = getRestTypeOfTupleType(source);
50235                         if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
50236                             if (reportErrors) {
50237                                 reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
50238                             }
50239                             return 0 /* False */;
50240                         }
50241                         var targetCount = getTypeReferenceArity(target) - 1;
50242                         var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
50243                         var sourceTypeArguments = getTypeArguments(source);
50244                         for (var i = targetCount; i < sourceCount; i++) {
50245                             var related = isRelatedTo(sourceTypeArguments[i], targetRestType, reportErrors);
50246                             if (!related) {
50247                                 if (reportErrors) {
50248                                     reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
50249                                 }
50250                                 return 0 /* False */;
50251                             }
50252                             result &= related;
50253                         }
50254                     }
50255                 }
50256                 // We only call this for union target types when we're attempting to do excess property checking - in those cases, we want to get _all possible props_
50257                 // from the target union, across all members
50258                 var properties = getPropertiesOfType(target);
50259                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
50260                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
50261                     var targetProp = _c[_b];
50262                     var name = targetProp.escapedName;
50263                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
50264                         var sourceProp = getPropertyOfType(source, name);
50265                         if (sourceProp && sourceProp !== targetProp) {
50266                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
50267                             if (!related) {
50268                                 return 0 /* False */;
50269                             }
50270                             result &= related;
50271                         }
50272                     }
50273                 }
50274                 return result;
50275             }
50276             function propertiesIdenticalTo(source, target, excludedProperties) {
50277                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
50278                     return 0 /* False */;
50279                 }
50280                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
50281                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
50282                 if (sourceProperties.length !== targetProperties.length) {
50283                     return 0 /* False */;
50284                 }
50285                 var result = -1 /* True */;
50286                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
50287                     var sourceProp = sourceProperties_1[_i];
50288                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
50289                     if (!targetProp) {
50290                         return 0 /* False */;
50291                     }
50292                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
50293                     if (!related) {
50294                         return 0 /* False */;
50295                     }
50296                     result &= related;
50297                 }
50298                 return result;
50299             }
50300             function signaturesRelatedTo(source, target, kind, reportErrors) {
50301                 if (relation === identityRelation) {
50302                     return signaturesIdenticalTo(source, target, kind);
50303                 }
50304                 if (target === anyFunctionType || source === anyFunctionType) {
50305                     return -1 /* True */;
50306                 }
50307                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
50308                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
50309                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
50310                     0 /* Call */ : kind);
50311                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
50312                     0 /* Call */ : kind);
50313                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
50314                     if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
50315                         // An abstract constructor type is not assignable to a non-abstract constructor type
50316                         // as it would otherwise be possible to new an abstract class. Note that the assignability
50317                         // check we perform for an extends clause excludes construct signatures from the target,
50318                         // so this check never proceeds.
50319                         if (reportErrors) {
50320                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
50321                         }
50322                         return 0 /* False */;
50323                     }
50324                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
50325                         return 0 /* False */;
50326                     }
50327                 }
50328                 var result = -1 /* True */;
50329                 var saveErrorInfo = captureErrorCalculationState();
50330                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
50331                 if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
50332                     // We have instantiations of the same anonymous type (which typically will be the type of a
50333                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
50334                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
50335                     // as they are known to always be the same.
50336                     for (var i = 0; i < targetSignatures.length; i++) {
50337                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
50338                         if (!related) {
50339                             return 0 /* False */;
50340                         }
50341                         result &= related;
50342                     }
50343                 }
50344                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
50345                     // For simple functions (functions with a single signature) we only erase type parameters for
50346                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
50347                     // in the context of the target signature before checking the relationship. Ideally we'd do
50348                     // this regardless of the number of signatures, but the potential costs are prohibitive due
50349                     // to the quadratic nature of the logic below.
50350                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
50351                     result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors, incompatibleReporter(sourceSignatures[0], targetSignatures[0]));
50352                 }
50353                 else {
50354                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
50355                         var t = targetSignatures_1[_i];
50356                         // Only elaborate errors from the first failure
50357                         var shouldElaborateErrors = reportErrors;
50358                         for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
50359                             var s = sourceSignatures_1[_a];
50360                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
50361                             if (related) {
50362                                 result &= related;
50363                                 resetErrorInfo(saveErrorInfo);
50364                                 continue outer;
50365                             }
50366                             shouldElaborateErrors = false;
50367                         }
50368                         if (shouldElaborateErrors) {
50369                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
50370                         }
50371                         return 0 /* False */;
50372                     }
50373                 }
50374                 return result;
50375             }
50376             function reportIncompatibleCallSignatureReturn(siga, sigb) {
50377                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50378                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50379                 }
50380                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50381             }
50382             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
50383                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50384                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50385                 }
50386                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50387             }
50388             /**
50389              * See signatureAssignableTo, compareSignaturesIdentical
50390              */
50391             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
50392                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
50393             }
50394             function signaturesIdenticalTo(source, target, kind) {
50395                 var sourceSignatures = getSignaturesOfType(source, kind);
50396                 var targetSignatures = getSignaturesOfType(target, kind);
50397                 if (sourceSignatures.length !== targetSignatures.length) {
50398                     return 0 /* False */;
50399                 }
50400                 var result = -1 /* True */;
50401                 for (var i = 0; i < sourceSignatures.length; i++) {
50402                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
50403                     if (!related) {
50404                         return 0 /* False */;
50405                     }
50406                     result &= related;
50407                 }
50408                 return result;
50409             }
50410             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
50411                 var result = -1 /* True */;
50412                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
50413                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
50414                     var prop = props_2[_i];
50415                     // Skip over ignored JSX and symbol-named members
50416                     if (isIgnoredJsxProperty(source, prop)) {
50417                         continue;
50418                     }
50419                     var nameType = getSymbolLinks(prop).nameType;
50420                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
50421                         continue;
50422                     }
50423                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
50424                         var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
50425                         if (!related) {
50426                             if (reportErrors) {
50427                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
50428                             }
50429                             return 0 /* False */;
50430                         }
50431                         result &= related;
50432                     }
50433                 }
50434                 return result;
50435             }
50436             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
50437                 var related = isRelatedTo(sourceType, targetType, reportErrors);
50438                 if (!related && reportErrors) {
50439                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
50440                 }
50441                 return related;
50442             }
50443             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
50444                 if (relation === identityRelation) {
50445                     return indexTypesIdenticalTo(source, target, kind);
50446                 }
50447                 var targetType = getIndexTypeOfType(target, kind);
50448                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
50449                     // Index signature of type any permits assignment from everything but primitives
50450                     return -1 /* True */;
50451                 }
50452                 if (isGenericMappedType(source)) {
50453                     // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
50454                     // if T is related to U.
50455                     return kind === 0 /* String */ ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
50456                 }
50457                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
50458                 if (indexType) {
50459                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
50460                 }
50461                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
50462                     // Intersection constituents are never considered to have an inferred index signature
50463                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
50464                     if (related && kind === 0 /* String */) {
50465                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
50466                         if (numberIndexType) {
50467                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
50468                         }
50469                     }
50470                     return related;
50471                 }
50472                 if (reportErrors) {
50473                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
50474                 }
50475                 return 0 /* False */;
50476             }
50477             function indexTypesIdenticalTo(source, target, indexKind) {
50478                 var targetInfo = getIndexInfoOfType(target, indexKind);
50479                 var sourceInfo = getIndexInfoOfType(source, indexKind);
50480                 if (!sourceInfo && !targetInfo) {
50481                     return -1 /* True */;
50482                 }
50483                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
50484                     return isRelatedTo(sourceInfo.type, targetInfo.type);
50485                 }
50486                 return 0 /* False */;
50487             }
50488             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
50489                 if (!sourceSignature.declaration || !targetSignature.declaration) {
50490                     return true;
50491                 }
50492                 var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50493                 var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50494                 // A public, protected and private signature is assignable to a private signature.
50495                 if (targetAccessibility === 8 /* Private */) {
50496                     return true;
50497                 }
50498                 // A public and protected signature is assignable to a protected signature.
50499                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
50500                     return true;
50501                 }
50502                 // Only a public signature is assignable to public signature.
50503                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
50504                     return true;
50505                 }
50506                 if (reportErrors) {
50507                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
50508                 }
50509                 return false;
50510             }
50511         }
50512         function getBestMatchingType(source, target, isRelatedTo) {
50513             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
50514             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
50515                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
50516                 findBestTypeForObjectLiteral(source, target) ||
50517                 findBestTypeForInvokable(source, target) ||
50518                 findMostOverlappyType(source, target);
50519         }
50520         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
50521             // undefined=unknown, true=discriminated, false=not discriminated
50522             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
50523             var discriminable = target.types.map(function (_) { return undefined; });
50524             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
50525                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
50526                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
50527                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
50528                     continue;
50529                 }
50530                 var i = 0;
50531                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
50532                     var type = _c[_b];
50533                     var targetType = getTypeOfPropertyOfType(type, propertyName);
50534                     if (targetType && related(getDiscriminatingType(), targetType)) {
50535                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
50536                     }
50537                     else {
50538                         discriminable[i] = false;
50539                     }
50540                     i++;
50541                 }
50542             }
50543             var match = discriminable.indexOf(/*searchElement*/ true);
50544             // make sure exactly 1 matches before returning it
50545             return match === -1 || discriminable.indexOf(/*searchElement*/ true, match + 1) !== -1 ? defaultValue : target.types[match];
50546         }
50547         /**
50548          * A type is 'weak' if it is an object type with at least one optional property
50549          * and no required properties, call/construct signatures or index signatures
50550          */
50551         function isWeakType(type) {
50552             if (type.flags & 524288 /* Object */) {
50553                 var resolved = resolveStructuredTypeMembers(type);
50554                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
50555                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
50556                     resolved.properties.length > 0 &&
50557                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
50558             }
50559             if (type.flags & 2097152 /* Intersection */) {
50560                 return ts.every(type.types, isWeakType);
50561             }
50562             return false;
50563         }
50564         function hasCommonProperties(source, target, isComparingJsxAttributes) {
50565             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50566                 var prop = _a[_i];
50567                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
50568                     return true;
50569                 }
50570             }
50571             return false;
50572         }
50573         // Return a type reference where the source type parameter is replaced with the target marker
50574         // type, and flag the result as a marker type reference.
50575         function getMarkerTypeReference(type, source, target) {
50576             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
50577             result.objectFlags |= 8192 /* MarkerType */;
50578             return result;
50579         }
50580         function getAliasVariances(symbol) {
50581             var links = getSymbolLinks(symbol);
50582             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
50583                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
50584                 type.aliasTypeArgumentsContainsMarker = true;
50585                 return type;
50586             });
50587         }
50588         // Return an array containing the variance of each type parameter. The variance is effectively
50589         // a digest of the type comparisons that occur for each type argument when instantiations of the
50590         // generic type are structurally compared. We infer the variance information by comparing
50591         // instantiations of the generic type for type arguments with known relations. The function
50592         // returns the emptyArray singleton when invoked recursively for the given generic type.
50593         function getVariancesWorker(typeParameters, cache, createMarkerType) {
50594             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
50595             var variances = cache.variances;
50596             if (!variances) {
50597                 // The emptyArray singleton is used to signal a recursive invocation.
50598                 cache.variances = ts.emptyArray;
50599                 variances = [];
50600                 var _loop_16 = function (tp) {
50601                     var unmeasurable = false;
50602                     var unreliable = false;
50603                     var oldHandler = outofbandVarianceMarkerHandler;
50604                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
50605                     // We first compare instantiations where the type parameter is replaced with
50606                     // marker types that have a known subtype relationship. From this we can infer
50607                     // invariance, covariance, contravariance or bivariance.
50608                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
50609                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
50610                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
50611                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
50612                     // If the instantiations appear to be related bivariantly it may be because the
50613                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
50614                     // type). To determine this we compare instantiations where the type parameter is
50615                     // replaced with marker types that are known to be unrelated.
50616                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
50617                         variance = 4 /* Independent */;
50618                     }
50619                     outofbandVarianceMarkerHandler = oldHandler;
50620                     if (unmeasurable || unreliable) {
50621                         if (unmeasurable) {
50622                             variance |= 8 /* Unmeasurable */;
50623                         }
50624                         if (unreliable) {
50625                             variance |= 16 /* Unreliable */;
50626                         }
50627                     }
50628                     variances.push(variance);
50629                 };
50630                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
50631                     var tp = typeParameters_1[_i];
50632                     _loop_16(tp);
50633                 }
50634                 cache.variances = variances;
50635             }
50636             return variances;
50637         }
50638         function getVariances(type) {
50639             // Arrays and tuples are known to be covariant, no need to spend time computing this.
50640             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
50641                 return arrayVariances;
50642             }
50643             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
50644         }
50645         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
50646         // See comment at call in recursiveTypeRelatedTo for when this case matters.
50647         function hasCovariantVoidArgument(typeArguments, variances) {
50648             for (var i = 0; i < variances.length; i++) {
50649                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
50650                     return true;
50651                 }
50652             }
50653             return false;
50654         }
50655         function isUnconstrainedTypeParameter(type) {
50656             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
50657         }
50658         function isNonDeferredTypeReference(type) {
50659             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
50660         }
50661         function isTypeReferenceWithGenericArguments(type) {
50662             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
50663         }
50664         /**
50665          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
50666          *   where A.id=111 and number.id=12
50667          */
50668         function getTypeReferenceId(type, typeParameters, depth) {
50669             if (depth === void 0) { depth = 0; }
50670             var result = "" + type.target.id;
50671             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
50672                 var t = _a[_i];
50673                 if (isUnconstrainedTypeParameter(t)) {
50674                     var index = typeParameters.indexOf(t);
50675                     if (index < 0) {
50676                         index = typeParameters.length;
50677                         typeParameters.push(t);
50678                     }
50679                     result += "=" + index;
50680                 }
50681                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
50682                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
50683                 }
50684                 else {
50685                     result += "-" + t.id;
50686                 }
50687             }
50688             return result;
50689         }
50690         /**
50691          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
50692          * For other cases, the types ids are used.
50693          */
50694         function getRelationKey(source, target, intersectionState, relation) {
50695             if (relation === identityRelation && source.id > target.id) {
50696                 var temp = source;
50697                 source = target;
50698                 target = temp;
50699             }
50700             var postFix = intersectionState ? ":" + intersectionState : "";
50701             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
50702                 var typeParameters = [];
50703                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
50704             }
50705             return source.id + "," + target.id + postFix;
50706         }
50707         // Invoke the callback for each underlying property symbol of the given symbol and return the first
50708         // value that isn't undefined.
50709         function forEachProperty(prop, callback) {
50710             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
50711                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
50712                     var t = _a[_i];
50713                     var p = getPropertyOfType(t, prop.escapedName);
50714                     var result = p && forEachProperty(p, callback);
50715                     if (result) {
50716                         return result;
50717                     }
50718                 }
50719                 return undefined;
50720             }
50721             return callback(prop);
50722         }
50723         // Return the declaring class type of a property or undefined if property not declared in class
50724         function getDeclaringClass(prop) {
50725             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
50726         }
50727         // Return true if some underlying source property is declared in a class that derives
50728         // from the given base class.
50729         function isPropertyInClassDerivedFrom(prop, baseClass) {
50730             return forEachProperty(prop, function (sp) {
50731                 var sourceClass = getDeclaringClass(sp);
50732                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
50733             });
50734         }
50735         // Return true if source property is a valid override of protected parts of target property.
50736         function isValidOverrideOf(sourceProp, targetProp) {
50737             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
50738                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
50739         }
50740         // Return true if the given class derives from each of the declaring classes of the protected
50741         // constituents of the given property.
50742         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
50743             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
50744                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
50745         }
50746         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
50747         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
50748         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
50749         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
50750         // levels, but unequal at some level beyond that.
50751         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
50752         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
50753         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
50754         function isDeeplyNestedType(type, stack, depth) {
50755             // We track all object types that have an associated symbol (representing the origin of the type)
50756             if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
50757                 var symbol = type.symbol;
50758                 if (symbol) {
50759                     var count = 0;
50760                     for (var i = 0; i < depth; i++) {
50761                         var t = stack[i];
50762                         if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
50763                             count++;
50764                             if (count >= 5)
50765                                 return true;
50766                         }
50767                     }
50768                 }
50769             }
50770             if (depth >= 5 && type.flags & 8388608 /* IndexedAccess */) {
50771                 var root = getRootObjectTypeFromIndexedAccessChain(type);
50772                 var count = 0;
50773                 for (var i = 0; i < depth; i++) {
50774                     var t = stack[i];
50775                     if (getRootObjectTypeFromIndexedAccessChain(t) === root) {
50776                         count++;
50777                         if (count >= 5)
50778                             return true;
50779                     }
50780                 }
50781             }
50782             return false;
50783         }
50784         /**
50785          * Gets the leftmost object type in a chain of indexed accesses, eg, in A[P][Q], returns A
50786          */
50787         function getRootObjectTypeFromIndexedAccessChain(type) {
50788             var t = type;
50789             while (t.flags & 8388608 /* IndexedAccess */) {
50790                 t = t.objectType;
50791             }
50792             return t;
50793         }
50794         function isPropertyIdenticalTo(sourceProp, targetProp) {
50795             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
50796         }
50797         function compareProperties(sourceProp, targetProp, compareTypes) {
50798             // Two members are considered identical when
50799             // - they are public properties with identical names, optionality, and types,
50800             // - they are private or protected properties originating in the same declaration and having identical types
50801             if (sourceProp === targetProp) {
50802                 return -1 /* True */;
50803             }
50804             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
50805             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
50806             if (sourcePropAccessibility !== targetPropAccessibility) {
50807                 return 0 /* False */;
50808             }
50809             if (sourcePropAccessibility) {
50810                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
50811                     return 0 /* False */;
50812                 }
50813             }
50814             else {
50815                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
50816                     return 0 /* False */;
50817                 }
50818             }
50819             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
50820                 return 0 /* False */;
50821             }
50822             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
50823         }
50824         function isMatchingSignature(source, target, partialMatch) {
50825             var sourceParameterCount = getParameterCount(source);
50826             var targetParameterCount = getParameterCount(target);
50827             var sourceMinArgumentCount = getMinArgumentCount(source);
50828             var targetMinArgumentCount = getMinArgumentCount(target);
50829             var sourceHasRestParameter = hasEffectiveRestParameter(source);
50830             var targetHasRestParameter = hasEffectiveRestParameter(target);
50831             // A source signature matches a target signature if the two signatures have the same number of required,
50832             // optional, and rest parameters.
50833             if (sourceParameterCount === targetParameterCount &&
50834                 sourceMinArgumentCount === targetMinArgumentCount &&
50835                 sourceHasRestParameter === targetHasRestParameter) {
50836                 return true;
50837             }
50838             // A source signature partially matches a target signature if the target signature has no fewer required
50839             // parameters
50840             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
50841                 return true;
50842             }
50843             return false;
50844         }
50845         /**
50846          * See signatureRelatedTo, compareSignaturesIdentical
50847          */
50848         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
50849             // TODO (drosen): De-duplicate code between related functions.
50850             if (source === target) {
50851                 return -1 /* True */;
50852             }
50853             if (!(isMatchingSignature(source, target, partialMatch))) {
50854                 return 0 /* False */;
50855             }
50856             // Check that the two signatures have the same number of type parameters.
50857             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
50858                 return 0 /* False */;
50859             }
50860             // Check that type parameter constraints and defaults match. If they do, instantiate the source
50861             // signature with the type parameters of the target signature and continue the comparison.
50862             if (target.typeParameters) {
50863                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
50864                 for (var i = 0; i < target.typeParameters.length; i++) {
50865                     var s = source.typeParameters[i];
50866                     var t = target.typeParameters[i];
50867                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
50868                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
50869                         return 0 /* False */;
50870                     }
50871                 }
50872                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
50873             }
50874             var result = -1 /* True */;
50875             if (!ignoreThisTypes) {
50876                 var sourceThisType = getThisTypeOfSignature(source);
50877                 if (sourceThisType) {
50878                     var targetThisType = getThisTypeOfSignature(target);
50879                     if (targetThisType) {
50880                         var related = compareTypes(sourceThisType, targetThisType);
50881                         if (!related) {
50882                             return 0 /* False */;
50883                         }
50884                         result &= related;
50885                     }
50886                 }
50887             }
50888             var targetLen = getParameterCount(target);
50889             for (var i = 0; i < targetLen; i++) {
50890                 var s = getTypeAtPosition(source, i);
50891                 var t = getTypeAtPosition(target, i);
50892                 var related = compareTypes(t, s);
50893                 if (!related) {
50894                     return 0 /* False */;
50895                 }
50896                 result &= related;
50897             }
50898             if (!ignoreReturnTypes) {
50899                 var sourceTypePredicate = getTypePredicateOfSignature(source);
50900                 var targetTypePredicate = getTypePredicateOfSignature(target);
50901                 result &= sourceTypePredicate || targetTypePredicate ?
50902                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
50903                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
50904             }
50905             return result;
50906         }
50907         function compareTypePredicatesIdentical(source, target, compareTypes) {
50908             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
50909                 source.type === target.type ? -1 /* True */ :
50910                     source.type && target.type ? compareTypes(source.type, target.type) :
50911                         0 /* False */;
50912         }
50913         function literalTypesWithSameBaseType(types) {
50914             var commonBaseType;
50915             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
50916                 var t = types_12[_i];
50917                 var baseType = getBaseTypeOfLiteralType(t);
50918                 if (!commonBaseType) {
50919                     commonBaseType = baseType;
50920                 }
50921                 if (baseType === t || baseType !== commonBaseType) {
50922                     return false;
50923                 }
50924             }
50925             return true;
50926         }
50927         // When the candidate types are all literal types with the same base type, return a union
50928         // of those literal types. Otherwise, return the leftmost type for which no type to the
50929         // right is a supertype.
50930         function getSupertypeOrUnion(types) {
50931             return literalTypesWithSameBaseType(types) ?
50932                 getUnionType(types) :
50933                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
50934         }
50935         function getCommonSupertype(types) {
50936             if (!strictNullChecks) {
50937                 return getSupertypeOrUnion(types);
50938             }
50939             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
50940             return primaryTypes.length ?
50941                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
50942                 getUnionType(types, 2 /* Subtype */);
50943         }
50944         // Return the leftmost type for which no type to the right is a subtype.
50945         function getCommonSubtype(types) {
50946             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
50947         }
50948         function isArrayType(type) {
50949             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
50950         }
50951         function isReadonlyArrayType(type) {
50952             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
50953         }
50954         function isMutableArrayOrTuple(type) {
50955             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
50956         }
50957         function getElementTypeOfArrayType(type) {
50958             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50959         }
50960         function isArrayLikeType(type) {
50961             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
50962             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
50963             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
50964         }
50965         function isEmptyArrayLiteralType(type) {
50966             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50967             return elementType === undefinedWideningType || elementType === implicitNeverType;
50968         }
50969         function isTupleLikeType(type) {
50970             return isTupleType(type) || !!getPropertyOfType(type, "0");
50971         }
50972         function isArrayOrTupleLikeType(type) {
50973             return isArrayLikeType(type) || isTupleLikeType(type);
50974         }
50975         function getTupleElementType(type, index) {
50976             var propType = getTypeOfPropertyOfType(type, "" + index);
50977             if (propType) {
50978                 return propType;
50979             }
50980             if (everyType(type, isTupleType)) {
50981                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
50982             }
50983             return undefined;
50984         }
50985         function isNeitherUnitTypeNorNever(type) {
50986             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
50987         }
50988         function isUnitType(type) {
50989             return !!(type.flags & 109440 /* Unit */);
50990         }
50991         function isLiteralType(type) {
50992             return type.flags & 16 /* Boolean */ ? true :
50993                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
50994                     isUnitType(type);
50995         }
50996         function getBaseTypeOfLiteralType(type) {
50997             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
50998                 type.flags & 128 /* StringLiteral */ ? stringType :
50999                     type.flags & 256 /* NumberLiteral */ ? numberType :
51000                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
51001                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
51002                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
51003                                     type;
51004         }
51005         function getWidenedLiteralType(type) {
51006             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
51007                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
51008                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
51009                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
51010                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
51011                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
51012                                     type;
51013         }
51014         function getWidenedUniqueESSymbolType(type) {
51015             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
51016                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
51017                     type;
51018         }
51019         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
51020             if (!isLiteralOfContextualType(type, contextualType)) {
51021                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
51022             }
51023             return type;
51024         }
51025         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
51026             if (type && isUnitType(type)) {
51027                 var contextualType = !contextualSignatureReturnType ? undefined :
51028                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
51029                         contextualSignatureReturnType;
51030                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51031             }
51032             return type;
51033         }
51034         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
51035             if (type && isUnitType(type)) {
51036                 var contextualType = !contextualSignatureReturnType ? undefined :
51037                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
51038                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51039             }
51040             return type;
51041         }
51042         /**
51043          * Check if a Type was written as a tuple type literal.
51044          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
51045          */
51046         function isTupleType(type) {
51047             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
51048         }
51049         function getRestTypeOfTupleType(type) {
51050             return type.target.hasRestElement ? getTypeArguments(type)[type.target.typeParameters.length - 1] : undefined;
51051         }
51052         function getRestArrayTypeOfTupleType(type) {
51053             var restType = getRestTypeOfTupleType(type);
51054             return restType && createArrayType(restType);
51055         }
51056         function getLengthOfTupleType(type) {
51057             return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
51058         }
51059         function isZeroBigInt(_a) {
51060             var value = _a.value;
51061             return value.base10Value === "0";
51062         }
51063         function getFalsyFlagsOfTypes(types) {
51064             var result = 0;
51065             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
51066                 var t = types_13[_i];
51067                 result |= getFalsyFlags(t);
51068             }
51069             return result;
51070         }
51071         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
51072         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
51073         // no flags for all other types (including non-falsy literal types).
51074         function getFalsyFlags(type) {
51075             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
51076                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
51077                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
51078                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
51079                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
51080                                 type.flags & 117724 /* PossiblyFalsy */;
51081         }
51082         function removeDefinitelyFalsyTypes(type) {
51083             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
51084                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
51085                 type;
51086         }
51087         function extractDefinitelyFalsyTypes(type) {
51088             return mapType(type, getDefinitelyFalsyPartOfType);
51089         }
51090         function getDefinitelyFalsyPartOfType(type) {
51091             return type.flags & 4 /* String */ ? emptyStringType :
51092                 type.flags & 8 /* Number */ ? zeroType :
51093                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
51094                         type === regularFalseType ||
51095                             type === falseType ||
51096                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
51097                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
51098                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
51099                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
51100                             neverType;
51101         }
51102         /**
51103          * Add undefined or null or both to a type if they are missing.
51104          * @param type - type to add undefined and/or null to if not present
51105          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
51106          */
51107         function getNullableType(type, flags) {
51108             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
51109             return missing === 0 ? type :
51110                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
51111                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
51112                         getUnionType([type, undefinedType, nullType]);
51113         }
51114         function getOptionalType(type) {
51115             ts.Debug.assert(strictNullChecks);
51116             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
51117         }
51118         function getGlobalNonNullableTypeInstantiation(type) {
51119             if (!deferredGlobalNonNullableTypeAlias) {
51120                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
51121             }
51122             // Use NonNullable global type alias if available to improve quick info/declaration emit
51123             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
51124                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
51125             }
51126             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
51127         }
51128         function getNonNullableType(type) {
51129             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
51130         }
51131         function addOptionalTypeMarker(type) {
51132             return strictNullChecks ? getUnionType([type, optionalType]) : type;
51133         }
51134         function isNotOptionalTypeMarker(type) {
51135             return type !== optionalType;
51136         }
51137         function removeOptionalTypeMarker(type) {
51138             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
51139         }
51140         function propagateOptionalTypeMarker(type, node, wasOptional) {
51141             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
51142         }
51143         function getOptionalExpressionType(exprType, expression) {
51144             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
51145                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
51146                     exprType;
51147         }
51148         /**
51149          * Is source potentially coercible to target type under `==`.
51150          * Assumes that `source` is a constituent of a union, hence
51151          * the boolean literal flag on the LHS, but not on the RHS.
51152          *
51153          * This does not fully replicate the semantics of `==`. The
51154          * intention is to catch cases that are clearly not right.
51155          *
51156          * Comparing (string | number) to number should not remove the
51157          * string element.
51158          *
51159          * Comparing (string | number) to 1 will remove the string
51160          * element, though this is not sound. This is a pragmatic
51161          * choice.
51162          *
51163          * @see narrowTypeByEquality
51164          *
51165          * @param source
51166          * @param target
51167          */
51168         function isCoercibleUnderDoubleEquals(source, target) {
51169             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
51170                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
51171         }
51172         /**
51173          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
51174          * with no call or construct signatures.
51175          */
51176         function isObjectTypeWithInferableIndex(type) {
51177             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
51178                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
51179                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
51180         }
51181         function createSymbolWithType(source, type) {
51182             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
51183             symbol.declarations = source.declarations;
51184             symbol.parent = source.parent;
51185             symbol.type = type;
51186             symbol.target = source;
51187             if (source.valueDeclaration) {
51188                 symbol.valueDeclaration = source.valueDeclaration;
51189             }
51190             var nameType = getSymbolLinks(source).nameType;
51191             if (nameType) {
51192                 symbol.nameType = nameType;
51193             }
51194             return symbol;
51195         }
51196         function transformTypeOfMembers(type, f) {
51197             var members = ts.createSymbolTable();
51198             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51199                 var property = _a[_i];
51200                 var original = getTypeOfSymbol(property);
51201                 var updated = f(original);
51202                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
51203             }
51204             return members;
51205         }
51206         /**
51207          * If the the provided object literal is subject to the excess properties check,
51208          * create a new that is exempt. Recursively mark object literal members as exempt.
51209          * Leave signatures alone since they are not subject to the check.
51210          */
51211         function getRegularTypeOfObjectLiteral(type) {
51212             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
51213                 return type;
51214             }
51215             var regularType = type.regularType;
51216             if (regularType) {
51217                 return regularType;
51218             }
51219             var resolved = type;
51220             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
51221             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
51222             regularNew.flags = resolved.flags;
51223             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
51224             type.regularType = regularNew;
51225             return regularNew;
51226         }
51227         function createWideningContext(parent, propertyName, siblings) {
51228             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
51229         }
51230         function getSiblingsOfContext(context) {
51231             if (!context.siblings) {
51232                 var siblings_1 = [];
51233                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
51234                     var type = _a[_i];
51235                     if (isObjectLiteralType(type)) {
51236                         var prop = getPropertyOfObjectType(type, context.propertyName);
51237                         if (prop) {
51238                             forEachType(getTypeOfSymbol(prop), function (t) {
51239                                 siblings_1.push(t);
51240                             });
51241                         }
51242                     }
51243                 }
51244                 context.siblings = siblings_1;
51245             }
51246             return context.siblings;
51247         }
51248         function getPropertiesOfContext(context) {
51249             if (!context.resolvedProperties) {
51250                 var names = ts.createMap();
51251                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
51252                     var t = _a[_i];
51253                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
51254                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
51255                             var prop = _c[_b];
51256                             names.set(prop.escapedName, prop);
51257                         }
51258                     }
51259                 }
51260                 context.resolvedProperties = ts.arrayFrom(names.values());
51261             }
51262             return context.resolvedProperties;
51263         }
51264         function getWidenedProperty(prop, context) {
51265             if (!(prop.flags & 4 /* Property */)) {
51266                 // Since get accessors already widen their return value there is no need to
51267                 // widen accessor based properties here.
51268                 return prop;
51269             }
51270             var original = getTypeOfSymbol(prop);
51271             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
51272             var widened = getWidenedTypeWithContext(original, propContext);
51273             return widened === original ? prop : createSymbolWithType(prop, widened);
51274         }
51275         function getUndefinedProperty(prop) {
51276             var cached = undefinedProperties.get(prop.escapedName);
51277             if (cached) {
51278                 return cached;
51279             }
51280             var result = createSymbolWithType(prop, undefinedType);
51281             result.flags |= 16777216 /* Optional */;
51282             undefinedProperties.set(prop.escapedName, result);
51283             return result;
51284         }
51285         function getWidenedTypeOfObjectLiteral(type, context) {
51286             var members = ts.createSymbolTable();
51287             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51288                 var prop = _a[_i];
51289                 members.set(prop.escapedName, getWidenedProperty(prop, context));
51290             }
51291             if (context) {
51292                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
51293                     var prop = _c[_b];
51294                     if (!members.has(prop.escapedName)) {
51295                         members.set(prop.escapedName, getUndefinedProperty(prop));
51296                     }
51297                 }
51298             }
51299             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
51300             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
51301             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
51302             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
51303             return result;
51304         }
51305         function getWidenedType(type) {
51306             return getWidenedTypeWithContext(type, /*context*/ undefined);
51307         }
51308         function getWidenedTypeWithContext(type, context) {
51309             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
51310                 if (context === undefined && type.widened) {
51311                     return type.widened;
51312                 }
51313                 var result = void 0;
51314                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
51315                     result = anyType;
51316                 }
51317                 else if (isObjectLiteralType(type)) {
51318                     result = getWidenedTypeOfObjectLiteral(type, context);
51319                 }
51320                 else if (type.flags & 1048576 /* Union */) {
51321                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
51322                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
51323                     // Widening an empty object literal transitions from a highly restrictive type to
51324                     // a highly inclusive one. For that reason we perform subtype reduction here if the
51325                     // union includes empty object types (e.g. reducing {} | string to just {}).
51326                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
51327                 }
51328                 else if (type.flags & 2097152 /* Intersection */) {
51329                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
51330                 }
51331                 else if (isArrayType(type) || isTupleType(type)) {
51332                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
51333                 }
51334                 if (result && context === undefined) {
51335                     type.widened = result;
51336                 }
51337                 return result || type;
51338             }
51339             return type;
51340         }
51341         /**
51342          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
51343          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
51344          * getWidenedType. But in some cases getWidenedType is called without reporting errors
51345          * (type argument inference is an example).
51346          *
51347          * The return value indicates whether an error was in fact reported. The particular circumstances
51348          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
51349          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
51350          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
51351          */
51352         function reportWideningErrorsInType(type) {
51353             var errorReported = false;
51354             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
51355                 if (type.flags & 1048576 /* Union */) {
51356                     if (ts.some(type.types, isEmptyObjectType)) {
51357                         errorReported = true;
51358                     }
51359                     else {
51360                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
51361                             var t = _a[_i];
51362                             if (reportWideningErrorsInType(t)) {
51363                                 errorReported = true;
51364                             }
51365                         }
51366                     }
51367                 }
51368                 if (isArrayType(type) || isTupleType(type)) {
51369                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
51370                         var t = _c[_b];
51371                         if (reportWideningErrorsInType(t)) {
51372                             errorReported = true;
51373                         }
51374                     }
51375                 }
51376                 if (isObjectLiteralType(type)) {
51377                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
51378                         var p = _e[_d];
51379                         var t = getTypeOfSymbol(p);
51380                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
51381                             if (!reportWideningErrorsInType(t)) {
51382                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
51383                             }
51384                             errorReported = true;
51385                         }
51386                     }
51387                 }
51388             }
51389             return errorReported;
51390         }
51391         function reportImplicitAny(declaration, type, wideningKind) {
51392             var typeAsString = typeToString(getWidenedType(type));
51393             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
51394                 // Only report implicit any errors/suggestions in TS and ts-check JS files
51395                 return;
51396             }
51397             var diagnostic;
51398             switch (declaration.kind) {
51399                 case 209 /* BinaryExpression */:
51400                 case 159 /* PropertyDeclaration */:
51401                 case 158 /* PropertySignature */:
51402                     diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
51403                     break;
51404                 case 156 /* Parameter */:
51405                     var param = declaration;
51406                     if (ts.isIdentifier(param.name) &&
51407                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
51408                         param.parent.parameters.indexOf(param) > -1 &&
51409                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
51410                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
51411                         var newName = "arg" + param.parent.parameters.indexOf(param);
51412                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
51413                         return;
51414                     }
51415                     diagnostic = declaration.dotDotDotToken ?
51416                         noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
51417                         noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
51418                     break;
51419                 case 191 /* BindingElement */:
51420                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
51421                     if (!noImplicitAny) {
51422                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
51423                         return;
51424                     }
51425                     break;
51426                 case 300 /* JSDocFunctionType */:
51427                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51428                     return;
51429                 case 244 /* FunctionDeclaration */:
51430                 case 161 /* MethodDeclaration */:
51431                 case 160 /* MethodSignature */:
51432                 case 163 /* GetAccessor */:
51433                 case 164 /* SetAccessor */:
51434                 case 201 /* FunctionExpression */:
51435                 case 202 /* ArrowFunction */:
51436                     if (noImplicitAny && !declaration.name) {
51437                         if (wideningKind === 3 /* GeneratorYield */) {
51438                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
51439                         }
51440                         else {
51441                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51442                         }
51443                         return;
51444                     }
51445                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
51446                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
51447                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
51448                     break;
51449                 case 186 /* MappedType */:
51450                     if (noImplicitAny) {
51451                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
51452                     }
51453                     return;
51454                 default:
51455                     diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
51456             }
51457             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
51458         }
51459         function reportErrorsFromWidening(declaration, type, wideningKind) {
51460             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
51461                 // Report implicit any error within type if possible, otherwise report error on declaration
51462                 if (!reportWideningErrorsInType(type)) {
51463                     reportImplicitAny(declaration, type, wideningKind);
51464                 }
51465             }
51466         }
51467         function applyToParameterTypes(source, target, callback) {
51468             var sourceCount = getParameterCount(source);
51469             var targetCount = getParameterCount(target);
51470             var sourceRestType = getEffectiveRestType(source);
51471             var targetRestType = getEffectiveRestType(target);
51472             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
51473             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
51474             var sourceThisType = getThisTypeOfSignature(source);
51475             if (sourceThisType) {
51476                 var targetThisType = getThisTypeOfSignature(target);
51477                 if (targetThisType) {
51478                     callback(sourceThisType, targetThisType);
51479                 }
51480             }
51481             for (var i = 0; i < paramCount; i++) {
51482                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
51483             }
51484             if (targetRestType) {
51485                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
51486             }
51487         }
51488         function applyToReturnTypes(source, target, callback) {
51489             var sourceTypePredicate = getTypePredicateOfSignature(source);
51490             var targetTypePredicate = getTypePredicateOfSignature(target);
51491             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
51492                 callback(sourceTypePredicate.type, targetTypePredicate.type);
51493             }
51494             else {
51495                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
51496             }
51497         }
51498         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
51499             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
51500         }
51501         function cloneInferenceContext(context, extraFlags) {
51502             if (extraFlags === void 0) { extraFlags = 0; }
51503             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
51504         }
51505         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
51506             var context = {
51507                 inferences: inferences,
51508                 signature: signature,
51509                 flags: flags,
51510                 compareTypes: compareTypes,
51511                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
51512                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
51513             };
51514             return context;
51515         }
51516         function mapToInferredType(context, t, fix) {
51517             var inferences = context.inferences;
51518             for (var i = 0; i < inferences.length; i++) {
51519                 var inference = inferences[i];
51520                 if (t === inference.typeParameter) {
51521                     if (fix && !inference.isFixed) {
51522                         clearCachedInferences(inferences);
51523                         inference.isFixed = true;
51524                     }
51525                     return getInferredType(context, i);
51526                 }
51527             }
51528             return t;
51529         }
51530         function clearCachedInferences(inferences) {
51531             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
51532                 var inference = inferences_1[_i];
51533                 if (!inference.isFixed) {
51534                     inference.inferredType = undefined;
51535                 }
51536             }
51537         }
51538         function createInferenceInfo(typeParameter) {
51539             return {
51540                 typeParameter: typeParameter,
51541                 candidates: undefined,
51542                 contraCandidates: undefined,
51543                 inferredType: undefined,
51544                 priority: undefined,
51545                 topLevel: true,
51546                 isFixed: false
51547             };
51548         }
51549         function cloneInferenceInfo(inference) {
51550             return {
51551                 typeParameter: inference.typeParameter,
51552                 candidates: inference.candidates && inference.candidates.slice(),
51553                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
51554                 inferredType: inference.inferredType,
51555                 priority: inference.priority,
51556                 topLevel: inference.topLevel,
51557                 isFixed: inference.isFixed
51558             };
51559         }
51560         function cloneInferredPartOfContext(context) {
51561             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
51562             return inferences.length ?
51563                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
51564                 undefined;
51565         }
51566         function getMapperFromContext(context) {
51567             return context && context.mapper;
51568         }
51569         // Return true if the given type could possibly reference a type parameter for which
51570         // we perform type inference (i.e. a type parameter of a generic function). We cache
51571         // results for union and intersection types for performance reasons.
51572         function couldContainTypeVariables(type) {
51573             var objectFlags = ts.getObjectFlags(type);
51574             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
51575                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
51576             }
51577             var result = !!(type.flags & 63176704 /* Instantiable */ ||
51578                 objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
51579                 objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
51580                 objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) ||
51581                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables));
51582             if (type.flags & 3899393 /* ObjectFlagsType */) {
51583                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
51584             }
51585             return result;
51586         }
51587         function isTypeParameterAtTopLevel(type, typeParameter) {
51588             return !!(type === typeParameter ||
51589                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
51590                 type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), typeParameter) ||
51591                     isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), typeParameter)));
51592         }
51593         /** Create an object with properties named in the string literal type. Every property has type `any` */
51594         function createEmptyObjectTypeFromStringLiteral(type) {
51595             var members = ts.createSymbolTable();
51596             forEachType(type, function (t) {
51597                 if (!(t.flags & 128 /* StringLiteral */)) {
51598                     return;
51599                 }
51600                 var name = ts.escapeLeadingUnderscores(t.value);
51601                 var literalProp = createSymbol(4 /* Property */, name);
51602                 literalProp.type = anyType;
51603                 if (t.symbol) {
51604                     literalProp.declarations = t.symbol.declarations;
51605                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
51606                 }
51607                 members.set(name, literalProp);
51608             });
51609             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
51610             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
51611         }
51612         /**
51613          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
51614          * an object type with the same set of properties as the source type, where the type of each
51615          * property is computed by inferring from the source property type to X for the type
51616          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
51617          */
51618         function inferTypeForHomomorphicMappedType(source, target, constraint) {
51619             var key = source.id + "," + target.id + "," + constraint.id;
51620             if (reverseMappedCache.has(key)) {
51621                 return reverseMappedCache.get(key);
51622             }
51623             reverseMappedCache.set(key, undefined);
51624             var type = createReverseMappedType(source, target, constraint);
51625             reverseMappedCache.set(key, type);
51626             return type;
51627         }
51628         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
51629         // an object literal type with at least one property of an inferable type. For example, an object
51630         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
51631         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
51632         function isPartiallyInferableType(type) {
51633             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
51634                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); });
51635         }
51636         function createReverseMappedType(source, target, constraint) {
51637             // We consider a source type reverse mappable if it has a string index signature or if
51638             // it has one or more properties and is of a partially inferable type.
51639             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
51640                 return undefined;
51641             }
51642             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
51643             // applied to the element type(s).
51644             if (isArrayType(source)) {
51645                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
51646             }
51647             if (isTupleType(source)) {
51648                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
51649                 var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
51650                     getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
51651                 return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
51652             }
51653             // For all other object types we infer a new object type where the reverse mapping has been
51654             // applied to the type of each property.
51655             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
51656             reversed.source = source;
51657             reversed.mappedType = target;
51658             reversed.constraintType = constraint;
51659             return reversed;
51660         }
51661         function getTypeOfReverseMappedSymbol(symbol) {
51662             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
51663         }
51664         function inferReverseMappedType(sourceType, target, constraint) {
51665             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
51666             var templateType = getTemplateTypeFromMappedType(target);
51667             var inference = createInferenceInfo(typeParameter);
51668             inferTypes([inference], sourceType, templateType);
51669             return getTypeFromInference(inference) || unknownType;
51670         }
51671         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51672             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
51673             return __generator(this, function (_a) {
51674                 switch (_a.label) {
51675                     case 0:
51676                         properties = getPropertiesOfType(target);
51677                         _i = 0, properties_2 = properties;
51678                         _a.label = 1;
51679                     case 1:
51680                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
51681                         targetProp = properties_2[_i];
51682                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
51683                         if (isStaticPrivateIdentifierProperty(targetProp)) {
51684                             return [3 /*break*/, 5];
51685                         }
51686                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
51687                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
51688                         if (!!sourceProp) return [3 /*break*/, 3];
51689                         return [4 /*yield*/, targetProp];
51690                     case 2:
51691                         _a.sent();
51692                         return [3 /*break*/, 5];
51693                     case 3:
51694                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
51695                         targetType = getTypeOfSymbol(targetProp);
51696                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
51697                         sourceType = getTypeOfSymbol(sourceProp);
51698                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
51699                         return [4 /*yield*/, targetProp];
51700                     case 4:
51701                         _a.sent();
51702                         _a.label = 5;
51703                     case 5:
51704                         _i++;
51705                         return [3 /*break*/, 1];
51706                     case 6: return [2 /*return*/];
51707                 }
51708             });
51709         }
51710         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51711             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
51712             if (!result.done)
51713                 return result.value;
51714         }
51715         function tupleTypesDefinitelyUnrelated(source, target) {
51716             return target.target.minLength > source.target.minLength ||
51717                 !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
51718         }
51719         function typesDefinitelyUnrelated(source, target) {
51720             // Two tuple types with incompatible arities are definitely unrelated.
51721             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
51722             return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
51723                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
51724                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
51725         }
51726         function getTypeFromInference(inference) {
51727             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
51728                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
51729                     undefined;
51730         }
51731         function hasSkipDirectInferenceFlag(node) {
51732             return !!getNodeLinks(node).skipDirectInference;
51733         }
51734         function isFromInferenceBlockedSource(type) {
51735             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
51736         }
51737         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
51738             if (priority === void 0) { priority = 0; }
51739             if (contravariant === void 0) { contravariant = false; }
51740             var symbolOrTypeStack;
51741             var visited;
51742             var bivariant = false;
51743             var propagationType;
51744             var inferencePriority = 512 /* MaxValue */;
51745             var allowComplexConstraintInference = true;
51746             inferFromTypes(originalSource, originalTarget);
51747             function inferFromTypes(source, target) {
51748                 if (!couldContainTypeVariables(target)) {
51749                     return;
51750                 }
51751                 if (source === wildcardType) {
51752                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
51753                     // referenced in the target type, so we record it as the propagation type and infer from the
51754                     // target to itself. Then, as we find candidates we substitute the propagation type.
51755                     var savePropagationType = propagationType;
51756                     propagationType = source;
51757                     inferFromTypes(target, target);
51758                     propagationType = savePropagationType;
51759                     return;
51760                 }
51761                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
51762                     // Source and target are types originating in the same generic type alias declaration.
51763                     // Simply infer from source type arguments to target type arguments.
51764                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
51765                     return;
51766                 }
51767                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
51768                     // When source and target are the same union or intersection type, just relate each constituent
51769                     // type to itself.
51770                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
51771                         var t = _a[_i];
51772                         inferFromTypes(t, t);
51773                     }
51774                     return;
51775                 }
51776                 if (target.flags & 1048576 /* Union */) {
51777                     // First, infer between identically matching source and target constituents and remove the
51778                     // matching types.
51779                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
51780                     // Next, infer between closely matching source and target constituents and remove
51781                     // the matching types. Types closely match when they are instantiations of the same
51782                     // object type or instantiations of the same type alias.
51783                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
51784                     if (targets.length === 0) {
51785                         return;
51786                     }
51787                     target = getUnionType(targets);
51788                     if (sources.length === 0) {
51789                         // All source constituents have been matched and there is nothing further to infer from.
51790                         // However, simply making no inferences is undesirable because it could ultimately mean
51791                         // inferring a type parameter constraint. Instead, make a lower priority inference from
51792                         // the full source to whatever remains in the target. For example, when inferring from
51793                         // string to 'string | T', make a lower priority inference of string for T.
51794                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
51795                         return;
51796                     }
51797                     source = getUnionType(sources);
51798                 }
51799                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
51800                     // We reduce intersection types only when they contain naked type parameters. For example, when
51801                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
51802                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
51803                     // string[] on the source side and infer string for T.
51804                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
51805                     // in such scenarios.
51806                     if (!(source.flags & 1048576 /* Union */)) {
51807                         // Infer between identically matching source and target constituents and remove the matching types.
51808                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
51809                         if (sources.length === 0 || targets.length === 0) {
51810                             return;
51811                         }
51812                         source = getIntersectionType(sources);
51813                         target = getIntersectionType(targets);
51814                     }
51815                 }
51816                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
51817                     target = getActualTypeVariable(target);
51818                 }
51819                 if (target.flags & 8650752 /* TypeVariable */) {
51820                     // If target is a type parameter, make an inference, unless the source type contains
51821                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
51822                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
51823                     // it as an inference candidate. Hopefully, a better candidate will come along that does
51824                     // not contain anyFunctionType when we come back to this argument for its second round
51825                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
51826                     // when constructing types from type parameters that had no inference candidates).
51827                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
51828                         (priority & 32 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
51829                         return;
51830                     }
51831                     var inference = getInferenceInfoForType(target);
51832                     if (inference) {
51833                         if (!inference.isFixed) {
51834                             if (inference.priority === undefined || priority < inference.priority) {
51835                                 inference.candidates = undefined;
51836                                 inference.contraCandidates = undefined;
51837                                 inference.topLevel = true;
51838                                 inference.priority = priority;
51839                             }
51840                             if (priority === inference.priority) {
51841                                 var candidate = propagationType || source;
51842                                 // We make contravariant inferences only if we are in a pure contravariant position,
51843                                 // i.e. only if we have not descended into a bivariant position.
51844                                 if (contravariant && !bivariant) {
51845                                     if (!ts.contains(inference.contraCandidates, candidate)) {
51846                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
51847                                         clearCachedInferences(inferences);
51848                                     }
51849                                 }
51850                                 else if (!ts.contains(inference.candidates, candidate)) {
51851                                     inference.candidates = ts.append(inference.candidates, candidate);
51852                                     clearCachedInferences(inferences);
51853                                 }
51854                             }
51855                             if (!(priority & 32 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
51856                                 inference.topLevel = false;
51857                                 clearCachedInferences(inferences);
51858                             }
51859                         }
51860                         inferencePriority = Math.min(inferencePriority, priority);
51861                         return;
51862                     }
51863                     else {
51864                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
51865                         var simplified = getSimplifiedType(target, /*writing*/ false);
51866                         if (simplified !== target) {
51867                             invokeOnce(source, simplified, inferFromTypes);
51868                         }
51869                         else if (target.flags & 8388608 /* IndexedAccess */) {
51870                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
51871                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
51872                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
51873                             if (indexType.flags & 63176704 /* Instantiable */) {
51874                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
51875                                 if (simplified_1 && simplified_1 !== target) {
51876                                     invokeOnce(source, simplified_1, inferFromTypes);
51877                                 }
51878                             }
51879                         }
51880                     }
51881                 }
51882                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
51883                     !(source.node && target.node)) {
51884                     // If source and target are references to the same generic type, infer from type arguments
51885                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
51886                 }
51887                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
51888                     contravariant = !contravariant;
51889                     inferFromTypes(source.type, target.type);
51890                     contravariant = !contravariant;
51891                 }
51892                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
51893                     var empty = createEmptyObjectTypeFromStringLiteral(source);
51894                     contravariant = !contravariant;
51895                     inferWithPriority(empty, target.type, 64 /* LiteralKeyof */);
51896                     contravariant = !contravariant;
51897                 }
51898                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
51899                     inferFromTypes(source.objectType, target.objectType);
51900                     inferFromTypes(source.indexType, target.indexType);
51901                 }
51902                 else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
51903                     inferFromTypes(source.checkType, target.checkType);
51904                     inferFromTypes(source.extendsType, target.extendsType);
51905                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
51906                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
51907                 }
51908                 else if (target.flags & 16777216 /* Conditional */) {
51909                     var savePriority = priority;
51910                     priority |= contravariant ? 16 /* ContravariantConditional */ : 0;
51911                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
51912                     inferToMultipleTypes(source, targetTypes, target.flags);
51913                     priority = savePriority;
51914                 }
51915                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
51916                     inferToMultipleTypes(source, target.types, target.flags);
51917                 }
51918                 else if (source.flags & 1048576 /* Union */) {
51919                     // Source is a union or intersection type, infer from each constituent type
51920                     var sourceTypes = source.types;
51921                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
51922                         var sourceType = sourceTypes_2[_e];
51923                         inferFromTypes(sourceType, target);
51924                     }
51925                 }
51926                 else {
51927                     source = getReducedType(source);
51928                     if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
51929                         var apparentSource = getApparentType(source);
51930                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
51931                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
51932                         // with the simplified source.
51933                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
51934                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
51935                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
51936                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
51937                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
51938                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
51939                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
51940                             // remove this `allowComplexConstraintInference` flag.
51941                             allowComplexConstraintInference = false;
51942                             return inferFromTypes(apparentSource, target);
51943                         }
51944                         source = apparentSource;
51945                     }
51946                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
51947                         invokeOnce(source, target, inferFromObjectTypes);
51948                     }
51949                 }
51950                 if (source.flags & 25165824 /* Simplifiable */) {
51951                     var simplified = getSimplifiedType(source, contravariant);
51952                     if (simplified !== source) {
51953                         inferFromTypes(simplified, target);
51954                     }
51955                 }
51956             }
51957             function inferWithPriority(source, target, newPriority) {
51958                 var savePriority = priority;
51959                 priority |= newPriority;
51960                 inferFromTypes(source, target);
51961                 priority = savePriority;
51962             }
51963             function invokeOnce(source, target, action) {
51964                 var key = source.id + "," + target.id;
51965                 var status = visited && visited.get(key);
51966                 if (status !== undefined) {
51967                     inferencePriority = Math.min(inferencePriority, status);
51968                     return;
51969                 }
51970                 (visited || (visited = ts.createMap())).set(key, -1 /* Circularity */);
51971                 var saveInferencePriority = inferencePriority;
51972                 inferencePriority = 512 /* MaxValue */;
51973                 action(source, target);
51974                 visited.set(key, inferencePriority);
51975                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
51976             }
51977             function inferFromMatchingTypes(sources, targets, matches) {
51978                 var matchedSources;
51979                 var matchedTargets;
51980                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
51981                     var t = targets_1[_i];
51982                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
51983                         var s = sources_1[_a];
51984                         if (matches(s, t)) {
51985                             inferFromTypes(s, t);
51986                             matchedSources = ts.appendIfUnique(matchedSources, s);
51987                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
51988                         }
51989                     }
51990                 }
51991                 return [
51992                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
51993                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
51994                 ];
51995             }
51996             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
51997                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
51998                 for (var i = 0; i < count; i++) {
51999                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
52000                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
52001                     }
52002                     else {
52003                         inferFromTypes(sourceTypes[i], targetTypes[i]);
52004                     }
52005                 }
52006             }
52007             function inferFromContravariantTypes(source, target) {
52008                 if (strictFunctionTypes || priority & 256 /* AlwaysStrict */) {
52009                     contravariant = !contravariant;
52010                     inferFromTypes(source, target);
52011                     contravariant = !contravariant;
52012                 }
52013                 else {
52014                     inferFromTypes(source, target);
52015                 }
52016             }
52017             function getInferenceInfoForType(type) {
52018                 if (type.flags & 8650752 /* TypeVariable */) {
52019                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
52020                         var inference = inferences_2[_i];
52021                         if (type === inference.typeParameter) {
52022                             return inference;
52023                         }
52024                     }
52025                 }
52026                 return undefined;
52027             }
52028             function getSingleTypeVariableFromIntersectionTypes(types) {
52029                 var typeVariable;
52030                 for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
52031                     var type = types_14[_i];
52032                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
52033                     if (!t || typeVariable && t !== typeVariable) {
52034                         return undefined;
52035                     }
52036                     typeVariable = t;
52037                 }
52038                 return typeVariable;
52039             }
52040             function inferToMultipleTypes(source, targets, targetFlags) {
52041                 var typeVariableCount = 0;
52042                 if (targetFlags & 1048576 /* Union */) {
52043                     var nakedTypeVariable = void 0;
52044                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
52045                     var matched_1 = new Array(sources.length);
52046                     var inferenceCircularity = false;
52047                     // First infer to types that are not naked type variables. For each source type we
52048                     // track whether inferences were made from that particular type to some target with
52049                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
52050                     // parameter.
52051                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
52052                         var t = targets_2[_i];
52053                         if (getInferenceInfoForType(t)) {
52054                             nakedTypeVariable = t;
52055                             typeVariableCount++;
52056                         }
52057                         else {
52058                             for (var i = 0; i < sources.length; i++) {
52059                                 var saveInferencePriority = inferencePriority;
52060                                 inferencePriority = 512 /* MaxValue */;
52061                                 inferFromTypes(sources[i], t);
52062                                 if (inferencePriority === priority)
52063                                     matched_1[i] = true;
52064                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
52065                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
52066                             }
52067                         }
52068                     }
52069                     if (typeVariableCount === 0) {
52070                         // If every target is an intersection of types containing a single naked type variable,
52071                         // make a lower priority inference to that type variable. This handles inferring from
52072                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
52073                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
52074                         if (intersectionTypeVariable) {
52075                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
52076                         }
52077                         return;
52078                     }
52079                     // If the target has a single naked type variable and no inference circularities were
52080                     // encountered above (meaning we explored the types fully), create a union of the source
52081                     // types from which no inferences have been made so far and infer from that union to the
52082                     // naked type variable.
52083                     if (typeVariableCount === 1 && !inferenceCircularity) {
52084                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
52085                         if (unmatched.length) {
52086                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
52087                             return;
52088                         }
52089                     }
52090                 }
52091                 else {
52092                     // We infer from types that are not naked type variables first so that inferences we
52093                     // make from nested naked type variables and given slightly higher priority by virtue
52094                     // of being first in the candidates array.
52095                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
52096                         var t = targets_3[_a];
52097                         if (getInferenceInfoForType(t)) {
52098                             typeVariableCount++;
52099                         }
52100                         else {
52101                             inferFromTypes(source, t);
52102                         }
52103                     }
52104                 }
52105                 // Inferences directly to naked type variables are given lower priority as they are
52106                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
52107                 // we want to infer string for T, not Promise<string> | string. For intersection types
52108                 // we only infer to single naked type variables.
52109                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
52110                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
52111                         var t = targets_4[_b];
52112                         if (getInferenceInfoForType(t)) {
52113                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
52114                         }
52115                     }
52116                 }
52117             }
52118             function inferToMappedType(source, target, constraintType) {
52119                 if (constraintType.flags & 1048576 /* Union */) {
52120                     var result = false;
52121                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
52122                         var type = _a[_i];
52123                         result = inferToMappedType(source, target, type) || result;
52124                     }
52125                     return result;
52126                 }
52127                 if (constraintType.flags & 4194304 /* Index */) {
52128                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
52129                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
52130                     // type and then make a secondary inference from that type to T. We make a secondary inference
52131                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
52132                     var inference = getInferenceInfoForType(constraintType.type);
52133                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
52134                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
52135                         if (inferredType) {
52136                             // We assign a lower priority to inferences made from types containing non-inferrable
52137                             // types because we may only have a partial result (i.e. we may have failed to make
52138                             // reverse inferences for some properties).
52139                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
52140                                 4 /* PartialHomomorphicMappedType */ :
52141                                 2 /* HomomorphicMappedType */);
52142                         }
52143                     }
52144                     return true;
52145                 }
52146                 if (constraintType.flags & 262144 /* TypeParameter */) {
52147                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
52148                     // parameter. First infer from 'keyof S' to K.
52149                     inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */);
52150                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
52151                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
52152                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
52153                     // Pick<T, K>.
52154                     var extendedConstraint = getConstraintOfType(constraintType);
52155                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
52156                         return true;
52157                     }
52158                     // If no inferences can be made to K's constraint, infer from a union of the property types
52159                     // in the source to the template type X.
52160                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
52161                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
52162                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
52163                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
52164                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
52165                     return true;
52166                 }
52167                 return false;
52168             }
52169             function inferFromObjectTypes(source, target) {
52170                 // If we are already processing another target type with the same associated symbol (such as
52171                 // an instantiation of the same generic type), we do not explore this target as it would yield
52172                 // no further inferences. We exclude the static side of classes from this check since it shares
52173                 // its symbol with the instance side which would lead to false positives.
52174                 var isNonConstructorObject = target.flags & 524288 /* Object */ &&
52175                     !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
52176                 var symbolOrType = isNonConstructorObject ? isTupleType(target) ? target.target : target.symbol : undefined;
52177                 if (symbolOrType) {
52178                     if (ts.contains(symbolOrTypeStack, symbolOrType)) {
52179                         inferencePriority = -1 /* Circularity */;
52180                         return;
52181                     }
52182                     (symbolOrTypeStack || (symbolOrTypeStack = [])).push(symbolOrType);
52183                     inferFromObjectTypesWorker(source, target);
52184                     symbolOrTypeStack.pop();
52185                 }
52186                 else {
52187                     inferFromObjectTypesWorker(source, target);
52188                 }
52189             }
52190             function inferFromObjectTypesWorker(source, target) {
52191                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
52192                     // If source and target are references to the same generic type, infer from type arguments
52193                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
52194                     return;
52195                 }
52196                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
52197                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
52198                     // from S to T and from X to Y.
52199                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
52200                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
52201                 }
52202                 if (ts.getObjectFlags(target) & 32 /* Mapped */) {
52203                     var constraintType = getConstraintTypeFromMappedType(target);
52204                     if (inferToMappedType(source, target, constraintType)) {
52205                         return;
52206                     }
52207                 }
52208                 // Infer from the members of source and target only if the two types are possibly related
52209                 if (!typesDefinitelyUnrelated(source, target)) {
52210                     if (isArrayType(source) || isTupleType(source)) {
52211                         if (isTupleType(target)) {
52212                             var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
52213                             var targetLength = getLengthOfTupleType(target);
52214                             var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
52215                             var targetRestType = getRestTypeOfTupleType(target);
52216                             var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
52217                             for (var i = 0; i < fixedLength; i++) {
52218                                 inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]);
52219                             }
52220                             if (targetRestType) {
52221                                 var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : [];
52222                                 if (sourceRestType) {
52223                                     types.push(sourceRestType);
52224                                 }
52225                                 if (types.length) {
52226                                     inferFromTypes(getUnionType(types), targetRestType);
52227                                 }
52228                             }
52229                             return;
52230                         }
52231                         if (isArrayType(target)) {
52232                             inferFromIndexTypes(source, target);
52233                             return;
52234                         }
52235                     }
52236                     inferFromProperties(source, target);
52237                     inferFromSignatures(source, target, 0 /* Call */);
52238                     inferFromSignatures(source, target, 1 /* Construct */);
52239                     inferFromIndexTypes(source, target);
52240                 }
52241             }
52242             function inferFromProperties(source, target) {
52243                 var properties = getPropertiesOfObjectType(target);
52244                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
52245                     var targetProp = properties_3[_i];
52246                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
52247                     if (sourceProp) {
52248                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
52249                     }
52250                 }
52251             }
52252             function inferFromSignatures(source, target, kind) {
52253                 var sourceSignatures = getSignaturesOfType(source, kind);
52254                 var targetSignatures = getSignaturesOfType(target, kind);
52255                 var sourceLen = sourceSignatures.length;
52256                 var targetLen = targetSignatures.length;
52257                 var len = sourceLen < targetLen ? sourceLen : targetLen;
52258                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
52259                 for (var i = 0; i < len; i++) {
52260                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
52261                 }
52262             }
52263             function inferFromSignature(source, target, skipParameters) {
52264                 if (!skipParameters) {
52265                     var saveBivariant = bivariant;
52266                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
52267                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
52268                     bivariant = bivariant || kind === 161 /* MethodDeclaration */ || kind === 160 /* MethodSignature */ || kind === 162 /* Constructor */;
52269                     applyToParameterTypes(source, target, inferFromContravariantTypes);
52270                     bivariant = saveBivariant;
52271                 }
52272                 applyToReturnTypes(source, target, inferFromTypes);
52273             }
52274             function inferFromIndexTypes(source, target) {
52275                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
52276                 if (targetStringIndexType) {
52277                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
52278                         getImplicitIndexTypeOfType(source, 0 /* String */);
52279                     if (sourceIndexType) {
52280                         inferFromTypes(sourceIndexType, targetStringIndexType);
52281                     }
52282                 }
52283                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
52284                 if (targetNumberIndexType) {
52285                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
52286                         getIndexTypeOfType(source, 0 /* String */) ||
52287                         getImplicitIndexTypeOfType(source, 1 /* Number */);
52288                     if (sourceIndexType) {
52289                         inferFromTypes(sourceIndexType, targetNumberIndexType);
52290                     }
52291                 }
52292             }
52293         }
52294         function isTypeOrBaseIdenticalTo(s, t) {
52295             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
52296         }
52297         function isTypeCloselyMatchedBy(s, t) {
52298             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
52299                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
52300         }
52301         function hasPrimitiveConstraint(type) {
52302             var constraint = getConstraintOfTypeParameter(type);
52303             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
52304         }
52305         function isObjectLiteralType(type) {
52306             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
52307         }
52308         function isObjectOrArrayLiteralType(type) {
52309             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
52310         }
52311         function unionObjectAndArrayLiteralCandidates(candidates) {
52312             if (candidates.length > 1) {
52313                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
52314                 if (objectLiterals.length) {
52315                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
52316                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
52317                 }
52318             }
52319             return candidates;
52320         }
52321         function getContravariantInference(inference) {
52322             return inference.priority & 104 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
52323         }
52324         function getCovariantInference(inference, signature) {
52325             // Extract all object and array literal types and replace them with a single widened and normalized type.
52326             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
52327             // We widen inferred literal types if
52328             // all inferences were made to top-level occurrences of the type parameter, and
52329             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
52330             // the type parameter was fixed during inference or does not occur at top-level in the return type.
52331             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
52332             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
52333                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
52334             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
52335                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
52336                     candidates;
52337             // If all inferences were made from a position that implies a combined result, infer a union type.
52338             // Otherwise, infer a common supertype.
52339             var unwidenedType = inference.priority & 104 /* PriorityImpliesCombination */ ?
52340                 getUnionType(baseCandidates, 2 /* Subtype */) :
52341                 getCommonSupertype(baseCandidates);
52342             return getWidenedType(unwidenedType);
52343         }
52344         function getInferredType(context, index) {
52345             var inference = context.inferences[index];
52346             if (!inference.inferredType) {
52347                 var inferredType = void 0;
52348                 var signature = context.signature;
52349                 if (signature) {
52350                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
52351                     if (inference.contraCandidates) {
52352                         var inferredContravariantType = getContravariantInference(inference);
52353                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
52354                         // unless the co-variant inference is a subtype and not 'never'.
52355                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
52356                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
52357                             inferredCovariantType : inferredContravariantType;
52358                     }
52359                     else if (inferredCovariantType) {
52360                         inferredType = inferredCovariantType;
52361                     }
52362                     else if (context.flags & 1 /* NoDefault */) {
52363                         // We use silentNeverType as the wildcard that signals no inferences.
52364                         inferredType = silentNeverType;
52365                     }
52366                     else {
52367                         // Infer either the default or the empty object type when no inferences were
52368                         // made. It is important to remember that in this case, inference still
52369                         // succeeds, meaning there is no error for not having inference candidates. An
52370                         // inference error only occurs when there are *conflicting* candidates, i.e.
52371                         // candidates with no common supertype.
52372                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
52373                         if (defaultType) {
52374                             // Instantiate the default type. Any forward reference to a type
52375                             // parameter should be instantiated to the empty object type.
52376                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
52377                         }
52378                     }
52379                 }
52380                 else {
52381                     inferredType = getTypeFromInference(inference);
52382                 }
52383                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
52384                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
52385                 if (constraint) {
52386                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
52387                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
52388                         inference.inferredType = inferredType = instantiatedConstraint;
52389                     }
52390                 }
52391             }
52392             return inference.inferredType;
52393         }
52394         function getDefaultTypeArgumentType(isInJavaScriptFile) {
52395             return isInJavaScriptFile ? anyType : unknownType;
52396         }
52397         function getInferredTypes(context) {
52398             var result = [];
52399             for (var i = 0; i < context.inferences.length; i++) {
52400                 result.push(getInferredType(context, i));
52401             }
52402             return result;
52403         }
52404         // EXPRESSION TYPE CHECKING
52405         function getCannotFindNameDiagnosticForName(node) {
52406             switch (node.escapedText) {
52407                 case "document":
52408                 case "console":
52409                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
52410                 case "$":
52411                     return compilerOptions.types
52412                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
52413                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
52414                 case "describe":
52415                 case "suite":
52416                 case "it":
52417                 case "test":
52418                     return compilerOptions.types
52419                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
52420                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
52421                 case "process":
52422                 case "require":
52423                 case "Buffer":
52424                 case "module":
52425                     return compilerOptions.types
52426                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
52427                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
52428                 case "Map":
52429                 case "Set":
52430                 case "Promise":
52431                 case "Symbol":
52432                 case "WeakMap":
52433                 case "WeakSet":
52434                 case "Iterator":
52435                 case "AsyncIterator":
52436                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later;
52437                 default:
52438                     if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
52439                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
52440                     }
52441                     else {
52442                         return ts.Diagnostics.Cannot_find_name_0;
52443                     }
52444             }
52445         }
52446         function getResolvedSymbol(node) {
52447             var links = getNodeLinks(node);
52448             if (!links.resolvedSymbol) {
52449                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
52450                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
52451                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
52452             }
52453             return links.resolvedSymbol;
52454         }
52455         function isInTypeQuery(node) {
52456             // TypeScript 1.0 spec (April 2014): 3.6.3
52457             // A type query consists of the keyword typeof followed by an expression.
52458             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
52459             return !!ts.findAncestor(node, function (n) { return n.kind === 172 /* TypeQuery */ ? true : n.kind === 75 /* Identifier */ || n.kind === 153 /* QualifiedName */ ? false : "quit"; });
52460         }
52461         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
52462         // separated by dots). The key consists of the id of the symbol referenced by the
52463         // leftmost identifier followed by zero or more property names separated by dots.
52464         // The result is undefined if the reference isn't a dotted name. We prefix nodes
52465         // occurring in an apparent type position with '@' because the control flow type
52466         // of such nodes may be based on the apparent type instead of the declared type.
52467         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
52468             switch (node.kind) {
52469                 case 75 /* Identifier */:
52470                     var symbol = getResolvedSymbol(node);
52471                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
52472                 case 104 /* ThisKeyword */:
52473                     return "0";
52474                 case 218 /* NonNullExpression */:
52475                 case 200 /* ParenthesizedExpression */:
52476                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52477                 case 194 /* PropertyAccessExpression */:
52478                 case 195 /* ElementAccessExpression */:
52479                     var propName = getAccessedPropertyName(node);
52480                     if (propName !== undefined) {
52481                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52482                         return key && key + "." + propName;
52483                     }
52484             }
52485             return undefined;
52486         }
52487         function isMatchingReference(source, target) {
52488             switch (target.kind) {
52489                 case 200 /* ParenthesizedExpression */:
52490                 case 218 /* NonNullExpression */:
52491                     return isMatchingReference(source, target.expression);
52492             }
52493             switch (source.kind) {
52494                 case 75 /* Identifier */:
52495                     return target.kind === 75 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
52496                         (target.kind === 242 /* VariableDeclaration */ || target.kind === 191 /* BindingElement */) &&
52497                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
52498                 case 104 /* ThisKeyword */:
52499                     return target.kind === 104 /* ThisKeyword */;
52500                 case 102 /* SuperKeyword */:
52501                     return target.kind === 102 /* SuperKeyword */;
52502                 case 218 /* NonNullExpression */:
52503                 case 200 /* ParenthesizedExpression */:
52504                     return isMatchingReference(source.expression, target);
52505                 case 194 /* PropertyAccessExpression */:
52506                 case 195 /* ElementAccessExpression */:
52507                     return ts.isAccessExpression(target) &&
52508                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
52509                         isMatchingReference(source.expression, target.expression);
52510             }
52511             return false;
52512         }
52513         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
52514         function containsTruthyCheck(source, target) {
52515             return isMatchingReference(source, target) ||
52516                 (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
52517                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
52518         }
52519         function getAccessedPropertyName(access) {
52520             return access.kind === 194 /* PropertyAccessExpression */ ? access.name.escapedText :
52521                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
52522                     undefined;
52523         }
52524         function containsMatchingReference(source, target) {
52525             while (ts.isAccessExpression(source)) {
52526                 source = source.expression;
52527                 if (isMatchingReference(source, target)) {
52528                     return true;
52529                 }
52530             }
52531             return false;
52532         }
52533         function optionalChainContainsReference(source, target) {
52534             while (ts.isOptionalChain(source)) {
52535                 source = source.expression;
52536                 if (isMatchingReference(source, target)) {
52537                     return true;
52538                 }
52539             }
52540             return false;
52541         }
52542         function isDiscriminantProperty(type, name) {
52543             if (type && type.flags & 1048576 /* Union */) {
52544                 var prop = getUnionOrIntersectionProperty(type, name);
52545                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
52546                     if (prop.isDiscriminantProperty === undefined) {
52547                         prop.isDiscriminantProperty =
52548                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
52549                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 63176704 /* Instantiable */);
52550                     }
52551                     return !!prop.isDiscriminantProperty;
52552                 }
52553             }
52554             return false;
52555         }
52556         function findDiscriminantProperties(sourceProperties, target) {
52557             var result;
52558             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
52559                 var sourceProperty = sourceProperties_2[_i];
52560                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
52561                     if (result) {
52562                         result.push(sourceProperty);
52563                         continue;
52564                     }
52565                     result = [sourceProperty];
52566                 }
52567             }
52568             return result;
52569         }
52570         function isOrContainsMatchingReference(source, target) {
52571             return isMatchingReference(source, target) || containsMatchingReference(source, target);
52572         }
52573         function hasMatchingArgument(callExpression, reference) {
52574             if (callExpression.arguments) {
52575                 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
52576                     var argument = _a[_i];
52577                     if (isOrContainsMatchingReference(reference, argument)) {
52578                         return true;
52579                     }
52580                 }
52581             }
52582             if (callExpression.expression.kind === 194 /* PropertyAccessExpression */ &&
52583                 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
52584                 return true;
52585             }
52586             return false;
52587         }
52588         function getFlowNodeId(flow) {
52589             if (!flow.id || flow.id < 0) {
52590                 flow.id = nextFlowId;
52591                 nextFlowId++;
52592             }
52593             return flow.id;
52594         }
52595         function typeMaybeAssignableTo(source, target) {
52596             if (!(source.flags & 1048576 /* Union */)) {
52597                 return isTypeAssignableTo(source, target);
52598             }
52599             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52600                 var t = _a[_i];
52601                 if (isTypeAssignableTo(t, target)) {
52602                     return true;
52603                 }
52604             }
52605             return false;
52606         }
52607         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
52608         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
52609         // we remove type string.
52610         function getAssignmentReducedType(declaredType, assignedType) {
52611             if (declaredType !== assignedType) {
52612                 if (assignedType.flags & 131072 /* Never */) {
52613                     return assignedType;
52614                 }
52615                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
52616                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
52617                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
52618                 }
52619                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
52620                 // For now, when that happens, we give up and don't narrow at all.  (This also
52621                 // means we'll never narrow for erroneous assignments where the assigned type
52622                 // is not assignable to the declared type.)
52623                 if (isTypeAssignableTo(assignedType, reducedType)) {
52624                     return reducedType;
52625                 }
52626             }
52627             return declaredType;
52628         }
52629         function getTypeFactsOfTypes(types) {
52630             var result = 0 /* None */;
52631             for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
52632                 var t = types_15[_i];
52633                 result |= getTypeFacts(t);
52634             }
52635             return result;
52636         }
52637         function isFunctionObjectType(type) {
52638             // We do a quick check for a "bind" property before performing the more expensive subtype
52639             // check. This gives us a quicker out in the common case where an object type is not a function.
52640             var resolved = resolveStructuredTypeMembers(type);
52641             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
52642                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
52643         }
52644         function getTypeFacts(type) {
52645             var flags = type.flags;
52646             if (flags & 4 /* String */) {
52647                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
52648             }
52649             if (flags & 128 /* StringLiteral */) {
52650                 var isEmpty = type.value === "";
52651                 return strictNullChecks ?
52652                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
52653                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
52654             }
52655             if (flags & (8 /* Number */ | 32 /* Enum */)) {
52656                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
52657             }
52658             if (flags & 256 /* NumberLiteral */) {
52659                 var isZero = type.value === 0;
52660                 return strictNullChecks ?
52661                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
52662                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
52663             }
52664             if (flags & 64 /* BigInt */) {
52665                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
52666             }
52667             if (flags & 2048 /* BigIntLiteral */) {
52668                 var isZero = isZeroBigInt(type);
52669                 return strictNullChecks ?
52670                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
52671                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
52672             }
52673             if (flags & 16 /* Boolean */) {
52674                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
52675             }
52676             if (flags & 528 /* BooleanLike */) {
52677                 return strictNullChecks ?
52678                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
52679                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
52680             }
52681             if (flags & 524288 /* Object */) {
52682                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
52683                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
52684                     isFunctionObjectType(type) ?
52685                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
52686                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52687             }
52688             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
52689                 return 9830144 /* UndefinedFacts */;
52690             }
52691             if (flags & 65536 /* Null */) {
52692                 return 9363232 /* NullFacts */;
52693             }
52694             if (flags & 12288 /* ESSymbolLike */) {
52695                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
52696             }
52697             if (flags & 67108864 /* NonPrimitive */) {
52698                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52699             }
52700             if (flags & 131072 /* Never */) {
52701                 return 0 /* None */;
52702             }
52703             if (flags & 63176704 /* Instantiable */) {
52704                 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
52705             }
52706             if (flags & 3145728 /* UnionOrIntersection */) {
52707                 return getTypeFactsOfTypes(type.types);
52708             }
52709             return 16777215 /* All */;
52710         }
52711         function getTypeWithFacts(type, include) {
52712             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
52713         }
52714         function getTypeWithDefault(type, defaultExpression) {
52715             if (defaultExpression) {
52716                 var defaultType = getTypeOfExpression(defaultExpression);
52717                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
52718             }
52719             return type;
52720         }
52721         function getTypeOfDestructuredProperty(type, name) {
52722             var nameType = getLiteralTypeFromPropertyName(name);
52723             if (!isTypeUsableAsPropertyName(nameType))
52724                 return errorType;
52725             var text = getPropertyNameFromType(nameType);
52726             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
52727                 isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
52728                 getIndexTypeOfType(type, 0 /* String */) ||
52729                 errorType;
52730         }
52731         function getTypeOfDestructuredArrayElement(type, index) {
52732             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
52733                 checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) ||
52734                 errorType;
52735         }
52736         function getTypeOfDestructuredSpreadExpression(type) {
52737             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
52738         }
52739         function getAssignedTypeOfBinaryExpression(node) {
52740             var isDestructuringDefaultAssignment = node.parent.kind === 192 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
52741                 node.parent.kind === 281 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
52742             return isDestructuringDefaultAssignment ?
52743                 getTypeWithDefault(getAssignedType(node), node.right) :
52744                 getTypeOfExpression(node.right);
52745         }
52746         function isDestructuringAssignmentTarget(parent) {
52747             return parent.parent.kind === 209 /* BinaryExpression */ && parent.parent.left === parent ||
52748                 parent.parent.kind === 232 /* ForOfStatement */ && parent.parent.initializer === parent;
52749         }
52750         function getAssignedTypeOfArrayLiteralElement(node, element) {
52751             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
52752         }
52753         function getAssignedTypeOfSpreadExpression(node) {
52754             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
52755         }
52756         function getAssignedTypeOfPropertyAssignment(node) {
52757             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
52758         }
52759         function getAssignedTypeOfShorthandPropertyAssignment(node) {
52760             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
52761         }
52762         function getAssignedType(node) {
52763             var parent = node.parent;
52764             switch (parent.kind) {
52765                 case 231 /* ForInStatement */:
52766                     return stringType;
52767                 case 232 /* ForOfStatement */:
52768                     return checkRightHandSideOfForOf(parent) || errorType;
52769                 case 209 /* BinaryExpression */:
52770                     return getAssignedTypeOfBinaryExpression(parent);
52771                 case 203 /* DeleteExpression */:
52772                     return undefinedType;
52773                 case 192 /* ArrayLiteralExpression */:
52774                     return getAssignedTypeOfArrayLiteralElement(parent, node);
52775                 case 213 /* SpreadElement */:
52776                     return getAssignedTypeOfSpreadExpression(parent);
52777                 case 281 /* PropertyAssignment */:
52778                     return getAssignedTypeOfPropertyAssignment(parent);
52779                 case 282 /* ShorthandPropertyAssignment */:
52780                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
52781             }
52782             return errorType;
52783         }
52784         function getInitialTypeOfBindingElement(node) {
52785             var pattern = node.parent;
52786             var parentType = getInitialType(pattern.parent);
52787             var type = pattern.kind === 189 /* ObjectBindingPattern */ ?
52788                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
52789                 !node.dotDotDotToken ?
52790                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
52791                     getTypeOfDestructuredSpreadExpression(parentType);
52792             return getTypeWithDefault(type, node.initializer);
52793         }
52794         function getTypeOfInitializer(node) {
52795             // Return the cached type if one is available. If the type of the variable was inferred
52796             // from its initializer, we'll already have cached the type. Otherwise we compute it now
52797             // without caching such that transient types are reflected.
52798             var links = getNodeLinks(node);
52799             return links.resolvedType || getTypeOfExpression(node);
52800         }
52801         function getInitialTypeOfVariableDeclaration(node) {
52802             if (node.initializer) {
52803                 return getTypeOfInitializer(node.initializer);
52804             }
52805             if (node.parent.parent.kind === 231 /* ForInStatement */) {
52806                 return stringType;
52807             }
52808             if (node.parent.parent.kind === 232 /* ForOfStatement */) {
52809                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
52810             }
52811             return errorType;
52812         }
52813         function getInitialType(node) {
52814             return node.kind === 242 /* VariableDeclaration */ ?
52815                 getInitialTypeOfVariableDeclaration(node) :
52816                 getInitialTypeOfBindingElement(node);
52817         }
52818         function isEmptyArrayAssignment(node) {
52819             return node.kind === 242 /* VariableDeclaration */ && node.initializer &&
52820                 isEmptyArrayLiteral(node.initializer) ||
52821                 node.kind !== 191 /* BindingElement */ && node.parent.kind === 209 /* BinaryExpression */ &&
52822                     isEmptyArrayLiteral(node.parent.right);
52823         }
52824         function getReferenceCandidate(node) {
52825             switch (node.kind) {
52826                 case 200 /* ParenthesizedExpression */:
52827                     return getReferenceCandidate(node.expression);
52828                 case 209 /* BinaryExpression */:
52829                     switch (node.operatorToken.kind) {
52830                         case 62 /* EqualsToken */:
52831                             return getReferenceCandidate(node.left);
52832                         case 27 /* CommaToken */:
52833                             return getReferenceCandidate(node.right);
52834                     }
52835             }
52836             return node;
52837         }
52838         function getReferenceRoot(node) {
52839             var parent = node.parent;
52840             return parent.kind === 200 /* ParenthesizedExpression */ ||
52841                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
52842                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
52843                 getReferenceRoot(parent) : node;
52844         }
52845         function getTypeOfSwitchClause(clause) {
52846             if (clause.kind === 277 /* CaseClause */) {
52847                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
52848             }
52849             return neverType;
52850         }
52851         function getSwitchClauseTypes(switchStatement) {
52852             var links = getNodeLinks(switchStatement);
52853             if (!links.switchTypes) {
52854                 links.switchTypes = [];
52855                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52856                     var clause = _a[_i];
52857                     links.switchTypes.push(getTypeOfSwitchClause(clause));
52858                 }
52859             }
52860             return links.switchTypes;
52861         }
52862         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
52863             var witnesses = [];
52864             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52865                 var clause = _a[_i];
52866                 if (clause.kind === 277 /* CaseClause */) {
52867                     if (ts.isStringLiteralLike(clause.expression)) {
52868                         witnesses.push(clause.expression.text);
52869                         continue;
52870                     }
52871                     return ts.emptyArray;
52872                 }
52873                 if (retainDefault)
52874                     witnesses.push(/*explicitDefaultStatement*/ undefined);
52875             }
52876             return witnesses;
52877         }
52878         function eachTypeContainedIn(source, types) {
52879             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
52880         }
52881         function isTypeSubsetOf(source, target) {
52882             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
52883         }
52884         function isTypeSubsetOfUnion(source, target) {
52885             if (source.flags & 1048576 /* Union */) {
52886                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52887                     var t = _a[_i];
52888                     if (!containsType(target.types, t)) {
52889                         return false;
52890                     }
52891                 }
52892                 return true;
52893             }
52894             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
52895                 return true;
52896             }
52897             return containsType(target.types, source);
52898         }
52899         function forEachType(type, f) {
52900             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
52901         }
52902         function everyType(type, f) {
52903             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
52904         }
52905         function filterType(type, f) {
52906             if (type.flags & 1048576 /* Union */) {
52907                 var types = type.types;
52908                 var filtered = ts.filter(types, f);
52909                 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
52910             }
52911             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
52912         }
52913         function countTypes(type) {
52914             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
52915         }
52916         function mapType(type, mapper, noReductions) {
52917             if (type.flags & 131072 /* Never */) {
52918                 return type;
52919             }
52920             if (!(type.flags & 1048576 /* Union */)) {
52921                 return mapper(type);
52922             }
52923             var mappedTypes;
52924             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
52925                 var t = _a[_i];
52926                 var mapped = mapper(t);
52927                 if (mapped) {
52928                     if (!mappedTypes) {
52929                         mappedTypes = [mapped];
52930                     }
52931                     else {
52932                         mappedTypes.push(mapped);
52933                     }
52934                 }
52935             }
52936             return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
52937         }
52938         function extractTypesOfKind(type, kind) {
52939             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
52940         }
52941         // Return a new type in which occurrences of the string and number primitive types in
52942         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
52943         // literals in typeWithLiterals, respectively.
52944         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
52945             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
52946                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
52947                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
52948                 return mapType(typeWithPrimitives, function (t) {
52949                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
52950                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
52951                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
52952                 });
52953             }
52954             return typeWithPrimitives;
52955         }
52956         function isIncomplete(flowType) {
52957             return flowType.flags === 0;
52958         }
52959         function getTypeFromFlowType(flowType) {
52960             return flowType.flags === 0 ? flowType.type : flowType;
52961         }
52962         function createFlowType(type, incomplete) {
52963             return incomplete ? { flags: 0, type: type } : type;
52964         }
52965         // An evolving array type tracks the element types that have so far been seen in an
52966         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
52967         // array types are ultimately converted into manifest array types (using getFinalArrayType)
52968         // and never escape the getFlowTypeOfReference function.
52969         function createEvolvingArrayType(elementType) {
52970             var result = createObjectType(256 /* EvolvingArray */);
52971             result.elementType = elementType;
52972             return result;
52973         }
52974         function getEvolvingArrayType(elementType) {
52975             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
52976         }
52977         // When adding evolving array element types we do not perform subtype reduction. Instead,
52978         // we defer subtype reduction until the evolving array type is finalized into a manifest
52979         // array type.
52980         function addEvolvingArrayElementType(evolvingArrayType, node) {
52981             var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
52982             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
52983         }
52984         function createFinalArrayType(elementType) {
52985             return elementType.flags & 131072 /* Never */ ?
52986                 autoArrayType :
52987                 createArrayType(elementType.flags & 1048576 /* Union */ ?
52988                     getUnionType(elementType.types, 2 /* Subtype */) :
52989                     elementType);
52990         }
52991         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
52992         function getFinalArrayType(evolvingArrayType) {
52993             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
52994         }
52995         function finalizeEvolvingArrayType(type) {
52996             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
52997         }
52998         function getElementTypeOfEvolvingArrayType(type) {
52999             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
53000         }
53001         function isEvolvingArrayTypeList(types) {
53002             var hasEvolvingArrayType = false;
53003             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
53004                 var t = types_16[_i];
53005                 if (!(t.flags & 131072 /* Never */)) {
53006                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
53007                         return false;
53008                     }
53009                     hasEvolvingArrayType = true;
53010                 }
53011             }
53012             return hasEvolvingArrayType;
53013         }
53014         // At flow control branch or loop junctions, if the type along every antecedent code path
53015         // is an evolving array type, we construct a combined evolving array type. Otherwise we
53016         // finalize all evolving array types.
53017         function getUnionOrEvolvingArrayType(types, subtypeReduction) {
53018             return isEvolvingArrayTypeList(types) ?
53019                 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
53020                 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
53021         }
53022         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
53023         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
53024         function isEvolvingArrayOperationTarget(node) {
53025             var root = getReferenceRoot(node);
53026             var parent = root.parent;
53027             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
53028                 parent.parent.kind === 196 /* CallExpression */
53029                     && ts.isIdentifier(parent.name)
53030                     && ts.isPushOrUnshiftIdentifier(parent.name));
53031             var isElementAssignment = parent.kind === 195 /* ElementAccessExpression */ &&
53032                 parent.expression === root &&
53033                 parent.parent.kind === 209 /* BinaryExpression */ &&
53034                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
53035                 parent.parent.left === parent &&
53036                 !ts.isAssignmentTarget(parent.parent) &&
53037                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
53038             return isLengthPushOrUnshift || isElementAssignment;
53039         }
53040         function isDeclarationWithExplicitTypeAnnotation(declaration) {
53041             return (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ ||
53042                 declaration.kind === 159 /* PropertyDeclaration */ || declaration.kind === 158 /* PropertySignature */) &&
53043                 !!ts.getEffectiveTypeAnnotationNode(declaration);
53044         }
53045         function getExplicitTypeOfSymbol(symbol, diagnostic) {
53046             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
53047                 return getTypeOfSymbol(symbol);
53048             }
53049             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
53050                 var declaration = symbol.valueDeclaration;
53051                 if (declaration) {
53052                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
53053                         return getTypeOfSymbol(symbol);
53054                     }
53055                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
53056                         var statement = declaration.parent.parent;
53057                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
53058                         if (expressionType) {
53059                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
53060                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
53061                         }
53062                     }
53063                     if (diagnostic) {
53064                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
53065                     }
53066                 }
53067             }
53068         }
53069         // We require the dotted function name in an assertion expression to be comprised of identifiers
53070         // that reference function, method, class or value module symbols; or variable, property or
53071         // parameter symbols with declarations that have explicit type annotations. Such references are
53072         // resolvable with no possibility of triggering circularities in control flow analysis.
53073         function getTypeOfDottedName(node, diagnostic) {
53074             if (!(node.flags & 16777216 /* InWithStatement */)) {
53075                 switch (node.kind) {
53076                     case 75 /* Identifier */:
53077                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
53078                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
53079                     case 104 /* ThisKeyword */:
53080                         return getExplicitThisType(node);
53081                     case 102 /* SuperKeyword */:
53082                         return checkSuperExpression(node);
53083                     case 194 /* PropertyAccessExpression */:
53084                         var type = getTypeOfDottedName(node.expression, diagnostic);
53085                         var prop = type && getPropertyOfType(type, node.name.escapedText);
53086                         return prop && getExplicitTypeOfSymbol(prop, diagnostic);
53087                     case 200 /* ParenthesizedExpression */:
53088                         return getTypeOfDottedName(node.expression, diagnostic);
53089                 }
53090             }
53091         }
53092         function getEffectsSignature(node) {
53093             var links = getNodeLinks(node);
53094             var signature = links.effectsSignature;
53095             if (signature === undefined) {
53096                 // A call expression parented by an expression statement is a potential assertion. Other call
53097                 // expressions are potential type predicate function calls. In order to avoid triggering
53098                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
53099                 // target expression of an assertion.
53100                 var funcType = void 0;
53101                 if (node.parent.kind === 226 /* ExpressionStatement */) {
53102                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
53103                 }
53104                 else if (node.expression.kind !== 102 /* SuperKeyword */) {
53105                     if (ts.isOptionalChain(node)) {
53106                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
53107                     }
53108                     else {
53109                         funcType = checkNonNullExpression(node.expression);
53110                     }
53111                 }
53112                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
53113                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
53114                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
53115                         undefined;
53116                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
53117             }
53118             return signature === unknownSignature ? undefined : signature;
53119         }
53120         function hasTypePredicateOrNeverReturnType(signature) {
53121             return !!(getTypePredicateOfSignature(signature) ||
53122                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
53123         }
53124         function getTypePredicateArgument(predicate, callExpression) {
53125             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
53126                 return callExpression.arguments[predicate.parameterIndex];
53127             }
53128             var invokedExpression = ts.skipParentheses(callExpression.expression);
53129             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
53130         }
53131         function reportFlowControlError(node) {
53132             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
53133             var sourceFile = ts.getSourceFileOfNode(node);
53134             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
53135             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
53136         }
53137         function isReachableFlowNode(flow) {
53138             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
53139             lastFlowNode = flow;
53140             lastFlowNodeReachable = result;
53141             return result;
53142         }
53143         function isFalseExpression(expr) {
53144             var node = ts.skipParentheses(expr);
53145             return node.kind === 91 /* FalseKeyword */ || node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
53146                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
53147         }
53148         function isReachableFlowNodeWorker(flow, noCacheCheck) {
53149             while (true) {
53150                 if (flow === lastFlowNode) {
53151                     return lastFlowNodeReachable;
53152                 }
53153                 var flags = flow.flags;
53154                 if (flags & 4096 /* Shared */) {
53155                     if (!noCacheCheck) {
53156                         var id = getFlowNodeId(flow);
53157                         var reachable = flowNodeReachable[id];
53158                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
53159                     }
53160                     noCacheCheck = false;
53161                 }
53162                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
53163                     flow = flow.antecedent;
53164                 }
53165                 else if (flags & 512 /* Call */) {
53166                     var signature = getEffectsSignature(flow.node);
53167                     if (signature) {
53168                         var predicate = getTypePredicateOfSignature(signature);
53169                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */) {
53170                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
53171                             if (predicateArgument && isFalseExpression(predicateArgument)) {
53172                                 return false;
53173                             }
53174                         }
53175                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53176                             return false;
53177                         }
53178                     }
53179                     flow = flow.antecedent;
53180                 }
53181                 else if (flags & 4 /* BranchLabel */) {
53182                     // A branching point is reachable if any branch is reachable.
53183                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
53184                 }
53185                 else if (flags & 8 /* LoopLabel */) {
53186                     // A loop is reachable if the control flow path that leads to the top is reachable.
53187                     flow = flow.antecedents[0];
53188                 }
53189                 else if (flags & 128 /* SwitchClause */) {
53190                     // The control flow path representing an unmatched value in a switch statement with
53191                     // no default clause is unreachable if the switch statement is exhaustive.
53192                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
53193                         return false;
53194                     }
53195                     flow = flow.antecedent;
53196                 }
53197                 else if (flags & 1024 /* ReduceLabel */) {
53198                     // Cache is unreliable once we start adjusting labels
53199                     lastFlowNode = undefined;
53200                     var target = flow.target;
53201                     var saveAntecedents = target.antecedents;
53202                     target.antecedents = flow.antecedents;
53203                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
53204                     target.antecedents = saveAntecedents;
53205                     return result;
53206                 }
53207                 else {
53208                     return !(flags & 1 /* Unreachable */);
53209                 }
53210             }
53211         }
53212         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
53213             if (initialType === void 0) { initialType = declaredType; }
53214             var key;
53215             var keySet = false;
53216             var flowDepth = 0;
53217             if (flowAnalysisDisabled) {
53218                 return errorType;
53219             }
53220             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
53221                 return declaredType;
53222             }
53223             flowInvocationCount++;
53224             var sharedFlowStart = sharedFlowCount;
53225             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
53226             sharedFlowCount = sharedFlowStart;
53227             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
53228             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
53229             // on empty arrays are possible without implicit any errors and new element types can be inferred without
53230             // type mismatch errors.
53231             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
53232             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 218 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
53233                 return declaredType;
53234             }
53235             return resultType;
53236             function getOrSetCacheKey() {
53237                 if (keySet) {
53238                     return key;
53239                 }
53240                 keySet = true;
53241                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
53242             }
53243             function getTypeAtFlowNode(flow) {
53244                 if (flowDepth === 2000) {
53245                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
53246                     // and disable further control flow analysis in the containing function or module body.
53247                     flowAnalysisDisabled = true;
53248                     reportFlowControlError(reference);
53249                     return errorType;
53250                 }
53251                 flowDepth++;
53252                 while (true) {
53253                     var flags = flow.flags;
53254                     if (flags & 4096 /* Shared */) {
53255                         // We cache results of flow type resolution for shared nodes that were previously visited in
53256                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
53257                         // antecedent of more than one node.
53258                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
53259                             if (sharedFlowNodes[i] === flow) {
53260                                 flowDepth--;
53261                                 return sharedFlowTypes[i];
53262                             }
53263                         }
53264                     }
53265                     var type = void 0;
53266                     if (flags & 16 /* Assignment */) {
53267                         type = getTypeAtFlowAssignment(flow);
53268                         if (!type) {
53269                             flow = flow.antecedent;
53270                             continue;
53271                         }
53272                     }
53273                     else if (flags & 512 /* Call */) {
53274                         type = getTypeAtFlowCall(flow);
53275                         if (!type) {
53276                             flow = flow.antecedent;
53277                             continue;
53278                         }
53279                     }
53280                     else if (flags & 96 /* Condition */) {
53281                         type = getTypeAtFlowCondition(flow);
53282                     }
53283                     else if (flags & 128 /* SwitchClause */) {
53284                         type = getTypeAtSwitchClause(flow);
53285                     }
53286                     else if (flags & 12 /* Label */) {
53287                         if (flow.antecedents.length === 1) {
53288                             flow = flow.antecedents[0];
53289                             continue;
53290                         }
53291                         type = flags & 4 /* BranchLabel */ ?
53292                             getTypeAtFlowBranchLabel(flow) :
53293                             getTypeAtFlowLoopLabel(flow);
53294                     }
53295                     else if (flags & 256 /* ArrayMutation */) {
53296                         type = getTypeAtFlowArrayMutation(flow);
53297                         if (!type) {
53298                             flow = flow.antecedent;
53299                             continue;
53300                         }
53301                     }
53302                     else if (flags & 1024 /* ReduceLabel */) {
53303                         var target = flow.target;
53304                         var saveAntecedents = target.antecedents;
53305                         target.antecedents = flow.antecedents;
53306                         type = getTypeAtFlowNode(flow.antecedent);
53307                         target.antecedents = saveAntecedents;
53308                     }
53309                     else if (flags & 2 /* Start */) {
53310                         // Check if we should continue with the control flow of the containing function.
53311                         var container = flow.node;
53312                         if (container && container !== flowContainer &&
53313                             reference.kind !== 194 /* PropertyAccessExpression */ &&
53314                             reference.kind !== 195 /* ElementAccessExpression */ &&
53315                             reference.kind !== 104 /* ThisKeyword */) {
53316                             flow = container.flowNode;
53317                             continue;
53318                         }
53319                         // At the top of the flow we have the initial type.
53320                         type = initialType;
53321                     }
53322                     else {
53323                         // Unreachable code errors are reported in the binding phase. Here we
53324                         // simply return the non-auto declared type to reduce follow-on errors.
53325                         type = convertAutoToAny(declaredType);
53326                     }
53327                     if (flags & 4096 /* Shared */) {
53328                         // Record visited node and the associated type in the cache.
53329                         sharedFlowNodes[sharedFlowCount] = flow;
53330                         sharedFlowTypes[sharedFlowCount] = type;
53331                         sharedFlowCount++;
53332                     }
53333                     flowDepth--;
53334                     return type;
53335                 }
53336             }
53337             function getInitialOrAssignedType(flow) {
53338                 var node = flow.node;
53339                 return getConstraintForLocation(node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */ ?
53340                     getInitialType(node) :
53341                     getAssignedType(node), reference);
53342             }
53343             function getTypeAtFlowAssignment(flow) {
53344                 var node = flow.node;
53345                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
53346                 // only need to evaluate the assigned type if the declared type is a union type.
53347                 if (isMatchingReference(reference, node)) {
53348                     if (!isReachableFlowNode(flow)) {
53349                         return unreachableNeverType;
53350                     }
53351                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
53352                         var flowType = getTypeAtFlowNode(flow.antecedent);
53353                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
53354                     }
53355                     if (declaredType === autoType || declaredType === autoArrayType) {
53356                         if (isEmptyArrayAssignment(node)) {
53357                             return getEvolvingArrayType(neverType);
53358                         }
53359                         var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow));
53360                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
53361                     }
53362                     if (declaredType.flags & 1048576 /* Union */) {
53363                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
53364                     }
53365                     return declaredType;
53366                 }
53367                 // We didn't have a direct match. However, if the reference is a dotted name, this
53368                 // may be an assignment to a left hand part of the reference. For example, for a
53369                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
53370                 // return the declared type.
53371                 if (containsMatchingReference(reference, node)) {
53372                     if (!isReachableFlowNode(flow)) {
53373                         return unreachableNeverType;
53374                     }
53375                     // A matching dotted name might also be an expando property on a function *expression*,
53376                     // in which case we continue control flow analysis back to the function's declaration
53377                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
53378                         var init = ts.getDeclaredExpandoInitializer(node);
53379                         if (init && (init.kind === 201 /* FunctionExpression */ || init.kind === 202 /* ArrowFunction */)) {
53380                             return getTypeAtFlowNode(flow.antecedent);
53381                         }
53382                     }
53383                     return declaredType;
53384                 }
53385                 // for (const _ in ref) acts as a nonnull on ref
53386                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 231 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
53387                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
53388                 }
53389                 // Assignment doesn't affect reference
53390                 return undefined;
53391             }
53392             function narrowTypeByAssertion(type, expr) {
53393                 var node = ts.skipParentheses(expr);
53394                 if (node.kind === 91 /* FalseKeyword */) {
53395                     return unreachableNeverType;
53396                 }
53397                 if (node.kind === 209 /* BinaryExpression */) {
53398                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
53399                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
53400                     }
53401                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
53402                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
53403                     }
53404                 }
53405                 return narrowType(type, node, /*assumeTrue*/ true);
53406             }
53407             function getTypeAtFlowCall(flow) {
53408                 var signature = getEffectsSignature(flow.node);
53409                 if (signature) {
53410                     var predicate = getTypePredicateOfSignature(signature);
53411                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
53412                         var flowType = getTypeAtFlowNode(flow.antecedent);
53413                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
53414                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
53415                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
53416                                 type;
53417                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
53418                     }
53419                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53420                         return unreachableNeverType;
53421                     }
53422                 }
53423                 return undefined;
53424             }
53425             function getTypeAtFlowArrayMutation(flow) {
53426                 if (declaredType === autoType || declaredType === autoArrayType) {
53427                     var node = flow.node;
53428                     var expr = node.kind === 196 /* CallExpression */ ?
53429                         node.expression.expression :
53430                         node.left.expression;
53431                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
53432                         var flowType = getTypeAtFlowNode(flow.antecedent);
53433                         var type = getTypeFromFlowType(flowType);
53434                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
53435                             var evolvedType_1 = type;
53436                             if (node.kind === 196 /* CallExpression */) {
53437                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
53438                                     var arg = _a[_i];
53439                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
53440                                 }
53441                             }
53442                             else {
53443                                 // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time)
53444                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
53445                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
53446                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
53447                                 }
53448                             }
53449                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
53450                         }
53451                         return flowType;
53452                     }
53453                 }
53454                 return undefined;
53455             }
53456             function getTypeAtFlowCondition(flow) {
53457                 var flowType = getTypeAtFlowNode(flow.antecedent);
53458                 var type = getTypeFromFlowType(flowType);
53459                 if (type.flags & 131072 /* Never */) {
53460                     return flowType;
53461                 }
53462                 // If we have an antecedent type (meaning we're reachable in some way), we first
53463                 // attempt to narrow the antecedent type. If that produces the never type, and if
53464                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
53465                 // take the type guard as an indication that control *could* reach here once we
53466                 // have the complete type. We proceed by switching to the silent never type which
53467                 // doesn't report errors when operators are applied to it. Note that this is the
53468                 // *only* place a silent never type is ever generated.
53469                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
53470                 var nonEvolvingType = finalizeEvolvingArrayType(type);
53471                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
53472                 if (narrowedType === nonEvolvingType) {
53473                     return flowType;
53474                 }
53475                 var incomplete = isIncomplete(flowType);
53476                 var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType;
53477                 return createFlowType(resultType, incomplete);
53478             }
53479             function getTypeAtSwitchClause(flow) {
53480                 var expr = flow.switchStatement.expression;
53481                 var flowType = getTypeAtFlowNode(flow.antecedent);
53482                 var type = getTypeFromFlowType(flowType);
53483                 if (isMatchingReference(reference, expr)) {
53484                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53485                 }
53486                 else if (expr.kind === 204 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
53487                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53488                 }
53489                 else {
53490                     if (strictNullChecks) {
53491                         if (optionalChainContainsReference(expr, reference)) {
53492                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
53493                         }
53494                         else if (expr.kind === 204 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
53495                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
53496                         }
53497                     }
53498                     if (isMatchingReferenceDiscriminant(expr, type)) {
53499                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
53500                     }
53501                 }
53502                 return createFlowType(type, isIncomplete(flowType));
53503             }
53504             function getTypeAtFlowBranchLabel(flow) {
53505                 var antecedentTypes = [];
53506                 var subtypeReduction = false;
53507                 var seenIncomplete = false;
53508                 var bypassFlow;
53509                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53510                     var antecedent = _a[_i];
53511                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
53512                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
53513                         bypassFlow = antecedent;
53514                         continue;
53515                     }
53516                     var flowType = getTypeAtFlowNode(antecedent);
53517                     var type = getTypeFromFlowType(flowType);
53518                     // If the type at a particular antecedent path is the declared type and the
53519                     // reference is known to always be assigned (i.e. when declared and initial types
53520                     // are the same), there is no reason to process more antecedents since the only
53521                     // possible outcome is subtypes that will be removed in the final union type anyway.
53522                     if (type === declaredType && declaredType === initialType) {
53523                         return type;
53524                     }
53525                     ts.pushIfUnique(antecedentTypes, type);
53526                     // If an antecedent type is not a subset of the declared type, we need to perform
53527                     // subtype reduction. This happens when a "foreign" type is injected into the control
53528                     // flow using the instanceof operator or a user defined type predicate.
53529                     if (!isTypeSubsetOf(type, declaredType)) {
53530                         subtypeReduction = true;
53531                     }
53532                     if (isIncomplete(flowType)) {
53533                         seenIncomplete = true;
53534                     }
53535                 }
53536                 if (bypassFlow) {
53537                     var flowType = getTypeAtFlowNode(bypassFlow);
53538                     var type = getTypeFromFlowType(flowType);
53539                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
53540                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
53541                     // the risk of circularities, we only want to perform them when they make a difference.
53542                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
53543                         if (type === declaredType && declaredType === initialType) {
53544                             return type;
53545                         }
53546                         antecedentTypes.push(type);
53547                         if (!isTypeSubsetOf(type, declaredType)) {
53548                             subtypeReduction = true;
53549                         }
53550                         if (isIncomplete(flowType)) {
53551                             seenIncomplete = true;
53552                         }
53553                     }
53554                 }
53555                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
53556             }
53557             function getTypeAtFlowLoopLabel(flow) {
53558                 // If we have previously computed the control flow type for the reference at
53559                 // this flow loop junction, return the cached type.
53560                 var id = getFlowNodeId(flow);
53561                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
53562                 var key = getOrSetCacheKey();
53563                 if (!key) {
53564                     // No cache key is generated when binding patterns are in unnarrowable situations
53565                     return declaredType;
53566                 }
53567                 var cached = cache.get(key);
53568                 if (cached) {
53569                     return cached;
53570                 }
53571                 // If this flow loop junction and reference are already being processed, return
53572                 // the union of the types computed for each branch so far, marked as incomplete.
53573                 // It is possible to see an empty array in cases where loops are nested and the
53574                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
53575                 // In such cases we restart the analysis of the inner loop, which will then see
53576                 // a non-empty in-process array for the outer loop and eventually terminate because
53577                 // the first antecedent of a loop junction is always the non-looping control flow
53578                 // path that leads to the top.
53579                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
53580                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
53581                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
53582                     }
53583                 }
53584                 // Add the flow loop junction and reference to the in-process stack and analyze
53585                 // each antecedent code path.
53586                 var antecedentTypes = [];
53587                 var subtypeReduction = false;
53588                 var firstAntecedentType;
53589                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53590                     var antecedent = _a[_i];
53591                     var flowType = void 0;
53592                     if (!firstAntecedentType) {
53593                         // The first antecedent of a loop junction is always the non-looping control
53594                         // flow path that leads to the top.
53595                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
53596                     }
53597                     else {
53598                         // All but the first antecedent are the looping control flow paths that lead
53599                         // back to the loop junction. We track these on the flow loop stack.
53600                         flowLoopNodes[flowLoopCount] = flow;
53601                         flowLoopKeys[flowLoopCount] = key;
53602                         flowLoopTypes[flowLoopCount] = antecedentTypes;
53603                         flowLoopCount++;
53604                         var saveFlowTypeCache = flowTypeCache;
53605                         flowTypeCache = undefined;
53606                         flowType = getTypeAtFlowNode(antecedent);
53607                         flowTypeCache = saveFlowTypeCache;
53608                         flowLoopCount--;
53609                         // If we see a value appear in the cache it is a sign that control flow analysis
53610                         // was restarted and completed by checkExpressionCached. We can simply pick up
53611                         // the resulting type and bail out.
53612                         var cached_1 = cache.get(key);
53613                         if (cached_1) {
53614                             return cached_1;
53615                         }
53616                     }
53617                     var type = getTypeFromFlowType(flowType);
53618                     ts.pushIfUnique(antecedentTypes, type);
53619                     // If an antecedent type is not a subset of the declared type, we need to perform
53620                     // subtype reduction. This happens when a "foreign" type is injected into the control
53621                     // flow using the instanceof operator or a user defined type predicate.
53622                     if (!isTypeSubsetOf(type, declaredType)) {
53623                         subtypeReduction = true;
53624                     }
53625                     // If the type at a particular antecedent path is the declared type there is no
53626                     // reason to process more antecedents since the only possible outcome is subtypes
53627                     // that will be removed in the final union type anyway.
53628                     if (type === declaredType) {
53629                         break;
53630                     }
53631                 }
53632                 // The result is incomplete if the first antecedent (the non-looping control flow path)
53633                 // is incomplete.
53634                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
53635                 if (isIncomplete(firstAntecedentType)) {
53636                     return createFlowType(result, /*incomplete*/ true);
53637                 }
53638                 cache.set(key, result);
53639                 return result;
53640             }
53641             function isMatchingReferenceDiscriminant(expr, computedType) {
53642                 if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
53643                     return false;
53644                 }
53645                 var name = getAccessedPropertyName(expr);
53646                 if (name === undefined) {
53647                     return false;
53648                 }
53649                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name);
53650             }
53651             function narrowTypeByDiscriminant(type, access, narrowType) {
53652                 var propName = getAccessedPropertyName(access);
53653                 if (propName === undefined) {
53654                     return type;
53655                 }
53656                 var propType = getTypeOfPropertyOfType(type, propName);
53657                 if (!propType) {
53658                     return type;
53659                 }
53660                 var narrowedPropType = narrowType(propType);
53661                 return filterType(type, function (t) {
53662                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
53663                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
53664                 });
53665             }
53666             function narrowTypeByTruthiness(type, expr, assumeTrue) {
53667                 if (isMatchingReference(reference, expr)) {
53668                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
53669                 }
53670                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
53671                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53672                 }
53673                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
53674                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
53675                 }
53676                 return type;
53677             }
53678             function isTypePresencePossible(type, propName, assumeTrue) {
53679                 if (getIndexInfoOfType(type, 0 /* String */)) {
53680                     return true;
53681                 }
53682                 var prop = getPropertyOfType(type, propName);
53683                 if (prop) {
53684                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
53685                 }
53686                 return !assumeTrue;
53687             }
53688             function narrowByInKeyword(type, literal, assumeTrue) {
53689                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */) || isThisTypeParameter(type)) {
53690                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
53691                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
53692                 }
53693                 return type;
53694             }
53695             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
53696                 switch (expr.operatorToken.kind) {
53697                     case 62 /* EqualsToken */:
53698                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
53699                     case 34 /* EqualsEqualsToken */:
53700                     case 35 /* ExclamationEqualsToken */:
53701                     case 36 /* EqualsEqualsEqualsToken */:
53702                     case 37 /* ExclamationEqualsEqualsToken */:
53703                         var operator_1 = expr.operatorToken.kind;
53704                         var left_1 = getReferenceCandidate(expr.left);
53705                         var right_1 = getReferenceCandidate(expr.right);
53706                         if (left_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
53707                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
53708                         }
53709                         if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
53710                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
53711                         }
53712                         if (isMatchingReference(reference, left_1)) {
53713                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
53714                         }
53715                         if (isMatchingReference(reference, right_1)) {
53716                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
53717                         }
53718                         if (strictNullChecks) {
53719                             if (optionalChainContainsReference(left_1, reference)) {
53720                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
53721                             }
53722                             else if (optionalChainContainsReference(right_1, reference)) {
53723                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
53724                             }
53725                         }
53726                         if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
53727                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
53728                         }
53729                         if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
53730                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
53731                         }
53732                         if (isMatchingConstructorReference(left_1)) {
53733                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
53734                         }
53735                         if (isMatchingConstructorReference(right_1)) {
53736                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
53737                         }
53738                         break;
53739                     case 98 /* InstanceOfKeyword */:
53740                         return narrowTypeByInstanceof(type, expr, assumeTrue);
53741                     case 97 /* InKeyword */:
53742                         var target = getReferenceCandidate(expr.right);
53743                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
53744                             return narrowByInKeyword(type, expr.left, assumeTrue);
53745                         }
53746                         break;
53747                     case 27 /* CommaToken */:
53748                         return narrowType(type, expr.right, assumeTrue);
53749                 }
53750                 return type;
53751             }
53752             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
53753                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
53754                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
53755                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
53756                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
53757                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
53758                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
53759                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
53760                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
53761                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
53762                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
53763                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
53764                 var valueType = getTypeOfExpression(value);
53765                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
53766                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
53767                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
53768                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53769             }
53770             function narrowTypeByEquality(type, operator, value, assumeTrue) {
53771                 if (type.flags & 1 /* Any */) {
53772                     return type;
53773                 }
53774                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53775                     assumeTrue = !assumeTrue;
53776                 }
53777                 var valueType = getTypeOfExpression(value);
53778                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
53779                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53780                         return valueType;
53781                     }
53782                     if (valueType.flags & 524288 /* Object */) {
53783                         return nonPrimitiveType;
53784                     }
53785                     return type;
53786                 }
53787                 if (valueType.flags & 98304 /* Nullable */) {
53788                     if (!strictNullChecks) {
53789                         return type;
53790                     }
53791                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
53792                     var facts = doubleEquals ?
53793                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
53794                         valueType.flags & 65536 /* Null */ ?
53795                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
53796                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
53797                     return getTypeWithFacts(type, facts);
53798                 }
53799                 if (type.flags & 67637251 /* NotUnionOrUnit */) {
53800                     return type;
53801                 }
53802                 if (assumeTrue) {
53803                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
53804                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
53805                         function (t) { return areTypesComparable(t, valueType); };
53806                     var narrowedType = filterType(type, filterFn);
53807                     return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
53808                 }
53809                 if (isUnitType(valueType)) {
53810                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
53811                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
53812                 }
53813                 return type;
53814             }
53815             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
53816                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
53817                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53818                     assumeTrue = !assumeTrue;
53819                 }
53820                 var target = getReferenceCandidate(typeOfExpr.expression);
53821                 if (!isMatchingReference(reference, target)) {
53822                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
53823                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53824                     }
53825                     return type;
53826                 }
53827                 if (type.flags & 1 /* Any */ && literal.text === "function") {
53828                     return type;
53829                 }
53830                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
53831                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
53832                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
53833                     if (typeOfExpr.parent.parent.kind === 209 /* BinaryExpression */) {
53834                         var expr = typeOfExpr.parent.parent;
53835                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
53836                             return nonPrimitiveType;
53837                         }
53838                     }
53839                     return getUnionType([nonPrimitiveType, nullType]);
53840                 }
53841                 var facts = assumeTrue ?
53842                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
53843                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
53844                 return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
53845                 function narrowTypeForTypeof(type) {
53846                     // We narrow a non-union type to an exact primitive type if the non-union type
53847                     // is a supertype of that primitive type. For example, type 'any' can be narrowed
53848                     // to one of the primitive types.
53849                     var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
53850                     if (targetType) {
53851                         if (isTypeSubtypeOf(type, targetType)) {
53852                             return type;
53853                         }
53854                         if (isTypeSubtypeOf(targetType, type)) {
53855                             return targetType;
53856                         }
53857                         if (type.flags & 63176704 /* Instantiable */) {
53858                             var constraint = getBaseConstraintOfType(type) || anyType;
53859                             if (isTypeSubtypeOf(targetType, constraint)) {
53860                                 return getIntersectionType([type, targetType]);
53861                             }
53862                         }
53863                     }
53864                     return type;
53865                 }
53866             }
53867             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
53868                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
53869                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53870             }
53871             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
53872                 // We only narrow if all case expressions specify
53873                 // values with unit types, except for the case where
53874                 // `type` is unknown. In this instance we map object
53875                 // types to the nonPrimitive type and narrow with that.
53876                 var switchTypes = getSwitchClauseTypes(switchStatement);
53877                 if (!switchTypes.length) {
53878                     return type;
53879                 }
53880                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
53881                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
53882                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
53883                     var groundClauseTypes = void 0;
53884                     for (var i = 0; i < clauseTypes.length; i += 1) {
53885                         var t = clauseTypes[i];
53886                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53887                             if (groundClauseTypes !== undefined) {
53888                                 groundClauseTypes.push(t);
53889                             }
53890                         }
53891                         else if (t.flags & 524288 /* Object */) {
53892                             if (groundClauseTypes === undefined) {
53893                                 groundClauseTypes = clauseTypes.slice(0, i);
53894                             }
53895                             groundClauseTypes.push(nonPrimitiveType);
53896                         }
53897                         else {
53898                             return type;
53899                         }
53900                     }
53901                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
53902                 }
53903                 var discriminantType = getUnionType(clauseTypes);
53904                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
53905                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
53906                 if (!hasDefaultClause) {
53907                     return caseType;
53908                 }
53909                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
53910                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
53911             }
53912             function getImpliedTypeFromTypeofCase(type, text) {
53913                 switch (text) {
53914                     case "function":
53915                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
53916                     case "object":
53917                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
53918                     default:
53919                         return typeofTypesByName.get(text) || type;
53920                 }
53921             }
53922             function narrowTypeForTypeofSwitch(candidate) {
53923                 return function (type) {
53924                     if (isTypeSubtypeOf(candidate, type)) {
53925                         return candidate;
53926                     }
53927                     if (type.flags & 63176704 /* Instantiable */) {
53928                         var constraint = getBaseConstraintOfType(type) || anyType;
53929                         if (isTypeSubtypeOf(candidate, constraint)) {
53930                             return getIntersectionType([type, candidate]);
53931                         }
53932                     }
53933                     return type;
53934                 };
53935             }
53936             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
53937                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
53938                 if (!switchWitnesses.length) {
53939                     return type;
53940                 }
53941                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
53942                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
53943                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
53944                 var clauseWitnesses;
53945                 var switchFacts;
53946                 if (defaultCaseLocation > -1) {
53947                     // We no longer need the undefined denoting an
53948                     // explicit default case. Remove the undefined and
53949                     // fix-up clauseStart and clauseEnd.  This means
53950                     // that we don't have to worry about undefined
53951                     // in the witness array.
53952                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
53953                     // The adjusted clause start and end after removing the `default` statement.
53954                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
53955                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
53956                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
53957                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
53958                 }
53959                 else {
53960                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
53961                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
53962                 }
53963                 if (hasDefaultClause) {
53964                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
53965                 }
53966                 /*
53967                   The implied type is the raw type suggested by a
53968                   value being caught in this clause.
53969
53970                   When the clause contains a default case we ignore
53971                   the implied type and try to narrow using any facts
53972                   we can learn: see `switchFacts`.
53973
53974                   Example:
53975                   switch (typeof x) {
53976                       case 'number':
53977                       case 'string': break;
53978                       default: break;
53979                       case 'number':
53980                       case 'boolean': break
53981                   }
53982
53983                   In the first clause (case `number` and `string`) the
53984                   implied type is number | string.
53985
53986                   In the default clause we de not compute an implied type.
53987
53988                   In the third clause (case `number` and `boolean`)
53989                   the naive implied type is number | boolean, however
53990                   we use the type facts to narrow the implied type to
53991                   boolean. We know that number cannot be selected
53992                   because it is caught in the first clause.
53993                 */
53994                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts);
53995                 if (impliedType.flags & 1048576 /* Union */) {
53996                     impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type));
53997                 }
53998                 return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts);
53999             }
54000             function isMatchingConstructorReference(expr) {
54001                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
54002                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
54003                     isMatchingReference(reference, expr.expression);
54004             }
54005             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
54006                 // Do not narrow when checking inequality.
54007                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
54008                     return type;
54009                 }
54010                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
54011                 var identifierType = getTypeOfExpression(identifier);
54012                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
54013                     return type;
54014                 }
54015                 // Get the prototype property of the type identifier so we can find out its type.
54016                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
54017                 if (!prototypeProperty) {
54018                     return type;
54019                 }
54020                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
54021                 var prototypeType = getTypeOfSymbol(prototypeProperty);
54022                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
54023                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
54024                     return type;
54025                 }
54026                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
54027                 if (isTypeAny(type)) {
54028                     return candidate;
54029                 }
54030                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
54031                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
54032                 function isConstructedBy(source, target) {
54033                     // If either the source or target type are a class type then we need to check that they are the same exact type.
54034                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
54035                     // that defines the same set of properties as class `A`, in that case they are structurally the same
54036                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
54037                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
54038                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
54039                         return source.symbol === target.symbol;
54040                     }
54041                     // For all other types just check that the `source` type is a subtype of the `target` type.
54042                     return isTypeSubtypeOf(source, target);
54043                 }
54044             }
54045             function narrowTypeByInstanceof(type, expr, assumeTrue) {
54046                 var left = getReferenceCandidate(expr.left);
54047                 if (!isMatchingReference(reference, left)) {
54048                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
54049                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54050                     }
54051                     return type;
54052                 }
54053                 // Check that right operand is a function type with a prototype property
54054                 var rightType = getTypeOfExpression(expr.right);
54055                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
54056                     return type;
54057                 }
54058                 var targetType;
54059                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
54060                 if (prototypeProperty) {
54061                     // Target type is type of the prototype property
54062                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
54063                     if (!isTypeAny(prototypePropertyType)) {
54064                         targetType = prototypePropertyType;
54065                     }
54066                 }
54067                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
54068                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
54069                     return type;
54070                 }
54071                 if (!targetType) {
54072                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
54073                     targetType = constructSignatures.length ?
54074                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
54075                         emptyObjectType;
54076                 }
54077                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
54078             }
54079             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
54080                 if (!assumeTrue) {
54081                     return filterType(type, function (t) { return !isRelated(t, candidate); });
54082                 }
54083                 // If the current type is a union type, remove all constituents that couldn't be instances of
54084                 // the candidate type. If one or more constituents remain, return a union of those.
54085                 if (type.flags & 1048576 /* Union */) {
54086                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
54087                     if (!(assignableType.flags & 131072 /* Never */)) {
54088                         return assignableType;
54089                     }
54090                 }
54091                 // If the candidate type is a subtype of the target type, narrow to the candidate type.
54092                 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
54093                 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
54094                 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
54095                 // two types.
54096                 return isTypeSubtypeOf(candidate, type) ? candidate :
54097                     isTypeAssignableTo(type, candidate) ? type :
54098                         isTypeAssignableTo(candidate, type) ? candidate :
54099                             getIntersectionType([type, candidate]);
54100             }
54101             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
54102                 if (hasMatchingArgument(callExpression, reference)) {
54103                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
54104                     var predicate = signature && getTypePredicateOfSignature(signature);
54105                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
54106                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
54107                     }
54108                 }
54109                 return type;
54110             }
54111             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
54112                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
54113                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
54114                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
54115                     if (predicateArgument) {
54116                         if (isMatchingReference(reference, predicateArgument)) {
54117                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
54118                         }
54119                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
54120                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
54121                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54122                         }
54123                         if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) {
54124                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
54125                         }
54126                     }
54127                 }
54128                 return type;
54129             }
54130             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
54131             // will be a subtype or the same type as the argument.
54132             function narrowType(type, expr, assumeTrue) {
54133                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
54134                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
54135                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
54136                     return narrowTypeByOptionality(type, expr, assumeTrue);
54137                 }
54138                 switch (expr.kind) {
54139                     case 75 /* Identifier */:
54140                     case 104 /* ThisKeyword */:
54141                     case 102 /* SuperKeyword */:
54142                     case 194 /* PropertyAccessExpression */:
54143                     case 195 /* ElementAccessExpression */:
54144                         return narrowTypeByTruthiness(type, expr, assumeTrue);
54145                     case 196 /* CallExpression */:
54146                         return narrowTypeByCallExpression(type, expr, assumeTrue);
54147                     case 200 /* ParenthesizedExpression */:
54148                         return narrowType(type, expr.expression, assumeTrue);
54149                     case 209 /* BinaryExpression */:
54150                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
54151                     case 207 /* PrefixUnaryExpression */:
54152                         if (expr.operator === 53 /* ExclamationToken */) {
54153                             return narrowType(type, expr.operand, !assumeTrue);
54154                         }
54155                         break;
54156                 }
54157                 return type;
54158             }
54159             function narrowTypeByOptionality(type, expr, assumePresent) {
54160                 if (isMatchingReference(reference, expr)) {
54161                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
54162                 }
54163                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
54164                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
54165                 }
54166                 return type;
54167             }
54168         }
54169         function getTypeOfSymbolAtLocation(symbol, location) {
54170             symbol = symbol.exportSymbol || symbol;
54171             // If we have an identifier or a property access at the given location, if the location is
54172             // an dotted name expression, and if the location is not an assignment target, obtain the type
54173             // of the expression (which will reflect control flow analysis). If the expression indeed
54174             // resolved to the given symbol, return the narrowed type.
54175             if (location.kind === 75 /* Identifier */) {
54176                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
54177                     location = location.parent;
54178                 }
54179                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
54180                     var type = getTypeOfExpression(location);
54181                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
54182                         return type;
54183                     }
54184                 }
54185             }
54186             // The location isn't a reference to the given symbol, meaning we're being asked
54187             // a hypothetical question of what type the symbol would have if there was a reference
54188             // to it at the given location. Since we have no control flow information for the
54189             // hypothetical reference (control flow information is created and attached by the
54190             // binder), we simply return the declared type of the symbol.
54191             return getTypeOfSymbol(symbol);
54192         }
54193         function getControlFlowContainer(node) {
54194             return ts.findAncestor(node.parent, function (node) {
54195                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
54196                     node.kind === 250 /* ModuleBlock */ ||
54197                     node.kind === 290 /* SourceFile */ ||
54198                     node.kind === 159 /* PropertyDeclaration */;
54199             });
54200         }
54201         // Check if a parameter is assigned anywhere within its declaring function.
54202         function isParameterAssigned(symbol) {
54203             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
54204             var links = getNodeLinks(func);
54205             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
54206                 links.flags |= 8388608 /* AssignmentsMarked */;
54207                 if (!hasParentWithAssignmentsMarked(func)) {
54208                     markParameterAssignments(func);
54209                 }
54210             }
54211             return symbol.isAssigned || false;
54212         }
54213         function hasParentWithAssignmentsMarked(node) {
54214             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
54215         }
54216         function markParameterAssignments(node) {
54217             if (node.kind === 75 /* Identifier */) {
54218                 if (ts.isAssignmentTarget(node)) {
54219                     var symbol = getResolvedSymbol(node);
54220                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 156 /* Parameter */) {
54221                         symbol.isAssigned = true;
54222                     }
54223                 }
54224             }
54225             else {
54226                 ts.forEachChild(node, markParameterAssignments);
54227             }
54228         }
54229         function isConstVariable(symbol) {
54230             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
54231         }
54232         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
54233         function removeOptionalityFromDeclaredType(declaredType, declaration) {
54234             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
54235                 var annotationIncludesUndefined = strictNullChecks &&
54236                     declaration.kind === 156 /* Parameter */ &&
54237                     declaration.initializer &&
54238                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
54239                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
54240                 popTypeResolution();
54241                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
54242             }
54243             else {
54244                 reportCircularityError(declaration.symbol);
54245                 return declaredType;
54246             }
54247         }
54248         function isConstraintPosition(node) {
54249             var parent = node.parent;
54250             return parent.kind === 194 /* PropertyAccessExpression */ ||
54251                 parent.kind === 196 /* CallExpression */ && parent.expression === node ||
54252                 parent.kind === 195 /* ElementAccessExpression */ && parent.expression === node ||
54253                 parent.kind === 191 /* BindingElement */ && parent.name === node && !!parent.initializer;
54254         }
54255         function typeHasNullableConstraint(type) {
54256             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
54257         }
54258         function getConstraintForLocation(type, node) {
54259             // When a node is the left hand expression of a property access, element access, or call expression,
54260             // and the type of the node includes type variables with constraints that are nullable, we fetch the
54261             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
54262             // the constraint type.
54263             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
54264                 return mapType(getWidenedType(type), getBaseConstraintOrType);
54265             }
54266             return type;
54267         }
54268         function isExportOrExportExpression(location) {
54269             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
54270         }
54271         function markAliasReferenced(symbol, location) {
54272             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
54273                 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
54274                     markAliasSymbolAsReferenced(symbol);
54275                 }
54276                 else {
54277                     markConstEnumAliasAsReferenced(symbol);
54278                 }
54279             }
54280         }
54281         function checkIdentifier(node) {
54282             var symbol = getResolvedSymbol(node);
54283             if (symbol === unknownSymbol) {
54284                 return errorType;
54285             }
54286             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
54287             // Although in down-level emit of arrow function, we emit it using function expression which means that
54288             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
54289             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
54290             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
54291             // can explicitly bound arguments objects
54292             if (symbol === argumentsSymbol) {
54293                 var container = ts.getContainingFunction(node);
54294                 if (languageVersion < 2 /* ES2015 */) {
54295                     if (container.kind === 202 /* ArrowFunction */) {
54296                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
54297                     }
54298                     else if (ts.hasModifier(container, 256 /* Async */)) {
54299                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method);
54300                     }
54301                 }
54302                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
54303                 return getTypeOfSymbol(symbol);
54304             }
54305             // We should only mark aliases as referenced if there isn't a local value declaration
54306             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
54307             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
54308                 markAliasReferenced(symbol, node);
54309             }
54310             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
54311             var declaration = localOrExportSymbol.valueDeclaration;
54312             if (localOrExportSymbol.flags & 32 /* Class */) {
54313                 // Due to the emit for class decorators, any reference to the class from inside of the class body
54314                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
54315                 // behavior of class names in ES6.
54316                 if (declaration.kind === 245 /* ClassDeclaration */
54317                     && ts.nodeIsDecorated(declaration)) {
54318                     var container = ts.getContainingClass(node);
54319                     while (container !== undefined) {
54320                         if (container === declaration && container.name !== node) {
54321                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54322                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54323                             break;
54324                         }
54325                         container = ts.getContainingClass(container);
54326                     }
54327                 }
54328                 else if (declaration.kind === 214 /* ClassExpression */) {
54329                     // When we emit a class expression with static members that contain a reference
54330                     // to the constructor in the initializer, we will need to substitute that
54331                     // binding with an alias as the class name is not in scope.
54332                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54333                     while (container.kind !== 290 /* SourceFile */) {
54334                         if (container.parent === declaration) {
54335                             if (container.kind === 159 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
54336                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54337                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54338                             }
54339                             break;
54340                         }
54341                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
54342                     }
54343                 }
54344             }
54345             checkNestedBlockScopedBinding(node, symbol);
54346             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
54347             var assignmentKind = ts.getAssignmentTargetKind(node);
54348             if (assignmentKind) {
54349                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
54350                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
54351                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
54352                     return errorType;
54353                 }
54354                 if (isReadonlySymbol(localOrExportSymbol)) {
54355                     if (localOrExportSymbol.flags & 3 /* Variable */) {
54356                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
54357                     }
54358                     else {
54359                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
54360                     }
54361                     return errorType;
54362                 }
54363             }
54364             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
54365             // We only narrow variables and parameters occurring in a non-assignment position. For all other
54366             // entities we simply return the declared type.
54367             if (localOrExportSymbol.flags & 3 /* Variable */) {
54368                 if (assignmentKind === 1 /* Definite */) {
54369                     return type;
54370                 }
54371             }
54372             else if (isAlias) {
54373                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
54374             }
54375             else {
54376                 return type;
54377             }
54378             if (!declaration) {
54379                 return type;
54380             }
54381             // The declaration container is the innermost function that encloses the declaration of the variable
54382             // or parameter. The flow container is the innermost function starting with which we analyze the control
54383             // flow graph to determine the control flow based type.
54384             var isParameter = ts.getRootDeclaration(declaration).kind === 156 /* Parameter */;
54385             var declarationContainer = getControlFlowContainer(declaration);
54386             var flowContainer = getControlFlowContainer(node);
54387             var isOuterVariable = flowContainer !== declarationContainer;
54388             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
54389             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
54390             // When the control flow originates in a function expression or arrow function and we are referencing
54391             // a const variable or parameter from an outer function, we extend the origin of the control flow
54392             // analysis to include the immediately enclosing function.
54393             while (flowContainer !== declarationContainer && (flowContainer.kind === 201 /* FunctionExpression */ ||
54394                 flowContainer.kind === 202 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
54395                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
54396                 flowContainer = getControlFlowContainer(flowContainer);
54397             }
54398             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
54399             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
54400             // declaration container are the same).
54401             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
54402                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
54403                     isInTypeQuery(node) || node.parent.kind === 263 /* ExportSpecifier */) ||
54404                 node.parent.kind === 218 /* NonNullExpression */ ||
54405                 declaration.kind === 242 /* VariableDeclaration */ && declaration.exclamationToken ||
54406                 declaration.flags & 8388608 /* Ambient */;
54407             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
54408                 type === autoType || type === autoArrayType ? undefinedType :
54409                     getOptionalType(type);
54410             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
54411             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
54412             // from declaration to use, and when the variable's declared type doesn't include undefined but the
54413             // control flow based type does include undefined.
54414             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
54415                 if (flowType === autoType || flowType === autoArrayType) {
54416                     if (noImplicitAny) {
54417                         error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
54418                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
54419                     }
54420                     return convertAutoToAny(flowType);
54421                 }
54422             }
54423             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
54424                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
54425                 // Return the declared type to reduce follow-on errors
54426                 return type;
54427             }
54428             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
54429         }
54430         function isInsideFunction(node, threshold) {
54431             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
54432         }
54433         function getPartOfForStatementContainingNode(node, container) {
54434             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
54435         }
54436         function checkNestedBlockScopedBinding(node, symbol) {
54437             if (languageVersion >= 2 /* ES2015 */ ||
54438                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
54439                 ts.isSourceFile(symbol.valueDeclaration) ||
54440                 symbol.valueDeclaration.parent.kind === 280 /* CatchClause */) {
54441                 return;
54442             }
54443             // 1. walk from the use site up to the declaration and check
54444             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
54445             // 2. walk from the declaration up to the boundary of lexical environment and check
54446             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
54447             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
54448             var usedInFunction = isInsideFunction(node.parent, container);
54449             var current = container;
54450             var containedInIterationStatement = false;
54451             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
54452                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
54453                     containedInIterationStatement = true;
54454                     break;
54455                 }
54456                 current = current.parent;
54457             }
54458             if (containedInIterationStatement) {
54459                 if (usedInFunction) {
54460                     // mark iteration statement as containing block-scoped binding captured in some function
54461                     var capturesBlockScopeBindingInLoopBody = true;
54462                     if (ts.isForStatement(container)) {
54463                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54464                         if (varDeclList && varDeclList.parent === container) {
54465                             var part = getPartOfForStatementContainingNode(node.parent, container);
54466                             if (part) {
54467                                 var links = getNodeLinks(part);
54468                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
54469                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
54470                                 ts.pushIfUnique(capturedBindings, symbol);
54471                                 if (part === container.initializer) {
54472                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
54473                                 }
54474                             }
54475                         }
54476                     }
54477                     if (capturesBlockScopeBindingInLoopBody) {
54478                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
54479                     }
54480                 }
54481                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
54482                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
54483                 if (ts.isForStatement(container)) {
54484                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54485                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
54486                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
54487                     }
54488                 }
54489                 // set 'declared inside loop' bit on the block-scoped binding
54490                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
54491             }
54492             if (usedInFunction) {
54493                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
54494             }
54495         }
54496         function isBindingCapturedByNode(node, decl) {
54497             var links = getNodeLinks(node);
54498             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
54499         }
54500         function isAssignedInBodyOfForStatement(node, container) {
54501             // skip parenthesized nodes
54502             var current = node;
54503             while (current.parent.kind === 200 /* ParenthesizedExpression */) {
54504                 current = current.parent;
54505             }
54506             // check if node is used as LHS in some assignment expression
54507             var isAssigned = false;
54508             if (ts.isAssignmentTarget(current)) {
54509                 isAssigned = true;
54510             }
54511             else if ((current.parent.kind === 207 /* PrefixUnaryExpression */ || current.parent.kind === 208 /* PostfixUnaryExpression */)) {
54512                 var expr = current.parent;
54513                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
54514             }
54515             if (!isAssigned) {
54516                 return false;
54517             }
54518             // at this point we know that node is the target of assignment
54519             // now check that modification happens inside the statement part of the ForStatement
54520             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
54521         }
54522         function captureLexicalThis(node, container) {
54523             getNodeLinks(node).flags |= 2 /* LexicalThis */;
54524             if (container.kind === 159 /* PropertyDeclaration */ || container.kind === 162 /* Constructor */) {
54525                 var classNode = container.parent;
54526                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
54527             }
54528             else {
54529                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
54530             }
54531         }
54532         function findFirstSuperCall(n) {
54533             if (ts.isSuperCall(n)) {
54534                 return n;
54535             }
54536             else if (ts.isFunctionLike(n)) {
54537                 return undefined;
54538             }
54539             return ts.forEachChild(n, findFirstSuperCall);
54540         }
54541         /**
54542          * Return a cached result if super-statement is already found.
54543          * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
54544          *
54545          * @param constructor constructor-function to look for super statement
54546          */
54547         function getSuperCallInConstructor(constructor) {
54548             var links = getNodeLinks(constructor);
54549             // Only trying to find super-call if we haven't yet tried to find one.  Once we try, we will record the result
54550             if (links.hasSuperCall === undefined) {
54551                 links.superCall = findFirstSuperCall(constructor.body);
54552                 links.hasSuperCall = links.superCall ? true : false;
54553             }
54554             return links.superCall;
54555         }
54556         /**
54557          * Check if the given class-declaration extends null then return true.
54558          * Otherwise, return false
54559          * @param classDecl a class declaration to check if it extends null
54560          */
54561         function classDeclarationExtendsNull(classDecl) {
54562             var classSymbol = getSymbolOfNode(classDecl);
54563             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
54564             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
54565             return baseConstructorType === nullWideningType;
54566         }
54567         function checkThisBeforeSuper(node, container, diagnosticMessage) {
54568             var containingClassDecl = container.parent;
54569             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
54570             // If a containing class does not have extends clause or the class extends null
54571             // skip checking whether super statement is called before "this" accessing.
54572             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
54573                 var superCall = getSuperCallInConstructor(container);
54574                 // We should give an error in the following cases:
54575                 //      - No super-call
54576                 //      - "this" is accessing before super-call.
54577                 //          i.e super(this)
54578                 //              this.x; super();
54579                 // We want to make sure that super-call is done before accessing "this" so that
54580                 // "this" is not accessed as a parameter of the super-call.
54581                 if (!superCall || superCall.end > node.pos) {
54582                     // In ES6, super inside constructor of class-declaration has to precede "this" accessing
54583                     error(node, diagnosticMessage);
54584                 }
54585             }
54586         }
54587         function checkThisExpression(node) {
54588             // Stop at the first arrow function so that we can
54589             // tell whether 'this' needs to be captured.
54590             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
54591             var capturedByArrowFunction = false;
54592             if (container.kind === 162 /* Constructor */) {
54593                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
54594             }
54595             // Now skip arrow functions to get the "real" owner of 'this'.
54596             if (container.kind === 202 /* ArrowFunction */) {
54597                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
54598                 capturedByArrowFunction = true;
54599             }
54600             switch (container.kind) {
54601                 case 249 /* ModuleDeclaration */:
54602                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
54603                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54604                     break;
54605                 case 248 /* EnumDeclaration */:
54606                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
54607                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54608                     break;
54609                 case 162 /* Constructor */:
54610                     if (isInConstructorArgumentInitializer(node, container)) {
54611                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
54612                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54613                     }
54614                     break;
54615                 case 159 /* PropertyDeclaration */:
54616                 case 158 /* PropertySignature */:
54617                     if (ts.hasModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
54618                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
54619                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54620                     }
54621                     break;
54622                 case 154 /* ComputedPropertyName */:
54623                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
54624                     break;
54625             }
54626             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
54627             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
54628                 captureLexicalThis(node, container);
54629             }
54630             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
54631             if (noImplicitThis) {
54632                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
54633                 if (type === globalThisType_1 && capturedByArrowFunction) {
54634                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
54635                 }
54636                 else if (!type) {
54637                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
54638                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
54639                     if (!ts.isSourceFile(container)) {
54640                         var outsideThis = tryGetThisTypeAt(container);
54641                         if (outsideThis && outsideThis !== globalThisType_1) {
54642                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
54643                         }
54644                     }
54645                 }
54646             }
54647             return type || anyType;
54648         }
54649         function tryGetThisTypeAt(node, includeGlobalThis, container) {
54650             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
54651             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
54652             var isInJS = ts.isInJSFile(node);
54653             if (ts.isFunctionLike(container) &&
54654                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
54655                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
54656                 // If this is a function in a JS file, it might be a class method.
54657                 var className = getClassNameFromPrototypeMethod(container);
54658                 if (isInJS && className) {
54659                     var classSymbol = checkExpression(className).symbol;
54660                     if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
54661                         var classType = getDeclaredTypeOfSymbol(classSymbol).thisType;
54662                         if (classType) {
54663                             return getFlowTypeOfReference(node, classType);
54664                         }
54665                     }
54666                 }
54667                 // Check if it's a constructor definition, can be either a variable decl or function decl
54668                 // i.e.
54669                 //   * /** @constructor */ function [name]() { ... }
54670                 //   * /** @constructor */ var x = function() { ... }
54671                 else if (isInJS &&
54672                     (container.kind === 201 /* FunctionExpression */ || container.kind === 244 /* FunctionDeclaration */) &&
54673                     ts.getJSDocClassTag(container)) {
54674                     var classType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
54675                     return getFlowTypeOfReference(node, classType);
54676                 }
54677                 var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
54678                 if (thisType) {
54679                     return getFlowTypeOfReference(node, thisType);
54680                 }
54681             }
54682             if (ts.isClassLike(container.parent)) {
54683                 var symbol = getSymbolOfNode(container.parent);
54684                 var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54685                 return getFlowTypeOfReference(node, type);
54686             }
54687             if (isInJS) {
54688                 var type = getTypeForThisExpressionFromJSDoc(container);
54689                 if (type && type !== errorType) {
54690                     return getFlowTypeOfReference(node, type);
54691                 }
54692             }
54693             if (ts.isSourceFile(container)) {
54694                 // look up in the source file's locals or exports
54695                 if (container.commonJsModuleIndicator) {
54696                     var fileSymbol = getSymbolOfNode(container);
54697                     return fileSymbol && getTypeOfSymbol(fileSymbol);
54698                 }
54699                 else if (includeGlobalThis) {
54700                     return getTypeOfSymbol(globalThisSymbol);
54701                 }
54702             }
54703         }
54704         function getExplicitThisType(node) {
54705             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54706             if (ts.isFunctionLike(container)) {
54707                 var signature = getSignatureFromDeclaration(container);
54708                 if (signature.thisParameter) {
54709                     return getExplicitTypeOfSymbol(signature.thisParameter);
54710                 }
54711             }
54712             if (ts.isClassLike(container.parent)) {
54713                 var symbol = getSymbolOfNode(container.parent);
54714                 return ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54715             }
54716         }
54717         function getClassNameFromPrototypeMethod(container) {
54718             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
54719             if (container.kind === 201 /* FunctionExpression */ &&
54720                 ts.isBinaryExpression(container.parent) &&
54721                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
54722                 // Get the 'x' of 'x.prototype.y = container'
54723                 return container.parent // x.prototype.y = container
54724                     .left // x.prototype.y
54725                     .expression // x.prototype
54726                     .expression; // x
54727             }
54728             // x.prototype = { method() { } }
54729             else if (container.kind === 161 /* MethodDeclaration */ &&
54730                 container.parent.kind === 193 /* ObjectLiteralExpression */ &&
54731                 ts.isBinaryExpression(container.parent.parent) &&
54732                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
54733                 return container.parent.parent.left.expression;
54734             }
54735             // x.prototype = { method: function() { } }
54736             else if (container.kind === 201 /* FunctionExpression */ &&
54737                 container.parent.kind === 281 /* PropertyAssignment */ &&
54738                 container.parent.parent.kind === 193 /* ObjectLiteralExpression */ &&
54739                 ts.isBinaryExpression(container.parent.parent.parent) &&
54740                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
54741                 return container.parent.parent.parent.left.expression;
54742             }
54743             // Object.defineProperty(x, "method", { value: function() { } });
54744             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
54745             // Object.defineProperty(x, "method", { get: () => function() { }) });
54746             else if (container.kind === 201 /* FunctionExpression */ &&
54747                 ts.isPropertyAssignment(container.parent) &&
54748                 ts.isIdentifier(container.parent.name) &&
54749                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
54750                 ts.isObjectLiteralExpression(container.parent.parent) &&
54751                 ts.isCallExpression(container.parent.parent.parent) &&
54752                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
54753                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54754                 return container.parent.parent.parent.arguments[0].expression;
54755             }
54756             // Object.defineProperty(x, "method", { value() { } });
54757             // Object.defineProperty(x, "method", { set(x: () => void) {} });
54758             // Object.defineProperty(x, "method", { get() { return () => {} } });
54759             else if (ts.isMethodDeclaration(container) &&
54760                 ts.isIdentifier(container.name) &&
54761                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
54762                 ts.isObjectLiteralExpression(container.parent) &&
54763                 ts.isCallExpression(container.parent.parent) &&
54764                 container.parent.parent.arguments[2] === container.parent &&
54765                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54766                 return container.parent.parent.arguments[0].expression;
54767             }
54768         }
54769         function getTypeForThisExpressionFromJSDoc(node) {
54770             var jsdocType = ts.getJSDocType(node);
54771             if (jsdocType && jsdocType.kind === 300 /* JSDocFunctionType */) {
54772                 var jsDocFunctionType = jsdocType;
54773                 if (jsDocFunctionType.parameters.length > 0 &&
54774                     jsDocFunctionType.parameters[0].name &&
54775                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
54776                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
54777                 }
54778             }
54779             var thisTag = ts.getJSDocThisTag(node);
54780             if (thisTag && thisTag.typeExpression) {
54781                 return getTypeFromTypeNode(thisTag.typeExpression);
54782             }
54783         }
54784         function isInConstructorArgumentInitializer(node, constructorDecl) {
54785             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 156 /* Parameter */ && n.parent === constructorDecl; });
54786         }
54787         function checkSuperExpression(node) {
54788             var isCallExpression = node.parent.kind === 196 /* CallExpression */ && node.parent.expression === node;
54789             var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
54790             var needToCaptureLexicalThis = false;
54791             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
54792             if (!isCallExpression) {
54793                 while (container && container.kind === 202 /* ArrowFunction */) {
54794                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
54795                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
54796                 }
54797             }
54798             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
54799             var nodeCheckFlag = 0;
54800             if (!canUseSuperExpression) {
54801                 // issue more specific error if super is used in computed property name
54802                 // class A { foo() { return "1" }}
54803                 // class B {
54804                 //     [super.foo()]() {}
54805                 // }
54806                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 154 /* ComputedPropertyName */; });
54807                 if (current && current.kind === 154 /* ComputedPropertyName */) {
54808                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
54809                 }
54810                 else if (isCallExpression) {
54811                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
54812                 }
54813                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */)) {
54814                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
54815                 }
54816                 else {
54817                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
54818                 }
54819                 return errorType;
54820             }
54821             if (!isCallExpression && container.kind === 162 /* Constructor */) {
54822                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
54823             }
54824             if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
54825                 nodeCheckFlag = 512 /* SuperStatic */;
54826             }
54827             else {
54828                 nodeCheckFlag = 256 /* SuperInstance */;
54829             }
54830             getNodeLinks(node).flags |= nodeCheckFlag;
54831             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
54832             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
54833             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
54834             // uses an arrow function, which is permitted to reference `super`.
54835             //
54836             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
54837             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
54838             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
54839             //
54840             // The simplest case is reading a value, in which case we will emit something like the following:
54841             //
54842             //  // ts
54843             //  ...
54844             //  async asyncMethod() {
54845             //    let x = await super.asyncMethod();
54846             //    return x;
54847             //  }
54848             //  ...
54849             //
54850             //  // js
54851             //  ...
54852             //  asyncMethod() {
54853             //      const _super = Object.create(null, {
54854             //        asyncMethod: { get: () => super.asyncMethod },
54855             //      });
54856             //      return __awaiter(this, arguments, Promise, function *() {
54857             //          let x = yield _super.asyncMethod.call(this);
54858             //          return x;
54859             //      });
54860             //  }
54861             //  ...
54862             //
54863             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
54864             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
54865             //
54866             //  // ts
54867             //  ...
54868             //  async asyncMethod(ar: Promise<any[]>) {
54869             //      [super.a, super.b] = await ar;
54870             //  }
54871             //  ...
54872             //
54873             //  // js
54874             //  ...
54875             //  asyncMethod(ar) {
54876             //      const _super = Object.create(null, {
54877             //        a: { get: () => super.a, set: (v) => super.a = v },
54878             //        b: { get: () => super.b, set: (v) => super.b = v }
54879             //      };
54880             //      return __awaiter(this, arguments, Promise, function *() {
54881             //          [_super.a, _super.b] = yield ar;
54882             //      });
54883             //  }
54884             //  ...
54885             //
54886             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
54887             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
54888             //
54889             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
54890             if (container.kind === 161 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
54891                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
54892                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
54893                 }
54894                 else {
54895                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
54896                 }
54897             }
54898             if (needToCaptureLexicalThis) {
54899                 // call expressions are allowed only in constructors so they should always capture correct 'this'
54900                 // super property access expressions can also appear in arrow functions -
54901                 // in this case they should also use correct lexical this
54902                 captureLexicalThis(node.parent, container);
54903             }
54904             if (container.parent.kind === 193 /* ObjectLiteralExpression */) {
54905                 if (languageVersion < 2 /* ES2015 */) {
54906                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
54907                     return errorType;
54908                 }
54909                 else {
54910                     // for object literal assume that type of 'super' is 'any'
54911                     return anyType;
54912                 }
54913             }
54914             // at this point the only legal case for parent is ClassLikeDeclaration
54915             var classLikeDeclaration = container.parent;
54916             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
54917                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
54918                 return errorType;
54919             }
54920             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
54921             var baseClassType = classType && getBaseTypes(classType)[0];
54922             if (!baseClassType) {
54923                 return errorType;
54924             }
54925             if (container.kind === 162 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
54926                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
54927                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
54928                 return errorType;
54929             }
54930             return nodeCheckFlag === 512 /* SuperStatic */
54931                 ? getBaseConstructorTypeOfClass(classType)
54932                 : getTypeWithThisArgument(baseClassType, classType.thisType);
54933             function isLegalUsageOfSuperExpression(container) {
54934                 if (!container) {
54935                     return false;
54936                 }
54937                 if (isCallExpression) {
54938                     // TS 1.0 SPEC (April 2014): 4.8.1
54939                     // Super calls are only permitted in constructors of derived classes
54940                     return container.kind === 162 /* Constructor */;
54941                 }
54942                 else {
54943                     // TS 1.0 SPEC (April 2014)
54944                     // 'super' property access is allowed
54945                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
54946                     // - In a static member function or static member accessor
54947                     // topmost container must be something that is directly nested in the class declaration\object literal expression
54948                     if (ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */) {
54949                         if (ts.hasModifier(container, 32 /* Static */)) {
54950                             return container.kind === 161 /* MethodDeclaration */ ||
54951                                 container.kind === 160 /* MethodSignature */ ||
54952                                 container.kind === 163 /* GetAccessor */ ||
54953                                 container.kind === 164 /* SetAccessor */;
54954                         }
54955                         else {
54956                             return container.kind === 161 /* MethodDeclaration */ ||
54957                                 container.kind === 160 /* MethodSignature */ ||
54958                                 container.kind === 163 /* GetAccessor */ ||
54959                                 container.kind === 164 /* SetAccessor */ ||
54960                                 container.kind === 159 /* PropertyDeclaration */ ||
54961                                 container.kind === 158 /* PropertySignature */ ||
54962                                 container.kind === 162 /* Constructor */;
54963                         }
54964                     }
54965                 }
54966                 return false;
54967             }
54968         }
54969         function getContainingObjectLiteral(func) {
54970             return (func.kind === 161 /* MethodDeclaration */ ||
54971                 func.kind === 163 /* GetAccessor */ ||
54972                 func.kind === 164 /* SetAccessor */) && func.parent.kind === 193 /* ObjectLiteralExpression */ ? func.parent :
54973                 func.kind === 201 /* FunctionExpression */ && func.parent.kind === 281 /* PropertyAssignment */ ? func.parent.parent :
54974                     undefined;
54975         }
54976         function getThisTypeArgument(type) {
54977             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
54978         }
54979         function getThisTypeFromContextualType(type) {
54980             return mapType(type, function (t) {
54981                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
54982             });
54983         }
54984         function getContextualThisParameterType(func) {
54985             if (func.kind === 202 /* ArrowFunction */) {
54986                 return undefined;
54987             }
54988             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
54989                 var contextualSignature = getContextualSignature(func);
54990                 if (contextualSignature) {
54991                     var thisParameter = contextualSignature.thisParameter;
54992                     if (thisParameter) {
54993                         return getTypeOfSymbol(thisParameter);
54994                     }
54995                 }
54996             }
54997             var inJs = ts.isInJSFile(func);
54998             if (noImplicitThis || inJs) {
54999                 var containingLiteral = getContainingObjectLiteral(func);
55000                 if (containingLiteral) {
55001                     // We have an object literal method. Check if the containing object literal has a contextual type
55002                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
55003                     // any directly enclosing object literals.
55004                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
55005                     var literal = containingLiteral;
55006                     var type = contextualType;
55007                     while (type) {
55008                         var thisType = getThisTypeFromContextualType(type);
55009                         if (thisType) {
55010                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
55011                         }
55012                         if (literal.parent.kind !== 281 /* PropertyAssignment */) {
55013                             break;
55014                         }
55015                         literal = literal.parent.parent;
55016                         type = getApparentTypeOfContextualType(literal);
55017                     }
55018                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
55019                     // for 'this' is the non-null form of the contextual type for the containing object literal or
55020                     // the type of the object literal itself.
55021                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
55022                 }
55023                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
55024                 // contextual type for 'this' is 'obj'.
55025                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
55026                 if (parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
55027                     var target = parent.left;
55028                     if (ts.isAccessExpression(target)) {
55029                         var expression = target.expression;
55030                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
55031                         if (inJs && ts.isIdentifier(expression)) {
55032                             var sourceFile = ts.getSourceFileOfNode(parent);
55033                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
55034                                 return undefined;
55035                             }
55036                         }
55037                         return getWidenedType(checkExpressionCached(expression));
55038                     }
55039                 }
55040             }
55041             return undefined;
55042         }
55043         // Return contextual type of parameter or undefined if no contextual type is available
55044         function getContextuallyTypedParameterType(parameter) {
55045             var func = parameter.parent;
55046             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
55047                 return undefined;
55048             }
55049             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
55050             if (iife && iife.arguments) {
55051                 var args = getEffectiveCallArguments(iife);
55052                 var indexOfParameter = func.parameters.indexOf(parameter);
55053                 if (parameter.dotDotDotToken) {
55054                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
55055                 }
55056                 var links = getNodeLinks(iife);
55057                 var cached = links.resolvedSignature;
55058                 links.resolvedSignature = anySignature;
55059                 var type = indexOfParameter < args.length ?
55060                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
55061                     parameter.initializer ? undefined : undefinedWideningType;
55062                 links.resolvedSignature = cached;
55063                 return type;
55064             }
55065             var contextualSignature = getContextualSignature(func);
55066             if (contextualSignature) {
55067                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
55068                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
55069                     getRestTypeAtPosition(contextualSignature, index) :
55070                     tryGetTypeAtPosition(contextualSignature, index);
55071             }
55072         }
55073         function getContextualTypeForVariableLikeDeclaration(declaration) {
55074             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
55075             if (typeNode) {
55076                 return getTypeFromTypeNode(typeNode);
55077             }
55078             switch (declaration.kind) {
55079                 case 156 /* Parameter */:
55080                     return getContextuallyTypedParameterType(declaration);
55081                 case 191 /* BindingElement */:
55082                     return getContextualTypeForBindingElement(declaration);
55083                 // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
55084             }
55085         }
55086         function getContextualTypeForBindingElement(declaration) {
55087             var parent = declaration.parent.parent;
55088             var name = declaration.propertyName || declaration.name;
55089             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
55090                 parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
55091             if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) {
55092                 var nameType = getLiteralTypeFromPropertyName(name);
55093                 if (isTypeUsableAsPropertyName(nameType)) {
55094                     var text = getPropertyNameFromType(nameType);
55095                     return getTypeOfPropertyOfType(parentType, text);
55096                 }
55097             }
55098         }
55099         // In a variable, parameter or property declaration with a type annotation,
55100         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
55101         // Otherwise, in a parameter declaration of a contextually typed function expression,
55102         //   the contextual type of an initializer expression is the contextual type of the parameter.
55103         // Otherwise, in a variable or parameter declaration with a binding pattern name,
55104         //   the contextual type of an initializer expression is the type implied by the binding pattern.
55105         // Otherwise, in a binding pattern inside a variable or parameter declaration,
55106         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
55107         function getContextualTypeForInitializerExpression(node) {
55108             var declaration = node.parent;
55109             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
55110                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
55111                 if (result) {
55112                     return result;
55113                 }
55114                 if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
55115                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
55116                 }
55117             }
55118             return undefined;
55119         }
55120         function getContextualTypeForReturnExpression(node) {
55121             var func = ts.getContainingFunction(node);
55122             if (func) {
55123                 var functionFlags = ts.getFunctionFlags(func);
55124                 if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
55125                     return undefined;
55126                 }
55127                 var contextualReturnType = getContextualReturnType(func);
55128                 if (contextualReturnType) {
55129                     if (functionFlags & 2 /* Async */) { // Async function
55130                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise);
55131                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55132                     }
55133                     return contextualReturnType; // Regular function
55134                 }
55135             }
55136             return undefined;
55137         }
55138         function getContextualTypeForAwaitOperand(node) {
55139             var contextualType = getContextualType(node);
55140             if (contextualType) {
55141                 var contextualAwaitedType = getAwaitedType(contextualType);
55142                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55143             }
55144             return undefined;
55145         }
55146         function getContextualTypeForYieldOperand(node) {
55147             var func = ts.getContainingFunction(node);
55148             if (func) {
55149                 var functionFlags = ts.getFunctionFlags(func);
55150                 var contextualReturnType = getContextualReturnType(func);
55151                 if (contextualReturnType) {
55152                     return node.asteriskToken
55153                         ? contextualReturnType
55154                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
55155                 }
55156             }
55157             return undefined;
55158         }
55159         function isInParameterInitializerBeforeContainingFunction(node) {
55160             var inBindingInitializer = false;
55161             while (node.parent && !ts.isFunctionLike(node.parent)) {
55162                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
55163                     return true;
55164                 }
55165                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
55166                     inBindingInitializer = true;
55167                 }
55168                 node = node.parent;
55169             }
55170             return false;
55171         }
55172         function getContextualIterationType(kind, functionDecl) {
55173             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
55174             var contextualReturnType = getContextualReturnType(functionDecl);
55175             if (contextualReturnType) {
55176                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
55177                     || undefined;
55178             }
55179             return undefined;
55180         }
55181         function getContextualReturnType(functionDecl) {
55182             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
55183             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
55184             var returnType = getReturnTypeFromAnnotation(functionDecl);
55185             if (returnType) {
55186                 return returnType;
55187             }
55188             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
55189             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
55190             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
55191             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
55192                 return getReturnTypeOfSignature(signature);
55193             }
55194             return undefined;
55195         }
55196         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
55197         function getContextualTypeForArgument(callTarget, arg) {
55198             var args = getEffectiveCallArguments(callTarget);
55199             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
55200             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
55201         }
55202         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
55203             // If we're already in the process of resolving the given signature, don't resolve again as
55204             // that could cause infinite recursion. Instead, return anySignature.
55205             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
55206             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
55207                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
55208             }
55209             return getTypeAtPosition(signature, argIndex);
55210         }
55211         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
55212             if (template.parent.kind === 198 /* TaggedTemplateExpression */) {
55213                 return getContextualTypeForArgument(template.parent, substitutionExpression);
55214             }
55215             return undefined;
55216         }
55217         function getContextualTypeForBinaryOperand(node, contextFlags) {
55218             var binaryExpression = node.parent;
55219             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
55220             switch (operatorToken.kind) {
55221                 case 62 /* EqualsToken */:
55222                     if (node !== right) {
55223                         return undefined;
55224                     }
55225                     var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
55226                     if (!contextSensitive) {
55227                         return undefined;
55228                     }
55229                     return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
55230                 case 56 /* BarBarToken */:
55231                 case 60 /* QuestionQuestionToken */:
55232                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
55233                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
55234                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
55235                     // by the type of the left operand, except for the special case of Javascript declarations of the form
55236                     // `namespace.prop = namespace.prop || {}`.
55237                     var type = getContextualType(binaryExpression, contextFlags);
55238                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
55239                         getTypeOfExpression(left) : type;
55240                 case 55 /* AmpersandAmpersandToken */:
55241                 case 27 /* CommaToken */:
55242                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
55243                 default:
55244                     return undefined;
55245             }
55246         }
55247         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
55248         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
55249         function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
55250             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
55251             switch (kind) {
55252                 case 0 /* None */:
55253                     return true;
55254                 case 5 /* Property */:
55255                 case 1 /* ExportsProperty */:
55256                 case 6 /* Prototype */:
55257                 case 3 /* PrototypeProperty */:
55258                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
55259                     // See `bindStaticPropertyAssignment` in `binder.ts`.
55260                     if (!binaryExpression.left.symbol) {
55261                         return true;
55262                     }
55263                     else {
55264                         var decl = binaryExpression.left.symbol.valueDeclaration;
55265                         if (!decl) {
55266                             return false;
55267                         }
55268                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
55269                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
55270                         if (overallAnnotation) {
55271                             return getTypeFromTypeNode(overallAnnotation);
55272                         }
55273                         else if (ts.isIdentifier(lhs.expression)) {
55274                             var id = lhs.expression;
55275                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
55276                             if (parentSymbol) {
55277                                 var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
55278                                 if (annotated) {
55279                                     var nameStr_1 = ts.getElementOrPropertyAccessName(lhs);
55280                                     if (nameStr_1 !== undefined) {
55281                                         var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr_1);
55282                                         return type || false;
55283                                     }
55284                                 }
55285                                 return false;
55286                             }
55287                         }
55288                         return !ts.isInJSFile(decl);
55289                     }
55290                 case 2 /* ModuleExports */:
55291                 case 4 /* ThisProperty */:
55292                     if (!binaryExpression.symbol)
55293                         return true;
55294                     if (binaryExpression.symbol.valueDeclaration) {
55295                         var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
55296                         if (annotated) {
55297                             var type = getTypeFromTypeNode(annotated);
55298                             if (type) {
55299                                 return type;
55300                             }
55301                         }
55302                     }
55303                     if (kind === 2 /* ModuleExports */)
55304                         return false;
55305                     var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
55306                     if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
55307                         return false;
55308                     }
55309                     var thisType = checkThisExpression(thisAccess.expression);
55310                     var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
55311                     return nameStr !== undefined && thisType && getTypeOfPropertyOfContextualType(thisType, nameStr) || false;
55312                 case 7 /* ObjectDefinePropertyValue */:
55313                 case 8 /* ObjectDefinePropertyExports */:
55314                 case 9 /* ObjectDefinePrototypeProperty */:
55315                     return ts.Debug.fail("Does not apply");
55316                 default:
55317                     return ts.Debug.assertNever(kind);
55318             }
55319         }
55320         function isCircularMappedProperty(symbol) {
55321             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
55322         }
55323         function getTypeOfPropertyOfContextualType(type, name) {
55324             return mapType(type, function (t) {
55325                 if (isGenericMappedType(t)) {
55326                     var constraint = getConstraintTypeFromMappedType(t);
55327                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
55328                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
55329                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
55330                         return substituteIndexedMappedType(t, propertyNameType);
55331                     }
55332                 }
55333                 else if (t.flags & 3670016 /* StructuredType */) {
55334                     var prop = getPropertyOfType(t, name);
55335                     if (prop) {
55336                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
55337                     }
55338                     if (isTupleType(t)) {
55339                         var restType = getRestTypeOfTupleType(t);
55340                         if (restType && isNumericLiteralName(name) && +name >= 0) {
55341                             return restType;
55342                         }
55343                     }
55344                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
55345                         getIndexTypeOfContextualType(t, 0 /* String */);
55346                 }
55347                 return undefined;
55348             }, /*noReductions*/ true);
55349         }
55350         function getIndexTypeOfContextualType(type, kind) {
55351             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
55352         }
55353         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
55354         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
55355         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
55356         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
55357             ts.Debug.assert(ts.isObjectLiteralMethod(node));
55358             if (node.flags & 16777216 /* InWithStatement */) {
55359                 // We cannot answer semantic questions within a with block, do not proceed any further
55360                 return undefined;
55361             }
55362             return getContextualTypeForObjectLiteralElement(node, contextFlags);
55363         }
55364         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
55365             var objectLiteral = element.parent;
55366             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
55367             if (type) {
55368                 if (!hasNonBindableDynamicName(element)) {
55369                     // For a (non-symbol) computed property, there is no reason to look up the name
55370                     // in the type. It will just be "__computed", which does not appear in any
55371                     // SymbolTable.
55372                     var symbolName_3 = getSymbolOfNode(element).escapedName;
55373                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
55374                     if (propertyType) {
55375                         return propertyType;
55376                     }
55377                 }
55378                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
55379                     getIndexTypeOfContextualType(type, 0 /* String */);
55380             }
55381             return undefined;
55382         }
55383         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
55384         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
55385         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
55386         // type of T.
55387         function getContextualTypeForElementExpression(arrayContextualType, index) {
55388             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
55389                 || getIteratedTypeOrElementType(1 /* Element */, arrayContextualType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false));
55390         }
55391         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
55392         function getContextualTypeForConditionalOperand(node, contextFlags) {
55393             var conditional = node.parent;
55394             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
55395         }
55396         function getContextualTypeForChildJsxExpression(node, child) {
55397             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
55398             // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
55399             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
55400             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
55401                 return undefined;
55402             }
55403             var realChildren = getSemanticJsxChildren(node.children);
55404             var childIndex = realChildren.indexOf(child);
55405             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
55406             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
55407                 if (isArrayLikeType(t)) {
55408                     return getIndexedAccessType(t, getLiteralType(childIndex));
55409                 }
55410                 else {
55411                     return t;
55412                 }
55413             }, /*noReductions*/ true));
55414         }
55415         function getContextualTypeForJsxExpression(node) {
55416             var exprParent = node.parent;
55417             return ts.isJsxAttributeLike(exprParent)
55418                 ? getContextualType(node)
55419                 : ts.isJsxElement(exprParent)
55420                     ? getContextualTypeForChildJsxExpression(exprParent, node)
55421                     : undefined;
55422         }
55423         function getContextualTypeForJsxAttribute(attribute) {
55424             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
55425             // which is a type of the parameter of the signature we are trying out.
55426             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
55427             if (ts.isJsxAttribute(attribute)) {
55428                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
55429                 if (!attributesType || isTypeAny(attributesType)) {
55430                     return undefined;
55431                 }
55432                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
55433             }
55434             else {
55435                 return getContextualType(attribute.parent);
55436             }
55437         }
55438         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
55439         // expressions we check to those that don't depend on their contextual type in order not to cause
55440         // recursive (and possibly infinite) invocations of getContextualType.
55441         function isPossiblyDiscriminantValue(node) {
55442             switch (node.kind) {
55443                 case 10 /* StringLiteral */:
55444                 case 8 /* NumericLiteral */:
55445                 case 9 /* BigIntLiteral */:
55446                 case 14 /* NoSubstitutionTemplateLiteral */:
55447                 case 106 /* TrueKeyword */:
55448                 case 91 /* FalseKeyword */:
55449                 case 100 /* NullKeyword */:
55450                 case 75 /* Identifier */:
55451                 case 146 /* UndefinedKeyword */:
55452                     return true;
55453                 case 194 /* PropertyAccessExpression */:
55454                 case 200 /* ParenthesizedExpression */:
55455                     return isPossiblyDiscriminantValue(node.expression);
55456                 case 276 /* JsxExpression */:
55457                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
55458             }
55459             return false;
55460         }
55461         function discriminateContextualTypeByObjectMembers(node, contextualType) {
55462             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
55463         }
55464         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
55465             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
55466         }
55467         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
55468         // be "pushed" onto a node using the contextualType property.
55469         function getApparentTypeOfContextualType(node, contextFlags) {
55470             var contextualType = ts.isObjectLiteralMethod(node) ?
55471                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
55472                 getContextualType(node, contextFlags);
55473             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
55474             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
55475                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
55476                 if (apparentType.flags & 1048576 /* Union */) {
55477                     if (ts.isObjectLiteralExpression(node)) {
55478                         return discriminateContextualTypeByObjectMembers(node, apparentType);
55479                     }
55480                     else if (ts.isJsxAttributes(node)) {
55481                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
55482                     }
55483                 }
55484                 return apparentType;
55485             }
55486         }
55487         // If the given contextual type contains instantiable types and if a mapper representing
55488         // return type inferences is available, instantiate those types using that mapper.
55489         function instantiateContextualType(contextualType, node, contextFlags) {
55490             if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
55491                 var inferenceContext = getInferenceContext(node);
55492                 // If no inferences have been made, nothing is gained from instantiating as type parameters
55493                 // would just be replaced with their defaults similar to the apparent type.
55494                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
55495                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
55496                     // types as well as arguments to the left in a function call.
55497                     if (contextFlags && contextFlags & 1 /* Signature */) {
55498                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
55499                     }
55500                     // For other purposes (e.g. determining whether to produce literal types) we only
55501                     // incorporate inferences made from the return type in a function call.
55502                     if (inferenceContext.returnMapper) {
55503                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
55504                     }
55505                 }
55506             }
55507             return contextualType;
55508         }
55509         // This function is similar to instantiateType, except that (a) it only instantiates types that
55510         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
55511         // no reductions on instantiated union types.
55512         function instantiateInstantiableTypes(type, mapper) {
55513             if (type.flags & 63176704 /* Instantiable */) {
55514                 return instantiateType(type, mapper);
55515             }
55516             if (type.flags & 1048576 /* Union */) {
55517                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
55518             }
55519             if (type.flags & 2097152 /* Intersection */) {
55520                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
55521             }
55522             return type;
55523         }
55524         /**
55525          * Whoa! Do you really want to use this function?
55526          *
55527          * Unless you're trying to get the *non-apparent* type for a
55528          * value-literal type or you're authoring relevant portions of this algorithm,
55529          * you probably meant to use 'getApparentTypeOfContextualType'.
55530          * Otherwise this may not be very useful.
55531          *
55532          * In cases where you *are* working on this function, you should understand
55533          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
55534          *
55535          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
55536          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
55537          *
55538          * @param node the expression whose contextual type will be returned.
55539          * @returns the contextual type of an expression.
55540          */
55541         function getContextualType(node, contextFlags) {
55542             if (node.flags & 16777216 /* InWithStatement */) {
55543                 // We cannot answer semantic questions within a with block, do not proceed any further
55544                 return undefined;
55545             }
55546             if (node.contextualType) {
55547                 return node.contextualType;
55548             }
55549             var parent = node.parent;
55550             switch (parent.kind) {
55551                 case 242 /* VariableDeclaration */:
55552                 case 156 /* Parameter */:
55553                 case 159 /* PropertyDeclaration */:
55554                 case 158 /* PropertySignature */:
55555                 case 191 /* BindingElement */:
55556                     return getContextualTypeForInitializerExpression(node);
55557                 case 202 /* ArrowFunction */:
55558                 case 235 /* ReturnStatement */:
55559                     return getContextualTypeForReturnExpression(node);
55560                 case 212 /* YieldExpression */:
55561                     return getContextualTypeForYieldOperand(parent);
55562                 case 206 /* AwaitExpression */:
55563                     return getContextualTypeForAwaitOperand(parent);
55564                 case 196 /* CallExpression */:
55565                     if (parent.expression.kind === 96 /* ImportKeyword */) {
55566                         return stringType;
55567                     }
55568                 /* falls through */
55569                 case 197 /* NewExpression */:
55570                     return getContextualTypeForArgument(parent, node);
55571                 case 199 /* TypeAssertionExpression */:
55572                 case 217 /* AsExpression */:
55573                     return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
55574                 case 209 /* BinaryExpression */:
55575                     return getContextualTypeForBinaryOperand(node, contextFlags);
55576                 case 281 /* PropertyAssignment */:
55577                 case 282 /* ShorthandPropertyAssignment */:
55578                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
55579                 case 283 /* SpreadAssignment */:
55580                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
55581                 case 192 /* ArrayLiteralExpression */: {
55582                     var arrayLiteral = parent;
55583                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
55584                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
55585                 }
55586                 case 210 /* ConditionalExpression */:
55587                     return getContextualTypeForConditionalOperand(node, contextFlags);
55588                 case 221 /* TemplateSpan */:
55589                     ts.Debug.assert(parent.parent.kind === 211 /* TemplateExpression */);
55590                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
55591                 case 200 /* ParenthesizedExpression */: {
55592                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
55593                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
55594                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
55595                 }
55596                 case 276 /* JsxExpression */:
55597                     return getContextualTypeForJsxExpression(parent);
55598                 case 273 /* JsxAttribute */:
55599                 case 275 /* JsxSpreadAttribute */:
55600                     return getContextualTypeForJsxAttribute(parent);
55601                 case 268 /* JsxOpeningElement */:
55602                 case 267 /* JsxSelfClosingElement */:
55603                     return getContextualJsxElementAttributesType(parent, contextFlags);
55604             }
55605             return undefined;
55606         }
55607         function getInferenceContext(node) {
55608             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
55609             return ancestor && ancestor.inferenceContext;
55610         }
55611         function getContextualJsxElementAttributesType(node, contextFlags) {
55612             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
55613                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
55614                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
55615                 // (as below) instead!
55616                 return node.parent.contextualType;
55617             }
55618             return getContextualTypeForArgumentAtIndex(node, 0);
55619         }
55620         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
55621             return getJsxReferenceKind(node) !== 0 /* Component */
55622                 ? getJsxPropsTypeFromCallSignature(signature, node)
55623                 : getJsxPropsTypeFromClassType(signature, node);
55624         }
55625         function getJsxPropsTypeFromCallSignature(sig, context) {
55626             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
55627             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
55628             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55629             if (intrinsicAttribs !== errorType) {
55630                 propsType = intersectTypes(intrinsicAttribs, propsType);
55631             }
55632             return propsType;
55633         }
55634         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
55635             if (sig.unionSignatures) {
55636                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
55637                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
55638                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
55639                 // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input.
55640                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
55641                 var results = [];
55642                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
55643                     var signature = _a[_i];
55644                     var instance = getReturnTypeOfSignature(signature);
55645                     if (isTypeAny(instance)) {
55646                         return instance;
55647                     }
55648                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
55649                     if (!propType) {
55650                         return;
55651                     }
55652                     results.push(propType);
55653                 }
55654                 return getIntersectionType(results);
55655             }
55656             var instanceType = getReturnTypeOfSignature(sig);
55657             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
55658         }
55659         function getStaticTypeOfReferencedJsxConstructor(context) {
55660             if (isJsxIntrinsicIdentifier(context.tagName)) {
55661                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
55662                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55663                 return getOrCreateTypeFromSignature(fakeSignature);
55664             }
55665             var tagType = checkExpressionCached(context.tagName);
55666             if (tagType.flags & 128 /* StringLiteral */) {
55667                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
55668                 if (!result) {
55669                     return errorType;
55670                 }
55671                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55672                 return getOrCreateTypeFromSignature(fakeSignature);
55673             }
55674             return tagType;
55675         }
55676         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
55677             var managedSym = getJsxLibraryManagedAttributes(ns);
55678             if (managedSym) {
55679                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
55680                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
55681                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
55682                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
55683                     return createTypeReference(declaredManagedType, args);
55684                 }
55685                 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
55686                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
55687                     return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
55688                 }
55689             }
55690             return attributesType;
55691         }
55692         function getJsxPropsTypeFromClassType(sig, context) {
55693             var ns = getJsxNamespaceAt(context);
55694             var forcedLookupLocation = getJsxElementPropertiesName(ns);
55695             var attributesType = forcedLookupLocation === undefined
55696                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
55697                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
55698                 : forcedLookupLocation === ""
55699                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
55700                     ? getReturnTypeOfSignature(sig)
55701                     // Otherwise get the type of the property on the signature return type
55702                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
55703             if (!attributesType) {
55704                 // There is no property named 'props' on this instance type
55705                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
55706                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
55707                 }
55708                 return unknownType;
55709             }
55710             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
55711             if (isTypeAny(attributesType)) {
55712                 // Props is of type 'any' or unknown
55713                 return attributesType;
55714             }
55715             else {
55716                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
55717                 var apparentAttributesType = attributesType;
55718                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
55719                 if (intrinsicClassAttribs !== errorType) {
55720                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
55721                     var hostClassType = getReturnTypeOfSignature(sig);
55722                     apparentAttributesType = intersectTypes(typeParams
55723                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
55724                         : intrinsicClassAttribs, apparentAttributesType);
55725                 }
55726                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55727                 if (intrinsicAttribs !== errorType) {
55728                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
55729                 }
55730                 return apparentAttributesType;
55731             }
55732         }
55733         // If the given type is an object or union type with a single signature, and if that signature has at
55734         // least as many parameters as the given function, return the signature. Otherwise return undefined.
55735         function getContextualCallSignature(type, node) {
55736             var signatures = getSignaturesOfType(type, 0 /* Call */);
55737             if (signatures.length === 1) {
55738                 var signature = signatures[0];
55739                 if (!isAritySmaller(signature, node)) {
55740                     return signature;
55741                 }
55742             }
55743         }
55744         /** If the contextual signature has fewer parameters than the function expression, do not use it */
55745         function isAritySmaller(signature, target) {
55746             var targetParameterCount = 0;
55747             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
55748                 var param = target.parameters[targetParameterCount];
55749                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
55750                     break;
55751                 }
55752             }
55753             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
55754                 targetParameterCount--;
55755             }
55756             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
55757         }
55758         function isFunctionExpressionOrArrowFunction(node) {
55759             return node.kind === 201 /* FunctionExpression */ || node.kind === 202 /* ArrowFunction */;
55760         }
55761         function getContextualSignatureForFunctionLikeDeclaration(node) {
55762             // Only function expressions, arrow functions, and object literal methods are contextually typed.
55763             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
55764                 ? getContextualSignature(node)
55765                 : undefined;
55766         }
55767         // Return the contextual signature for a given expression node. A contextual type provides a
55768         // contextual signature if it has a single call signature and if that call signature is non-generic.
55769         // If the contextual type is a union type, get the signature from each type possible and if they are
55770         // all identical ignoring their return type, the result is same signature but with return type as
55771         // union type of return types from these signatures
55772         function getContextualSignature(node) {
55773             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
55774             var typeTagSignature = getSignatureOfTypeTag(node);
55775             if (typeTagSignature) {
55776                 return typeTagSignature;
55777             }
55778             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
55779             if (!type) {
55780                 return undefined;
55781             }
55782             if (!(type.flags & 1048576 /* Union */)) {
55783                 return getContextualCallSignature(type, node);
55784             }
55785             var signatureList;
55786             var types = type.types;
55787             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
55788                 var current = types_17[_i];
55789                 var signature = getContextualCallSignature(current, node);
55790                 if (signature) {
55791                     if (!signatureList) {
55792                         // This signature will contribute to contextual union signature
55793                         signatureList = [signature];
55794                     }
55795                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
55796                         // Signatures aren't identical, do not use
55797                         return undefined;
55798                     }
55799                     else {
55800                         // Use this signature for contextual union signature
55801                         signatureList.push(signature);
55802                     }
55803                 }
55804             }
55805             // Result is union of signatures collected (return type is union of return types of this signature set)
55806             if (signatureList) {
55807                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
55808             }
55809         }
55810         function checkSpreadExpression(node, checkMode) {
55811             if (languageVersion < 2 /* ES2015 */) {
55812                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
55813             }
55814             var arrayOrIterableType = checkExpression(node.expression, checkMode);
55815             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
55816         }
55817         function hasDefaultValue(node) {
55818             return (node.kind === 191 /* BindingElement */ && !!node.initializer) ||
55819                 (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
55820         }
55821         function checkArrayLiteral(node, checkMode, forceTuple) {
55822             var elements = node.elements;
55823             var elementCount = elements.length;
55824             var elementTypes = [];
55825             var hasEndingSpreadElement = false;
55826             var hasNonEndingSpreadElement = false;
55827             var contextualType = getApparentTypeOfContextualType(node);
55828             var inDestructuringPattern = ts.isAssignmentTarget(node);
55829             var inConstContext = isConstContext(node);
55830             for (var i = 0; i < elementCount; i++) {
55831                 var e = elements[i];
55832                 var spread = e.kind === 213 /* SpreadElement */ && e.expression;
55833                 var spreadType = spread && checkExpression(spread, checkMode, forceTuple);
55834                 if (spreadType && isTupleType(spreadType)) {
55835                     elementTypes.push.apply(elementTypes, getTypeArguments(spreadType));
55836                     if (spreadType.target.hasRestElement) {
55837                         if (i === elementCount - 1)
55838                             hasEndingSpreadElement = true;
55839                         else
55840                             hasNonEndingSpreadElement = true;
55841                     }
55842                 }
55843                 else {
55844                     if (inDestructuringPattern && spreadType) {
55845                         // Given the following situation:
55846                         //    var c: {};
55847                         //    [...c] = ["", 0];
55848                         //
55849                         // c is represented in the tree as a spread element in an array literal.
55850                         // But c really functions as a rest element, and its purpose is to provide
55851                         // a contextual type for the right hand side of the assignment. Therefore,
55852                         // instead of calling checkExpression on "...c", which will give an error
55853                         // if c is not iterable/array-like, we need to act as if we are trying to
55854                         // get the contextual element type from it. So we do something similar to
55855                         // getContextualTypeForElementExpression, which will crucially not error
55856                         // if there is no index type / iterated type.
55857                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
55858                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false);
55859                         if (restElementType) {
55860                             elementTypes.push(restElementType);
55861                         }
55862                     }
55863                     else {
55864                         var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
55865                         var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
55866                         elementTypes.push(type);
55867                     }
55868                     if (spread) { // tuples are done above, so these are only arrays
55869                         if (i === elementCount - 1)
55870                             hasEndingSpreadElement = true;
55871                         else
55872                             hasNonEndingSpreadElement = true;
55873                     }
55874                 }
55875             }
55876             if (!hasNonEndingSpreadElement) {
55877                 var minLength = elementTypes.length - (hasEndingSpreadElement ? 1 : 0);
55878                 // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
55879                 // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
55880                 var tupleResult = void 0;
55881                 if (inDestructuringPattern && minLength > 0) {
55882                     var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55883                     type.pattern = node;
55884                     return type;
55885                 }
55886                 else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasEndingSpreadElement, elementTypes.length, inConstContext)) {
55887                     return createArrayLiteralType(tupleResult);
55888                 }
55889                 else if (forceTuple) {
55890                     return createArrayLiteralType(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55891                 }
55892             }
55893             return createArrayLiteralType(createArrayType(elementTypes.length ?
55894                 getUnionType(elementTypes, 2 /* Subtype */) :
55895                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
55896         }
55897         function createArrayLiteralType(type) {
55898             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
55899                 return type;
55900             }
55901             var literalType = type.literalType;
55902             if (!literalType) {
55903                 literalType = type.literalType = cloneTypeReference(type);
55904                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
55905             }
55906             return literalType;
55907         }
55908         function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
55909             if (elementCount === void 0) { elementCount = elementTypes.length; }
55910             if (readonly === void 0) { readonly = false; }
55911             // Infer a tuple type when the contextual type is or contains a tuple-like type
55912             if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
55913                 return createTupleType(elementTypes, elementCount - (hasRestElement ? 1 : 0), hasRestElement, readonly);
55914             }
55915         }
55916         function isNumericName(name) {
55917             switch (name.kind) {
55918                 case 154 /* ComputedPropertyName */:
55919                     return isNumericComputedName(name);
55920                 case 75 /* Identifier */:
55921                     return isNumericLiteralName(name.escapedText);
55922                 case 8 /* NumericLiteral */:
55923                 case 10 /* StringLiteral */:
55924                     return isNumericLiteralName(name.text);
55925                 default:
55926                     return false;
55927             }
55928         }
55929         function isNumericComputedName(name) {
55930             // It seems odd to consider an expression of type Any to result in a numeric name,
55931             // but this behavior is consistent with checkIndexedAccess
55932             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
55933         }
55934         function isInfinityOrNaNString(name) {
55935             return name === "Infinity" || name === "-Infinity" || name === "NaN";
55936         }
55937         function isNumericLiteralName(name) {
55938             // The intent of numeric names is that
55939             //     - they are names with text in a numeric form, and that
55940             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
55941             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
55942             //
55943             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
55944             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
55945             //
55946             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
55947             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
55948             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
55949             // because their 'ToString' representation is not equal to their original text.
55950             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
55951             //
55952             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
55953             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
55954             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
55955             //
55956             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
55957             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
55958             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
55959             return (+name).toString() === name;
55960         }
55961         function checkComputedPropertyName(node) {
55962             var links = getNodeLinks(node.expression);
55963             if (!links.resolvedType) {
55964                 links.resolvedType = checkExpression(node.expression);
55965                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
55966                 // type, and any union of these types (like string | number).
55967                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
55968                     !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
55969                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
55970                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
55971                 }
55972                 else {
55973                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
55974                 }
55975             }
55976             return links.resolvedType;
55977         }
55978         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
55979             var propTypes = [];
55980             for (var i = 0; i < properties.length; i++) {
55981                 if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
55982                     propTypes.push(getTypeOfSymbol(properties[i]));
55983                 }
55984             }
55985             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
55986             return createIndexInfo(unionType, isConstContext(node));
55987         }
55988         function getImmediateAliasedSymbol(symbol) {
55989             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
55990             var links = getSymbolLinks(symbol);
55991             if (!links.immediateTarget) {
55992                 var node = getDeclarationOfAliasSymbol(symbol);
55993                 if (!node)
55994                     return ts.Debug.fail();
55995                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
55996             }
55997             return links.immediateTarget;
55998         }
55999         function checkObjectLiteral(node, checkMode) {
56000             var inDestructuringPattern = ts.isAssignmentTarget(node);
56001             // Grammar checking
56002             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
56003             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56004             var propertiesTable = ts.createSymbolTable();
56005             var propertiesArray = [];
56006             var spread = emptyObjectType;
56007             var contextualType = getApparentTypeOfContextualType(node);
56008             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
56009                 (contextualType.pattern.kind === 189 /* ObjectBindingPattern */ || contextualType.pattern.kind === 193 /* ObjectLiteralExpression */);
56010             var inConstContext = isConstContext(node);
56011             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
56012             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
56013             var enumTag = ts.getJSDocEnumTag(node);
56014             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
56015             var objectFlags = freshObjectLiteralFlag;
56016             var patternWithComputedProperties = false;
56017             var hasComputedStringProperty = false;
56018             var hasComputedNumberProperty = false;
56019             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
56020             // As otherwise they may not be checked until exports for the type at this position are retrieved,
56021             // which may never occur.
56022             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
56023                 var elem = _a[_i];
56024                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
56025                     checkComputedPropertyName(elem.name);
56026                 }
56027             }
56028             var offset = 0;
56029             for (var i = 0; i < node.properties.length; i++) {
56030                 var memberDecl = node.properties[i];
56031                 var member = getSymbolOfNode(memberDecl);
56032                 var computedNameType = memberDecl.name && memberDecl.name.kind === 154 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
56033                     checkComputedPropertyName(memberDecl.name) : undefined;
56034                 if (memberDecl.kind === 281 /* PropertyAssignment */ ||
56035                     memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ||
56036                     ts.isObjectLiteralMethod(memberDecl)) {
56037                     var type = memberDecl.kind === 281 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
56038                         memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
56039                             checkObjectLiteralMethod(memberDecl, checkMode);
56040                     if (isInJavascript) {
56041                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
56042                         if (jsDocType) {
56043                             checkTypeAssignableTo(type, jsDocType, memberDecl);
56044                             type = jsDocType;
56045                         }
56046                         else if (enumTag && enumTag.typeExpression) {
56047                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
56048                         }
56049                     }
56050                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
56051                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
56052                     var prop = nameType ?
56053                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
56054                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
56055                     if (nameType) {
56056                         prop.nameType = nameType;
56057                     }
56058                     if (inDestructuringPattern) {
56059                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
56060                         // for the property, make the property optional.
56061                         var isOptional = (memberDecl.kind === 281 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
56062                             (memberDecl.kind === 282 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
56063                         if (isOptional) {
56064                             prop.flags |= 16777216 /* Optional */;
56065                         }
56066                     }
56067                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
56068                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
56069                         // binding pattern specifies a default value for the property, make the property optional.
56070                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
56071                         if (impliedProp) {
56072                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
56073                         }
56074                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
56075                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
56076                         }
56077                     }
56078                     prop.declarations = member.declarations;
56079                     prop.parent = member.parent;
56080                     if (member.valueDeclaration) {
56081                         prop.valueDeclaration = member.valueDeclaration;
56082                     }
56083                     prop.type = type;
56084                     prop.target = member;
56085                     member = prop;
56086                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
56087                 }
56088                 else if (memberDecl.kind === 283 /* SpreadAssignment */) {
56089                     if (languageVersion < 2 /* ES2015 */) {
56090                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
56091                     }
56092                     if (propertiesArray.length > 0) {
56093                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56094                         propertiesArray = [];
56095                         propertiesTable = ts.createSymbolTable();
56096                         hasComputedStringProperty = false;
56097                         hasComputedNumberProperty = false;
56098                     }
56099                     var type = getReducedType(checkExpression(memberDecl.expression));
56100                     if (!isValidSpreadType(type)) {
56101                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
56102                         return errorType;
56103                     }
56104                     if (allPropertiesTable) {
56105                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
56106                     }
56107                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
56108                     offset = i + 1;
56109                     continue;
56110                 }
56111                 else {
56112                     // TypeScript 1.0 spec (April 2014)
56113                     // A get accessor declaration is processed in the same manner as
56114                     // an ordinary function declaration(section 6.1) with no parameters.
56115                     // A set accessor declaration is processed in the same manner
56116                     // as an ordinary function declaration with a single parameter and a Void return type.
56117                     ts.Debug.assert(memberDecl.kind === 163 /* GetAccessor */ || memberDecl.kind === 164 /* SetAccessor */);
56118                     checkNodeDeferred(memberDecl);
56119                 }
56120                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
56121                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
56122                         if (isTypeAssignableTo(computedNameType, numberType)) {
56123                             hasComputedNumberProperty = true;
56124                         }
56125                         else {
56126                             hasComputedStringProperty = true;
56127                         }
56128                         if (inDestructuringPattern) {
56129                             patternWithComputedProperties = true;
56130                         }
56131                     }
56132                 }
56133                 else {
56134                     propertiesTable.set(member.escapedName, member);
56135                 }
56136                 propertiesArray.push(member);
56137             }
56138             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
56139             // type with those properties for which the binding pattern specifies a default value.
56140             // If the object literal is spread into another object literal, skip this step and let the top-level object
56141             // literal handle it instead.
56142             if (contextualTypeHasPattern && node.parent.kind !== 283 /* SpreadAssignment */) {
56143                 for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) {
56144                     var prop = _c[_b];
56145                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
56146                         if (!(prop.flags & 16777216 /* Optional */)) {
56147                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
56148                         }
56149                         propertiesTable.set(prop.escapedName, prop);
56150                         propertiesArray.push(prop);
56151                     }
56152                 }
56153             }
56154             if (spread !== emptyObjectType) {
56155                 if (propertiesArray.length > 0) {
56156                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56157                     propertiesArray = [];
56158                     propertiesTable = ts.createSymbolTable();
56159                     hasComputedStringProperty = false;
56160                     hasComputedNumberProperty = false;
56161                 }
56162                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
56163                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
56164             }
56165             return createObjectLiteralType();
56166             function createObjectLiteralType() {
56167                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
56168                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
56169                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
56170                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56171                 if (isJSObjectLiteral) {
56172                     result.objectFlags |= 16384 /* JSLiteral */;
56173                 }
56174                 if (patternWithComputedProperties) {
56175                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
56176                 }
56177                 if (inDestructuringPattern) {
56178                     result.pattern = node;
56179                 }
56180                 return result;
56181             }
56182         }
56183         function isValidSpreadType(type) {
56184             if (type.flags & 63176704 /* Instantiable */) {
56185                 var constraint = getBaseConstraintOfType(type);
56186                 if (constraint !== undefined) {
56187                     return isValidSpreadType(constraint);
56188                 }
56189             }
56190             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
56191                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
56192                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
56193         }
56194         function checkJsxSelfClosingElementDeferred(node) {
56195             checkJsxOpeningLikeElementOrOpeningFragment(node);
56196             resolveUntypedCall(node); // ensure type arguments and parameters are typechecked, even if there is an arity error
56197         }
56198         function checkJsxSelfClosingElement(node, _checkMode) {
56199             checkNodeDeferred(node);
56200             return getJsxElementTypeAt(node) || anyType;
56201         }
56202         function checkJsxElementDeferred(node) {
56203             // Check attributes
56204             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
56205             // Perform resolution on the closing tag so that rename/go to definition/etc work
56206             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
56207                 getIntrinsicTagSymbol(node.closingElement);
56208             }
56209             else {
56210                 checkExpression(node.closingElement.tagName);
56211             }
56212             checkJsxChildren(node);
56213         }
56214         function checkJsxElement(node, _checkMode) {
56215             checkNodeDeferred(node);
56216             return getJsxElementTypeAt(node) || anyType;
56217         }
56218         function checkJsxFragment(node) {
56219             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
56220             if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
56221                 error(node, compilerOptions.jsxFactory
56222                     ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
56223                     : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
56224             }
56225             checkJsxChildren(node);
56226             return getJsxElementTypeAt(node) || anyType;
56227         }
56228         /**
56229          * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
56230          */
56231         function isUnhyphenatedJsxName(name) {
56232             // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
56233             return !ts.stringContains(name, "-");
56234         }
56235         /**
56236          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
56237          */
56238         function isJsxIntrinsicIdentifier(tagName) {
56239             return tagName.kind === 75 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
56240         }
56241         function checkJsxAttribute(node, checkMode) {
56242             return node.initializer
56243                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
56244                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
56245         }
56246         /**
56247          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
56248          *
56249          * @param openingLikeElement a JSX opening-like element
56250          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
56251          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
56252          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
56253          * which also calls getSpreadType.
56254          */
56255         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
56256             var attributes = openingLikeElement.attributes;
56257             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56258             var attributesTable = ts.createSymbolTable();
56259             var spread = emptyJsxObjectType;
56260             var hasSpreadAnyType = false;
56261             var typeToIntersect;
56262             var explicitlySpecifyChildrenAttribute = false;
56263             var objectFlags = 4096 /* JsxAttributes */;
56264             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
56265             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
56266                 var attributeDecl = _a[_i];
56267                 var member = attributeDecl.symbol;
56268                 if (ts.isJsxAttribute(attributeDecl)) {
56269                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
56270                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
56271                     var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
56272                     attributeSymbol.declarations = member.declarations;
56273                     attributeSymbol.parent = member.parent;
56274                     if (member.valueDeclaration) {
56275                         attributeSymbol.valueDeclaration = member.valueDeclaration;
56276                     }
56277                     attributeSymbol.type = exprType;
56278                     attributeSymbol.target = member;
56279                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56280                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56281                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
56282                         explicitlySpecifyChildrenAttribute = true;
56283                     }
56284                 }
56285                 else {
56286                     ts.Debug.assert(attributeDecl.kind === 275 /* JsxSpreadAttribute */);
56287                     if (attributesTable.size > 0) {
56288                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56289                         attributesTable = ts.createSymbolTable();
56290                     }
56291                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
56292                     if (isTypeAny(exprType)) {
56293                         hasSpreadAnyType = true;
56294                     }
56295                     if (isValidSpreadType(exprType)) {
56296                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
56297                         if (allAttributesTable) {
56298                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
56299                         }
56300                     }
56301                     else {
56302                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
56303                     }
56304                 }
56305             }
56306             if (!hasSpreadAnyType) {
56307                 if (attributesTable.size > 0) {
56308                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56309                 }
56310             }
56311             // Handle children attribute
56312             var parent = openingLikeElement.parent.kind === 266 /* JsxElement */ ? openingLikeElement.parent : undefined;
56313             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
56314             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
56315                 var childrenTypes = checkJsxChildren(parent, checkMode);
56316                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
56317                     // Error if there is a attribute named "children" explicitly specified and children element.
56318                     // This is because children element will overwrite the value from attributes.
56319                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
56320                     if (explicitlySpecifyChildrenAttribute) {
56321                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
56322                     }
56323                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
56324                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
56325                     // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process
56326                     var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
56327                     childrenPropSymbol.type = childrenTypes.length === 1 ?
56328                         childrenTypes[0] :
56329                         (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
56330                     // Fake up a property declaration for the children
56331                     childrenPropSymbol.valueDeclaration = ts.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
56332                     childrenPropSymbol.valueDeclaration.parent = attributes;
56333                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
56334                     var childPropMap = ts.createSymbolTable();
56335                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
56336                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
56337                 }
56338             }
56339             if (hasSpreadAnyType) {
56340                 return anyType;
56341             }
56342             if (typeToIntersect && spread !== emptyJsxObjectType) {
56343                 return getIntersectionType([typeToIntersect, spread]);
56344             }
56345             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
56346             /**
56347              * Create anonymous type from given attributes symbol table.
56348              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
56349              * @param attributesTable a symbol table of attributes property
56350              */
56351             function createJsxAttributesType() {
56352                 objectFlags |= freshObjectLiteralFlag;
56353                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
56354                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56355                 return result;
56356             }
56357         }
56358         function checkJsxChildren(node, checkMode) {
56359             var childrenTypes = [];
56360             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
56361                 var child = _a[_i];
56362                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
56363                 // because then type of children property will have constituent of string type.
56364                 if (child.kind === 11 /* JsxText */) {
56365                     if (!child.containsOnlyTriviaWhiteSpaces) {
56366                         childrenTypes.push(stringType);
56367                     }
56368                 }
56369                 else {
56370                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
56371                 }
56372             }
56373             return childrenTypes;
56374         }
56375         function checkSpreadPropOverrides(type, props, spread) {
56376             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56377                 var right = _a[_i];
56378                 var left = props.get(right.escapedName);
56379                 var rightType = getTypeOfSymbol(right);
56380                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
56381                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
56382                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
56383                 }
56384             }
56385         }
56386         /**
56387          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
56388          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
56389          * @param node a JSXAttributes to be resolved of its type
56390          */
56391         function checkJsxAttributes(node, checkMode) {
56392             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
56393         }
56394         function getJsxType(name, location) {
56395             var namespace = getJsxNamespaceAt(location);
56396             var exports = namespace && getExportsOfSymbol(namespace);
56397             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
56398             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
56399         }
56400         /**
56401          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
56402          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
56403          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
56404          * May also return unknownSymbol if both of these lookups fail.
56405          */
56406         function getIntrinsicTagSymbol(node) {
56407             var links = getNodeLinks(node);
56408             if (!links.resolvedSymbol) {
56409                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
56410                 if (intrinsicElementsType !== errorType) {
56411                     // Property case
56412                     if (!ts.isIdentifier(node.tagName))
56413                         return ts.Debug.fail();
56414                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
56415                     if (intrinsicProp) {
56416                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
56417                         return links.resolvedSymbol = intrinsicProp;
56418                     }
56419                     // Intrinsic string indexer case
56420                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56421                     if (indexSignatureType) {
56422                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
56423                         return links.resolvedSymbol = intrinsicElementsType.symbol;
56424                     }
56425                     // Wasn't found
56426                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
56427                     return links.resolvedSymbol = unknownSymbol;
56428                 }
56429                 else {
56430                     if (noImplicitAny) {
56431                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
56432                     }
56433                     return links.resolvedSymbol = unknownSymbol;
56434                 }
56435             }
56436             return links.resolvedSymbol;
56437         }
56438         function getJsxNamespaceAt(location) {
56439             var links = location && getNodeLinks(location);
56440             if (links && links.jsxNamespace) {
56441                 return links.jsxNamespace;
56442             }
56443             if (!links || links.jsxNamespace !== false) {
56444                 var namespaceName = getJsxNamespace(location);
56445                 var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
56446                 if (resolvedNamespace) {
56447                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
56448                     if (candidate) {
56449                         if (links) {
56450                             links.jsxNamespace = candidate;
56451                         }
56452                         return candidate;
56453                     }
56454                     if (links) {
56455                         links.jsxNamespace = false;
56456                     }
56457                 }
56458             }
56459             // JSX global fallback
56460             return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
56461         }
56462         /**
56463          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
56464          * Get a single property from that container if existed. Report an error if there are more than one property.
56465          *
56466          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
56467          *          if other string is given or the container doesn't exist, return undefined.
56468          */
56469         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
56470             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
56471             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
56472             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
56473             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
56474             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
56475             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
56476             if (propertiesOfJsxElementAttribPropInterface) {
56477                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
56478                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
56479                     return "";
56480                 }
56481                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
56482                 // property of the class instance type
56483                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
56484                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
56485                 }
56486                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
56487                     // More than one property on ElementAttributesProperty is an error
56488                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
56489                 }
56490             }
56491             return undefined;
56492         }
56493         function getJsxLibraryManagedAttributes(jsxNamespace) {
56494             // JSX.LibraryManagedAttributes [symbol]
56495             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
56496         }
56497         /// e.g. "props" for React.d.ts,
56498         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
56499         ///     non-intrinsic elements' attributes type is 'any'),
56500         /// or '' if it has 0 properties (which means every
56501         ///     non-intrinsic elements' attributes type is the element instance type)
56502         function getJsxElementPropertiesName(jsxNamespace) {
56503             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
56504         }
56505         function getJsxElementChildrenPropertyName(jsxNamespace) {
56506             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
56507         }
56508         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
56509             if (elementType.flags & 4 /* String */) {
56510                 return [anySignature];
56511             }
56512             else if (elementType.flags & 128 /* StringLiteral */) {
56513                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
56514                 if (!intrinsicType) {
56515                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
56516                     return ts.emptyArray;
56517                 }
56518                 else {
56519                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
56520                     return [fakeSignature];
56521                 }
56522             }
56523             var apparentElemType = getApparentType(elementType);
56524             // Resolve the signatures, preferring constructor
56525             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
56526             if (signatures.length === 0) {
56527                 // No construct signatures, try call signatures
56528                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
56529             }
56530             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
56531                 // If each member has some combination of new/call signatures; make a union signature list for those
56532                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
56533             }
56534             return signatures;
56535         }
56536         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
56537             // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type
56538             // For example:
56539             //      var CustomTag: "h1" = "h1";
56540             //      <CustomTag> Hello World </CustomTag>
56541             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
56542             if (intrinsicElementsType !== errorType) {
56543                 var stringLiteralTypeName = type.value;
56544                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
56545                 if (intrinsicProp) {
56546                     return getTypeOfSymbol(intrinsicProp);
56547                 }
56548                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56549                 if (indexSignatureType) {
56550                     return indexSignatureType;
56551                 }
56552                 return undefined;
56553             }
56554             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
56555             return anyType;
56556         }
56557         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
56558             if (refKind === 1 /* Function */) {
56559                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56560                 if (sfcReturnConstraint) {
56561                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56562                 }
56563             }
56564             else if (refKind === 0 /* Component */) {
56565                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56566                 if (classConstraint) {
56567                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
56568                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56569                 }
56570             }
56571             else { // Mixed
56572                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56573                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56574                 if (!sfcReturnConstraint || !classConstraint) {
56575                     return;
56576                 }
56577                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
56578                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56579             }
56580             function generateInitialErrorChain() {
56581                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
56582                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
56583             }
56584         }
56585         /**
56586          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
56587          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
56588          * @param node an intrinsic JSX opening-like element
56589          */
56590         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
56591             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
56592             var links = getNodeLinks(node);
56593             if (!links.resolvedJsxElementAttributesType) {
56594                 var symbol = getIntrinsicTagSymbol(node);
56595                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
56596                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
56597                 }
56598                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
56599                     return links.resolvedJsxElementAttributesType =
56600                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
56601                 }
56602                 else {
56603                     return links.resolvedJsxElementAttributesType = errorType;
56604                 }
56605             }
56606             return links.resolvedJsxElementAttributesType;
56607         }
56608         function getJsxElementClassTypeAt(location) {
56609             var type = getJsxType(JsxNames.ElementClass, location);
56610             if (type === errorType)
56611                 return undefined;
56612             return type;
56613         }
56614         function getJsxElementTypeAt(location) {
56615             return getJsxType(JsxNames.Element, location);
56616         }
56617         function getJsxStatelessElementTypeAt(location) {
56618             var jsxElementType = getJsxElementTypeAt(location);
56619             if (jsxElementType) {
56620                 return getUnionType([jsxElementType, nullType]);
56621             }
56622         }
56623         /**
56624          * Returns all the properties of the Jsx.IntrinsicElements interface
56625          */
56626         function getJsxIntrinsicTagNamesAt(location) {
56627             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
56628             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
56629         }
56630         function checkJsxPreconditions(errorNode) {
56631             // Preconditions for using JSX
56632             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
56633                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
56634             }
56635             if (getJsxElementTypeAt(errorNode) === undefined) {
56636                 if (noImplicitAny) {
56637                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
56638                 }
56639             }
56640         }
56641         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
56642             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
56643             if (isNodeOpeningLikeElement) {
56644                 checkGrammarJsxElement(node);
56645             }
56646             checkJsxPreconditions(node);
56647             // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
56648             // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
56649             var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
56650             var reactNamespace = getJsxNamespace(node);
56651             var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
56652             var reactSym = resolveName(reactLocation, reactNamespace, 111551 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
56653             if (reactSym) {
56654                 // Mark local symbol as referenced here because it might not have been marked
56655                 // if jsx emit was not react as there wont be error being emitted
56656                 reactSym.isReferenced = 67108863 /* All */;
56657                 // If react symbol is alias, mark it as refereced
56658                 if (reactSym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(reactSym)) {
56659                     markAliasSymbolAsReferenced(reactSym);
56660                 }
56661             }
56662             if (isNodeOpeningLikeElement) {
56663                 var jsxOpeningLikeNode = node;
56664                 var sig = getResolvedSignature(jsxOpeningLikeNode);
56665                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
56666             }
56667         }
56668         /**
56669          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
56670          * is considered known if
56671          * 1. the object type is empty and the check is for assignability, or
56672          * 2. if the object type has index signatures, or
56673          * 3. if the property is actually declared in the object type
56674          *    (this means that 'toString', for example, is not usually a known property).
56675          * 4. In a union or intersection type,
56676          *    a property is considered known if it is known in any constituent type.
56677          * @param targetType a type to search a given name in
56678          * @param name a property name to search
56679          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
56680          */
56681         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
56682             if (targetType.flags & 524288 /* Object */) {
56683                 var resolved = resolveStructuredTypeMembers(targetType);
56684                 if (resolved.stringIndexInfo ||
56685                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
56686                     getPropertyOfObjectType(targetType, name) ||
56687                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
56688                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
56689                     return true;
56690                 }
56691             }
56692             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
56693                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
56694                     var t = _a[_i];
56695                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
56696                         return true;
56697                     }
56698                 }
56699             }
56700             return false;
56701         }
56702         function isExcessPropertyCheckTarget(type) {
56703             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
56704                 type.flags & 67108864 /* NonPrimitive */ ||
56705                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
56706                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
56707         }
56708         function checkJsxExpression(node, checkMode) {
56709             checkGrammarJsxExpression(node);
56710             if (node.expression) {
56711                 var type = checkExpression(node.expression, checkMode);
56712                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
56713                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
56714                 }
56715                 return type;
56716             }
56717             else {
56718                 return errorType;
56719             }
56720         }
56721         function getDeclarationNodeFlagsFromSymbol(s) {
56722             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
56723         }
56724         /**
56725          * Return whether this symbol is a member of a prototype somewhere
56726          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
56727          */
56728         function isPrototypeProperty(symbol) {
56729             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
56730                 return true;
56731             }
56732             if (ts.isInJSFile(symbol.valueDeclaration)) {
56733                 var parent = symbol.valueDeclaration.parent;
56734                 return parent && ts.isBinaryExpression(parent) &&
56735                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
56736             }
56737         }
56738         /**
56739          * Check whether the requested property access is valid.
56740          * Returns true if node is a valid property access, and false otherwise.
56741          * @param node The node to be checked.
56742          * @param isSuper True if the access is from `super.`.
56743          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
56744          * @param prop The symbol for the property being accessed.
56745          */
56746         function checkPropertyAccessibility(node, isSuper, type, prop) {
56747             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
56748             var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name;
56749             if (isSuper) {
56750                 // TS 1.0 spec (April 2014): 4.8.2
56751                 // - In a constructor, instance member function, instance member accessor, or
56752                 //   instance member variable initializer where this references a derived class instance,
56753                 //   a super property access is permitted and must specify a public instance member function of the base class.
56754                 // - In a static member function or static member accessor
56755                 //   where this references the constructor function object of a derived class,
56756                 //   a super property access is permitted and must specify a public static member function of the base class.
56757                 if (languageVersion < 2 /* ES2015 */) {
56758                     if (symbolHasNonMethodDeclaration(prop)) {
56759                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
56760                         return false;
56761                     }
56762                 }
56763                 if (flags & 128 /* Abstract */) {
56764                     // A method cannot be accessed in a super property access if the method is abstract.
56765                     // This error could mask a private property access error. But, a member
56766                     // cannot simultaneously be private and abstract, so this will trigger an
56767                     // additional error elsewhere.
56768                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56769                     return false;
56770                 }
56771             }
56772             // Referencing abstract properties within their own constructors is not allowed
56773             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
56774                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56775                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
56776                     error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217
56777                     return false;
56778                 }
56779             }
56780             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
56781                 if (!ts.getContainingClass(node)) {
56782                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56783                     return false;
56784                 }
56785                 return true;
56786             }
56787             // Public properties are otherwise accessible.
56788             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
56789                 return true;
56790             }
56791             // Property is known to be private or protected at this point
56792             // Private property is accessible if the property is within the declaring class
56793             if (flags & 8 /* Private */) {
56794                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56795                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
56796                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56797                     return false;
56798                 }
56799                 return true;
56800             }
56801             // Property is known to be protected at this point
56802             // All protected properties of a supertype are accessible in a super access
56803             if (isSuper) {
56804                 return true;
56805             }
56806             // Find the first enclosing class that has the declaring classes of the protected constituents
56807             // of the property as base classes
56808             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
56809                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
56810                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
56811             });
56812             // A protected property is accessible if the property is within the declaring class or classes derived from it
56813             if (!enclosingClass) {
56814                 // allow PropertyAccessibility if context is in function with this parameter
56815                 // static member access is disallow
56816                 var thisParameter = void 0;
56817                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
56818                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
56819                     return false;
56820                 }
56821                 var thisType = getTypeFromTypeNode(thisParameter.type);
56822                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
56823             }
56824             // No further restrictions for static properties
56825             if (flags & 32 /* Static */) {
56826                 return true;
56827             }
56828             if (type.flags & 262144 /* TypeParameter */) {
56829                 // get the original type -- represented as the type constraint of the 'this' type
56830                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
56831             }
56832             if (!type || !hasBaseType(type, enclosingClass)) {
56833                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
56834                 return false;
56835             }
56836             return true;
56837         }
56838         function getThisParameterFromNodeContext(node) {
56839             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
56840             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
56841         }
56842         function symbolHasNonMethodDeclaration(symbol) {
56843             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
56844         }
56845         function checkNonNullExpression(node) {
56846             return checkNonNullType(checkExpression(node), node);
56847         }
56848         function isNullableType(type) {
56849             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
56850         }
56851         function getNonNullableTypeIfNeeded(type) {
56852             return isNullableType(type) ? getNonNullableType(type) : type;
56853         }
56854         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
56855             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56856                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
56857                 ts.Diagnostics.Object_is_possibly_undefined :
56858                 ts.Diagnostics.Object_is_possibly_null);
56859         }
56860         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
56861             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56862                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
56863                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
56864                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
56865         }
56866         function checkNonNullTypeWithReporter(type, node, reportError) {
56867             if (strictNullChecks && type.flags & 2 /* Unknown */) {
56868                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
56869                 return errorType;
56870             }
56871             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
56872             if (kind) {
56873                 reportError(node, kind);
56874                 var t = getNonNullableType(type);
56875                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
56876             }
56877             return type;
56878         }
56879         function checkNonNullType(type, node) {
56880             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
56881         }
56882         function checkNonNullNonVoidType(type, node) {
56883             var nonNullType = checkNonNullType(type, node);
56884             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
56885                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
56886             }
56887             return nonNullType;
56888         }
56889         function checkPropertyAccessExpression(node) {
56890             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
56891                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
56892         }
56893         function checkPropertyAccessChain(node) {
56894             var leftType = checkExpression(node.expression);
56895             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
56896             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
56897         }
56898         function checkQualifiedName(node) {
56899             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
56900         }
56901         function isMethodAccessForCall(node) {
56902             while (node.parent.kind === 200 /* ParenthesizedExpression */) {
56903                 node = node.parent;
56904             }
56905             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
56906         }
56907         // Lookup the private identifier lexically.
56908         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
56909             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
56910                 var symbol = containingClass.symbol;
56911                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
56912                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
56913                 if (prop) {
56914                     return prop;
56915                 }
56916             }
56917         }
56918         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
56919             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
56920         }
56921         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
56922             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
56923             // Find a private identifier with the same description on the type.
56924             var propertyOnType;
56925             var properties = getPropertiesOfType(leftType);
56926             if (properties) {
56927                 ts.forEach(properties, function (symbol) {
56928                     var decl = symbol.valueDeclaration;
56929                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
56930                         propertyOnType = symbol;
56931                         return true;
56932                     }
56933                 });
56934             }
56935             var diagName = diagnosticName(right);
56936             if (propertyOnType) {
56937                 var typeValueDecl = propertyOnType.valueDeclaration;
56938                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
56939                 ts.Debug.assert(!!typeClass_1);
56940                 // We found a private identifier property with the same description.
56941                 // Either:
56942                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
56943                 // - It is an attempt to access the private identifier outside of the class.
56944                 if (lexicallyScopedIdentifier) {
56945                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
56946                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
56947                     ts.Debug.assert(!!lexicalClass);
56948                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
56949                         var diagnostic = error(right, ts.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));
56950                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(lexicalValueDecl, ts.Diagnostics.The_shadowing_declaration_of_0_is_defined_here, diagName), ts.createDiagnosticForNode(typeValueDecl, ts.Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here, diagName));
56951                         return true;
56952                     }
56953                 }
56954                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
56955                 return true;
56956             }
56957             return false;
56958         }
56959         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
56960             var parentSymbol = getNodeLinks(left).resolvedSymbol;
56961             var assignmentKind = ts.getAssignmentTargetKind(node);
56962             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
56963             if (ts.isPrivateIdentifier(right)) {
56964                 checkExternalEmitHelpers(node, 262144 /* ClassPrivateFieldGet */);
56965             }
56966             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
56967             var prop;
56968             if (ts.isPrivateIdentifier(right)) {
56969                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
56970                 if (isAnyLike) {
56971                     if (lexicallyScopedSymbol) {
56972                         return apparentType;
56973                     }
56974                     if (!ts.getContainingClass(right)) {
56975                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56976                         return anyType;
56977                     }
56978                 }
56979                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
56980                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
56981                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
56982                     return errorType;
56983                 }
56984             }
56985             else {
56986                 if (isAnyLike) {
56987                     if (ts.isIdentifier(left) && parentSymbol) {
56988                         markAliasReferenced(parentSymbol, node);
56989                     }
56990                     return apparentType;
56991                 }
56992                 prop = getPropertyOfType(apparentType, right.escapedText);
56993             }
56994             if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
56995                 markAliasReferenced(parentSymbol, node);
56996             }
56997             var propType;
56998             if (!prop) {
56999                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
57000                 if (!(indexInfo && indexInfo.type)) {
57001                     if (isJSLiteralType(leftType)) {
57002                         return anyType;
57003                     }
57004                     if (leftType.symbol === globalThisSymbol) {
57005                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
57006                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
57007                         }
57008                         else if (noImplicitAny) {
57009                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
57010                         }
57011                         return anyType;
57012                     }
57013                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
57014                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
57015                     }
57016                     return errorType;
57017                 }
57018                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
57019                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
57020                 }
57021                 propType = indexInfo.type;
57022             }
57023             else {
57024                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
57025                 markPropertyAsReferenced(prop, node, left.kind === 104 /* ThisKeyword */);
57026                 getNodeLinks(node).resolvedSymbol = prop;
57027                 checkPropertyAccessibility(node, left.kind === 102 /* SuperKeyword */, apparentType, prop);
57028                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
57029                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
57030                     return errorType;
57031                 }
57032                 propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
57033             }
57034             return getFlowTypeOfAccessExpression(node, prop, propType, right);
57035         }
57036         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
57037             // Only compute control flow type if this is a property access expression that isn't an
57038             // assignment target, and the referenced property was declared as a variable, property,
57039             // accessor, or optional method.
57040             var assignmentKind = ts.getAssignmentTargetKind(node);
57041             if (!ts.isAccessExpression(node) ||
57042                 assignmentKind === 1 /* Definite */ ||
57043                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
57044                 return propType;
57045             }
57046             // If strict null checks and strict property initialization checks are enabled, if we have
57047             // a this.xxx property access, if the property is an instance property without an initializer,
57048             // and if we are in a constructor of the same class as the property declaration, assume that
57049             // the property is uninitialized at the top of the control flow.
57050             var assumeUninitialized = false;
57051             if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 104 /* ThisKeyword */) {
57052                 var declaration = prop && prop.valueDeclaration;
57053                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
57054                     var flowContainer = getControlFlowContainer(node);
57055                     if (flowContainer.kind === 162 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
57056                         assumeUninitialized = true;
57057                     }
57058                 }
57059             }
57060             else if (strictNullChecks && prop && prop.valueDeclaration &&
57061                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
57062                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
57063                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
57064                 assumeUninitialized = true;
57065             }
57066             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
57067             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
57068                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
57069                 // Return the declared type to reduce follow-on errors
57070                 return propType;
57071             }
57072             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
57073         }
57074         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
57075             var valueDeclaration = prop.valueDeclaration;
57076             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
57077                 return;
57078             }
57079             var diagnosticMessage;
57080             var declarationName = ts.idText(right);
57081             if (isInPropertyInitializer(node)
57082                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
57083                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
57084                 && !isPropertyDeclaredInAncestorClass(prop)) {
57085                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
57086             }
57087             else if (valueDeclaration.kind === 245 /* ClassDeclaration */ &&
57088                 node.parent.kind !== 169 /* TypeReference */ &&
57089                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
57090                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
57091                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
57092             }
57093             if (diagnosticMessage) {
57094                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
57095             }
57096         }
57097         function isInPropertyInitializer(node) {
57098             return !!ts.findAncestor(node, function (node) {
57099                 switch (node.kind) {
57100                     case 159 /* PropertyDeclaration */:
57101                         return true;
57102                     case 281 /* PropertyAssignment */:
57103                     case 161 /* MethodDeclaration */:
57104                     case 163 /* GetAccessor */:
57105                     case 164 /* SetAccessor */:
57106                     case 283 /* SpreadAssignment */:
57107                     case 154 /* ComputedPropertyName */:
57108                     case 221 /* TemplateSpan */:
57109                     case 276 /* JsxExpression */:
57110                     case 273 /* JsxAttribute */:
57111                     case 274 /* JsxAttributes */:
57112                     case 275 /* JsxSpreadAttribute */:
57113                     case 268 /* JsxOpeningElement */:
57114                     case 216 /* ExpressionWithTypeArguments */:
57115                     case 279 /* HeritageClause */:
57116                         return false;
57117                     default:
57118                         return ts.isExpressionNode(node) ? false : "quit";
57119                 }
57120             });
57121         }
57122         /**
57123          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
57124          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
57125          */
57126         function isPropertyDeclaredInAncestorClass(prop) {
57127             if (!(prop.parent.flags & 32 /* Class */)) {
57128                 return false;
57129             }
57130             var classType = getTypeOfSymbol(prop.parent);
57131             while (true) {
57132                 classType = classType.symbol && getSuperClass(classType);
57133                 if (!classType) {
57134                     return false;
57135                 }
57136                 var superProperty = getPropertyOfType(classType, prop.escapedName);
57137                 if (superProperty && superProperty.valueDeclaration) {
57138                     return true;
57139                 }
57140             }
57141         }
57142         function getSuperClass(classType) {
57143             var x = getBaseTypes(classType);
57144             if (x.length === 0) {
57145                 return undefined;
57146             }
57147             return getIntersectionType(x);
57148         }
57149         function reportNonexistentProperty(propNode, containingType) {
57150             var errorInfo;
57151             var relatedInfo;
57152             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
57153                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
57154                     var subtype = _a[_i];
57155                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
57156                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
57157                         break;
57158                     }
57159                 }
57160             }
57161             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
57162                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57163             }
57164             else {
57165                 var promisedType = getPromisedTypeOfPromise(containingType);
57166                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
57167                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57168                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
57169                 }
57170                 else {
57171                     var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
57172                     if (suggestion !== undefined) {
57173                         var suggestedName = ts.symbolName(suggestion);
57174                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
57175                         relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
57176                     }
57177                     else {
57178                         errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57179                     }
57180                 }
57181             }
57182             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
57183             if (relatedInfo) {
57184                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
57185             }
57186             diagnostics.add(resultDiagnostic);
57187         }
57188         function typeHasStaticProperty(propName, containingType) {
57189             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
57190             return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
57191         }
57192         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
57193             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
57194         }
57195         function getSuggestionForNonexistentProperty(name, containingType) {
57196             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
57197             return suggestion && ts.symbolName(suggestion);
57198         }
57199         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
57200             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
57201             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
57202                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
57203                 var symbol = getSymbol(symbols, name, meaning);
57204                 // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function
57205                 // So the table *contains* `x` but `x` isn't actually in scope.
57206                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
57207                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
57208             });
57209             return result;
57210         }
57211         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
57212             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
57213             return symbolResult && ts.symbolName(symbolResult);
57214         }
57215         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
57216             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
57217         }
57218         function getSuggestionForNonexistentExport(name, targetModule) {
57219             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
57220             return suggestion && ts.symbolName(suggestion);
57221         }
57222         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
57223             // check if object type has setter or getter
57224             function hasProp(name) {
57225                 var prop = getPropertyOfObjectType(objectType, name);
57226                 if (prop) {
57227                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
57228                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
57229                 }
57230                 return false;
57231             }
57232             ;
57233             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
57234             if (!hasProp(suggestedMethod)) {
57235                 return undefined;
57236             }
57237             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
57238             if (suggestion === undefined) {
57239                 suggestion = suggestedMethod;
57240             }
57241             else {
57242                 suggestion += "." + suggestedMethod;
57243             }
57244             return suggestion;
57245         }
57246         /**
57247          * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
57248          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
57249          *
57250          * If there is a candidate that's the same except for case, return that.
57251          * If there is a candidate that's within one edit of the name, return that.
57252          * Otherwise, return the candidate with the smallest Levenshtein distance,
57253          *    except for candidates:
57254          *      * With no name
57255          *      * Whose meaning doesn't match the `meaning` parameter.
57256          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
57257          *      * Whose levenshtein distance is more than 0.4 of the length of the name
57258          *        (0.4 allows 1 substitution/transposition for every 5 characters,
57259          *         and 1 insertion/deletion at 3 characters)
57260          */
57261         function getSpellingSuggestionForName(name, symbols, meaning) {
57262             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
57263             function getCandidateName(candidate) {
57264                 var candidateName = ts.symbolName(candidate);
57265                 if (ts.startsWith(candidateName, "\"")) {
57266                     return undefined;
57267                 }
57268                 if (candidate.flags & meaning) {
57269                     return candidateName;
57270                 }
57271                 if (candidate.flags & 2097152 /* Alias */) {
57272                     var alias = tryResolveAlias(candidate);
57273                     if (alias && alias.flags & meaning) {
57274                         return candidateName;
57275                     }
57276                 }
57277                 return undefined;
57278             }
57279         }
57280         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
57281             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
57282             if (!valueDeclaration) {
57283                 return;
57284             }
57285             var hasPrivateModifier = ts.hasModifier(valueDeclaration, 8 /* Private */);
57286             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
57287             if (!hasPrivateModifier && !hasPrivateIdentifier) {
57288                 return;
57289             }
57290             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
57291                 return;
57292             }
57293             if (isThisAccess) {
57294                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
57295                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
57296                 if (containingMethod && containingMethod.symbol === prop) {
57297                     return;
57298                 }
57299             }
57300             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
57301         }
57302         function isValidPropertyAccess(node, propertyName) {
57303             switch (node.kind) {
57304                 case 194 /* PropertyAccessExpression */:
57305                     return isValidPropertyAccessWithType(node, node.expression.kind === 102 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
57306                 case 153 /* QualifiedName */:
57307                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
57308                 case 188 /* ImportType */:
57309                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
57310             }
57311         }
57312         function isValidPropertyAccessForCompletions(node, type, property) {
57313             return isValidPropertyAccessWithType(node, node.kind === 194 /* PropertyAccessExpression */ && node.expression.kind === 102 /* SuperKeyword */, property.escapedName, type);
57314             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
57315         }
57316         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
57317             if (type === errorType || isTypeAny(type)) {
57318                 return true;
57319             }
57320             var prop = getPropertyOfType(type, propertyName);
57321             if (prop) {
57322                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
57323                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
57324                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
57325                 }
57326                 return checkPropertyAccessibility(node, isSuper, type, prop);
57327             }
57328             // In js files properties of unions are allowed in completion
57329             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
57330         }
57331         /**
57332          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
57333          */
57334         function getForInVariableSymbol(node) {
57335             var initializer = node.initializer;
57336             if (initializer.kind === 243 /* VariableDeclarationList */) {
57337                 var variable = initializer.declarations[0];
57338                 if (variable && !ts.isBindingPattern(variable.name)) {
57339                     return getSymbolOfNode(variable);
57340                 }
57341             }
57342             else if (initializer.kind === 75 /* Identifier */) {
57343                 return getResolvedSymbol(initializer);
57344             }
57345             return undefined;
57346         }
57347         /**
57348          * Return true if the given type is considered to have numeric property names.
57349          */
57350         function hasNumericPropertyNames(type) {
57351             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
57352         }
57353         /**
57354          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
57355          * that references a for-in variable for an object with numeric property names.
57356          */
57357         function isForInVariableForNumericPropertyNames(expr) {
57358             var e = ts.skipParentheses(expr);
57359             if (e.kind === 75 /* Identifier */) {
57360                 var symbol = getResolvedSymbol(e);
57361                 if (symbol.flags & 3 /* Variable */) {
57362                     var child = expr;
57363                     var node = expr.parent;
57364                     while (node) {
57365                         if (node.kind === 231 /* ForInStatement */ &&
57366                             child === node.statement &&
57367                             getForInVariableSymbol(node) === symbol &&
57368                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
57369                             return true;
57370                         }
57371                         child = node;
57372                         node = node.parent;
57373                     }
57374                 }
57375             }
57376             return false;
57377         }
57378         function checkIndexedAccess(node) {
57379             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
57380                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
57381         }
57382         function checkElementAccessChain(node) {
57383             var exprType = checkExpression(node.expression);
57384             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
57385             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
57386         }
57387         function checkElementAccessExpression(node, exprType) {
57388             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
57389             var indexExpression = node.argumentExpression;
57390             var indexType = checkExpression(indexExpression);
57391             if (objectType === errorType || objectType === silentNeverType) {
57392                 return objectType;
57393             }
57394             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
57395                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
57396                 return errorType;
57397             }
57398             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
57399             var accessFlags = ts.isAssignmentTarget(node) ?
57400                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
57401                 0 /* None */;
57402             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
57403             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
57404         }
57405         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
57406             if (expressionType === errorType) {
57407                 // There is already an error, so no need to report one.
57408                 return false;
57409             }
57410             if (!ts.isWellKnownSymbolSyntactically(expression)) {
57411                 return false;
57412             }
57413             // Make sure the property type is the primitive symbol type
57414             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
57415                 if (reportError) {
57416                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
57417                 }
57418                 return false;
57419             }
57420             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
57421             // global Symbol object
57422             var leftHandSide = expression.expression;
57423             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
57424             if (!leftHandSideSymbol) {
57425                 return false;
57426             }
57427             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
57428             if (!globalESSymbol) {
57429                 // Already errored when we tried to look up the symbol
57430                 return false;
57431             }
57432             if (leftHandSideSymbol !== globalESSymbol) {
57433                 if (reportError) {
57434                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
57435                 }
57436                 return false;
57437             }
57438             return true;
57439         }
57440         function callLikeExpressionMayHaveTypeArguments(node) {
57441             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
57442         }
57443         function resolveUntypedCall(node) {
57444             if (callLikeExpressionMayHaveTypeArguments(node)) {
57445                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
57446                 // This gets us diagnostics for the type arguments and marks them as referenced.
57447                 ts.forEach(node.typeArguments, checkSourceElement);
57448             }
57449             if (node.kind === 198 /* TaggedTemplateExpression */) {
57450                 checkExpression(node.template);
57451             }
57452             else if (ts.isJsxOpeningLikeElement(node)) {
57453                 checkExpression(node.attributes);
57454             }
57455             else if (node.kind !== 157 /* Decorator */) {
57456                 ts.forEach(node.arguments, function (argument) {
57457                     checkExpression(argument);
57458                 });
57459             }
57460             return anySignature;
57461         }
57462         function resolveErrorCall(node) {
57463             resolveUntypedCall(node);
57464             return unknownSignature;
57465         }
57466         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
57467         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
57468         // A nit here is that we reorder only signatures that belong to the same symbol,
57469         // so order how inherited signatures are processed is still preserved.
57470         // interface A { (x: string): void }
57471         // interface B extends A { (x: 'foo'): string }
57472         // const b: B;
57473         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
57474         function reorderCandidates(signatures, result, callChainFlags) {
57475             var lastParent;
57476             var lastSymbol;
57477             var cutoffIndex = 0;
57478             var index;
57479             var specializedIndex = -1;
57480             var spliceIndex;
57481             ts.Debug.assert(!result.length);
57482             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
57483                 var signature = signatures_7[_i];
57484                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
57485                 var parent = signature.declaration && signature.declaration.parent;
57486                 if (!lastSymbol || symbol === lastSymbol) {
57487                     if (lastParent && parent === lastParent) {
57488                         index = index + 1;
57489                     }
57490                     else {
57491                         lastParent = parent;
57492                         index = cutoffIndex;
57493                     }
57494                 }
57495                 else {
57496                     // current declaration belongs to a different symbol
57497                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
57498                     index = cutoffIndex = result.length;
57499                     lastParent = parent;
57500                 }
57501                 lastSymbol = symbol;
57502                 // specialized signatures always need to be placed before non-specialized signatures regardless
57503                 // of the cutoff position; see GH#1133
57504                 if (signatureHasLiteralTypes(signature)) {
57505                     specializedIndex++;
57506                     spliceIndex = specializedIndex;
57507                     // The cutoff index always needs to be greater than or equal to the specialized signature index
57508                     // in order to prevent non-specialized signatures from being added before a specialized
57509                     // signature.
57510                     cutoffIndex++;
57511                 }
57512                 else {
57513                     spliceIndex = index;
57514                 }
57515                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
57516             }
57517         }
57518         function isSpreadArgument(arg) {
57519             return !!arg && (arg.kind === 213 /* SpreadElement */ || arg.kind === 220 /* SyntheticExpression */ && arg.isSpread);
57520         }
57521         function getSpreadArgumentIndex(args) {
57522             return ts.findIndex(args, isSpreadArgument);
57523         }
57524         function acceptsVoid(t) {
57525             return !!(t.flags & 16384 /* Void */);
57526         }
57527         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
57528             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
57529             var argCount;
57530             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
57531             var effectiveParameterCount = getParameterCount(signature);
57532             var effectiveMinimumArguments = getMinArgumentCount(signature);
57533             if (node.kind === 198 /* TaggedTemplateExpression */) {
57534                 argCount = args.length;
57535                 if (node.template.kind === 211 /* TemplateExpression */) {
57536                     // If a tagged template expression lacks a tail literal, the call is incomplete.
57537                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
57538                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
57539                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
57540                 }
57541                 else {
57542                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
57543                     // then this might actually turn out to be a TemplateHead in the future;
57544                     // so we consider the call to be incomplete.
57545                     var templateLiteral = node.template;
57546                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
57547                     callIsIncomplete = !!templateLiteral.isUnterminated;
57548                 }
57549             }
57550             else if (node.kind === 157 /* Decorator */) {
57551                 argCount = getDecoratorArgumentCount(node, signature);
57552             }
57553             else if (ts.isJsxOpeningLikeElement(node)) {
57554                 callIsIncomplete = node.attributes.end === node.end;
57555                 if (callIsIncomplete) {
57556                     return true;
57557                 }
57558                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
57559                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
57560                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
57561             }
57562             else {
57563                 if (!node.arguments) {
57564                     // This only happens when we have something of the form: 'new C'
57565                     ts.Debug.assert(node.kind === 197 /* NewExpression */);
57566                     return getMinArgumentCount(signature) === 0;
57567                 }
57568                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
57569                 // If we are missing the close parenthesis, the call is incomplete.
57570                 callIsIncomplete = node.arguments.end === node.end;
57571                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
57572                 var spreadArgIndex = getSpreadArgumentIndex(args);
57573                 if (spreadArgIndex >= 0) {
57574                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
57575                 }
57576             }
57577             // Too many arguments implies incorrect arity.
57578             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
57579                 return false;
57580             }
57581             // If the call is incomplete, we should skip the lower bound check.
57582             // JSX signatures can have extra parameters provided by the library which we don't check
57583             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
57584                 return true;
57585             }
57586             for (var i = argCount; i < effectiveMinimumArguments; i++) {
57587                 var type = getTypeAtPosition(signature, i);
57588                 if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
57589                     return false;
57590                 }
57591             }
57592             return true;
57593         }
57594         function hasCorrectTypeArgumentArity(signature, typeArguments) {
57595             // If the user supplied type arguments, but the number of type arguments does not match
57596             // the declared number of type parameters, the call has an incorrect arity.
57597             var numTypeParameters = ts.length(signature.typeParameters);
57598             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
57599             return !ts.some(typeArguments) ||
57600                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
57601         }
57602         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
57603         function getSingleCallSignature(type) {
57604             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
57605         }
57606         function getSingleCallOrConstructSignature(type) {
57607             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
57608                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
57609         }
57610         function getSingleSignature(type, kind, allowMembers) {
57611             if (type.flags & 524288 /* Object */) {
57612                 var resolved = resolveStructuredTypeMembers(type);
57613                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
57614                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
57615                         return resolved.callSignatures[0];
57616                     }
57617                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
57618                         return resolved.constructSignatures[0];
57619                     }
57620                 }
57621             }
57622             return undefined;
57623         }
57624         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
57625         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
57626             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
57627             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
57628             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
57629             // for T but leave it possible to later infer '[any]' back to A.
57630             var restType = getEffectiveRestType(contextualSignature);
57631             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
57632             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
57633             applyToParameterTypes(sourceSignature, signature, function (source, target) {
57634                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
57635                 inferTypes(context.inferences, source, target);
57636             });
57637             if (!inferenceContext) {
57638                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
57639                     inferTypes(context.inferences, source, target, 32 /* ReturnType */);
57640                 });
57641             }
57642             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
57643         }
57644         function inferJsxTypeArguments(node, signature, checkMode, context) {
57645             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57646             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
57647             inferTypes(context.inferences, checkAttrType, paramType);
57648             return getInferredTypes(context);
57649         }
57650         function inferTypeArguments(node, signature, args, checkMode, context) {
57651             if (ts.isJsxOpeningLikeElement(node)) {
57652                 return inferJsxTypeArguments(node, signature, checkMode, context);
57653             }
57654             // If a contextual type is available, infer from that type to the return type of the call expression. For
57655             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
57656             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
57657             // return type of 'wrap'.
57658             if (node.kind !== 157 /* Decorator */) {
57659                 var contextualType = getContextualType(node);
57660                 if (contextualType) {
57661                     // We clone the inference context to avoid disturbing a resolution in progress for an
57662                     // outer call expression. Effectively we just want a snapshot of whatever has been
57663                     // inferred for any outer call expression so far.
57664                     var outerContext = getInferenceContext(node);
57665                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
57666                     var instantiatedType = instantiateType(contextualType, outerMapper);
57667                     // If the contextual type is a generic function type with a single call signature, we
57668                     // instantiate the type with its own type parameters and type arguments. This ensures that
57669                     // the type parameters are not erased to type any during type inference such that they can
57670                     // be inferred as actual types from the contextual type. For example:
57671                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
57672                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
57673                     // Above, the type of the 'value' parameter is inferred to be 'A'.
57674                     var contextualSignature = getSingleCallSignature(instantiatedType);
57675                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
57676                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
57677                         instantiatedType;
57678                     var inferenceTargetType = getReturnTypeOfSignature(signature);
57679                     // Inferences made from return types have lower priority than all other inferences.
57680                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 32 /* ReturnType */);
57681                     // Create a type mapper for instantiating generic contextual types using the inferences made
57682                     // from the return type. We need a separate inference pass here because (a) instantiation of
57683                     // the source type uses the outer context's return mapper (which excludes inferences made from
57684                     // outer arguments), and (b) we don't want any further inferences going into this context.
57685                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
57686                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
57687                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
57688                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
57689                 }
57690             }
57691             var thisType = getThisTypeOfSignature(signature);
57692             if (thisType) {
57693                 var thisArgumentNode = getThisArgumentOfCall(node);
57694                 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
57695                 inferTypes(context.inferences, thisArgumentType, thisType);
57696             }
57697             var restType = getNonArrayRestType(signature);
57698             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57699             for (var i = 0; i < argCount; i++) {
57700                 var arg = args[i];
57701                 if (arg.kind !== 215 /* OmittedExpression */) {
57702                     var paramType = getTypeAtPosition(signature, i);
57703                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
57704                     inferTypes(context.inferences, argType, paramType);
57705                 }
57706             }
57707             if (restType) {
57708                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
57709                 inferTypes(context.inferences, spreadType, restType);
57710             }
57711             return getInferredTypes(context);
57712         }
57713         function getArrayifiedType(type) {
57714             return type.flags & 1048576 /* Union */ ? mapType(type, getArrayifiedType) :
57715                 type.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isMutableArrayOrTuple(type) ? type :
57716                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.minLength, type.target.hasRestElement, /*readonly*/ false, type.target.associatedNames) :
57717                         createArrayType(getIndexedAccessType(type, numberType));
57718         }
57719         function getSpreadArgumentType(args, index, argCount, restType, context) {
57720             if (index >= argCount - 1) {
57721                 var arg = args[argCount - 1];
57722                 if (isSpreadArgument(arg)) {
57723                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
57724                     // and the argument are ...x forms.
57725                     return arg.kind === 220 /* SyntheticExpression */ ?
57726                         createArrayType(arg.type) :
57727                         getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
57728                 }
57729             }
57730             var types = [];
57731             var spreadIndex = -1;
57732             for (var i = index; i < argCount; i++) {
57733                 var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
57734                 var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
57735                 if (spreadIndex < 0 && isSpreadArgument(args[i])) {
57736                     spreadIndex = i - index;
57737                 }
57738                 var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
57739                 types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
57740             }
57741             return spreadIndex < 0 ?
57742                 createTupleType(types) :
57743                 createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
57744         }
57745         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
57746             var isJavascript = ts.isInJSFile(signature.declaration);
57747             var typeParameters = signature.typeParameters;
57748             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
57749             var mapper;
57750             for (var i = 0; i < typeArgumentNodes.length; i++) {
57751                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
57752                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
57753                 if (constraint) {
57754                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
57755                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
57756                     if (!mapper) {
57757                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
57758                     }
57759                     var typeArgument = typeArgumentTypes[i];
57760                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
57761                         return undefined;
57762                     }
57763                 }
57764             }
57765             return typeArgumentTypes;
57766         }
57767         function getJsxReferenceKind(node) {
57768             if (isJsxIntrinsicIdentifier(node.tagName)) {
57769                 return 2 /* Mixed */;
57770             }
57771             var tagType = getApparentType(checkExpression(node.tagName));
57772             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
57773                 return 0 /* Component */;
57774             }
57775             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
57776                 return 1 /* Function */;
57777             }
57778             return 2 /* Mixed */;
57779         }
57780         /**
57781          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
57782          * @param node a JSX opening-like element we are trying to figure its call signature
57783          * @param signature a candidate signature we are trying whether it is a call signature
57784          * @param relation a relationship to check parameter and argument type
57785          */
57786         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
57787             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
57788             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
57789             // can be specified by users through attributes property.
57790             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57791             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
57792             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
57793             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57794             function checkTagNameDoesNotExpectTooManyArguments() {
57795                 var _a;
57796                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
57797                 if (!tagType) {
57798                     return true;
57799                 }
57800                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
57801                 if (!ts.length(tagCallSignatures)) {
57802                     return true;
57803                 }
57804                 var factory = getJsxFactoryEntity(node);
57805                 if (!factory) {
57806                     return true;
57807                 }
57808                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
57809                 if (!factorySymbol) {
57810                     return true;
57811                 }
57812                 var factoryType = getTypeOfSymbol(factorySymbol);
57813                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
57814                 if (!ts.length(callSignatures)) {
57815                     return true;
57816                 }
57817                 var hasFirstParamSignatures = false;
57818                 var maxParamCount = 0;
57819                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
57820                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
57821                     var sig = callSignatures_1[_i];
57822                     var firstparam = getTypeAtPosition(sig, 0);
57823                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
57824                     if (!ts.length(signaturesOfParam))
57825                         continue;
57826                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
57827                         var paramSig = signaturesOfParam_1[_b];
57828                         hasFirstParamSignatures = true;
57829                         if (hasEffectiveRestParameter(paramSig)) {
57830                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
57831                         }
57832                         var paramCount = getParameterCount(paramSig);
57833                         if (paramCount > maxParamCount) {
57834                             maxParamCount = paramCount;
57835                         }
57836                     }
57837                 }
57838                 if (!hasFirstParamSignatures) {
57839                     // Not a single signature had a first parameter which expected a signature - for back compat, and
57840                     // to guard against generic factories which won't have signatures directly, do not error
57841                     return true;
57842                 }
57843                 var absoluteMinArgCount = Infinity;
57844                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
57845                     var tagSig = tagCallSignatures_1[_c];
57846                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
57847                     if (tagRequiredArgCount < absoluteMinArgCount) {
57848                         absoluteMinArgCount = tagRequiredArgCount;
57849                     }
57850                 }
57851                 if (absoluteMinArgCount <= maxParamCount) {
57852                     return true; // some signature accepts the number of arguments the function component provides
57853                 }
57854                 if (reportErrors) {
57855                     var diag = ts.createDiagnosticForNode(node.tagName, ts.Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, ts.entityNameToString(node.tagName), absoluteMinArgCount, ts.entityNameToString(factory), maxParamCount);
57856                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
57857                     if (tagNameDeclaration) {
57858                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
57859                     }
57860                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
57861                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57862                     }
57863                     if (!errorOutputContainer.skipLogging) {
57864                         diagnostics.add(diag);
57865                     }
57866                 }
57867                 return false;
57868             }
57869         }
57870         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
57871             var errorOutputContainer = { errors: undefined, skipLogging: true };
57872             if (ts.isJsxOpeningLikeElement(node)) {
57873                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
57874                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
57875                     return errorOutputContainer.errors || ts.emptyArray;
57876                 }
57877                 return undefined;
57878             }
57879             var thisType = getThisTypeOfSignature(signature);
57880             if (thisType && thisType !== voidType && node.kind !== 197 /* NewExpression */) {
57881                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
57882                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
57883                 // If the expression is a new expression, then the check is skipped.
57884                 var thisArgumentNode = getThisArgumentOfCall(node);
57885                 var thisArgumentType = void 0;
57886                 if (thisArgumentNode) {
57887                     thisArgumentType = checkExpression(thisArgumentNode);
57888                     if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
57889                         thisArgumentType = getNonNullableType(thisArgumentType);
57890                     }
57891                     else if (ts.isOptionalChain(thisArgumentNode.parent)) {
57892                         thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
57893                     }
57894                 }
57895                 else {
57896                     thisArgumentType = voidType;
57897                 }
57898                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
57899                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
57900                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
57901                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
57902                     return errorOutputContainer.errors || ts.emptyArray;
57903                 }
57904             }
57905             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
57906             var restType = getNonArrayRestType(signature);
57907             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57908             for (var i = 0; i < argCount; i++) {
57909                 var arg = args[i];
57910                 if (arg.kind !== 215 /* OmittedExpression */) {
57911                     var paramType = getTypeAtPosition(signature, i);
57912                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
57913                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
57914                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
57915                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
57916                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
57917                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
57918                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
57919                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
57920                         return errorOutputContainer.errors || ts.emptyArray;
57921                     }
57922                 }
57923             }
57924             if (restType) {
57925                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
57926                 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
57927                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
57928                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
57929                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
57930                     return errorOutputContainer.errors || ts.emptyArray;
57931                 }
57932             }
57933             return undefined;
57934             function maybeAddMissingAwaitInfo(errorNode, source, target) {
57935                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
57936                     // Bail if target is Promise-like---something else is wrong
57937                     if (getAwaitedTypeOfPromise(target)) {
57938                         return;
57939                     }
57940                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
57941                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
57942                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
57943                     }
57944                 }
57945             }
57946         }
57947         /**
57948          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
57949          */
57950         function getThisArgumentOfCall(node) {
57951             if (node.kind === 196 /* CallExpression */) {
57952                 var callee = ts.skipOuterExpressions(node.expression);
57953                 if (ts.isAccessExpression(callee)) {
57954                     return callee.expression;
57955                 }
57956             }
57957         }
57958         function createSyntheticExpression(parent, type, isSpread) {
57959             var result = ts.createNode(220 /* SyntheticExpression */, parent.pos, parent.end);
57960             result.parent = parent;
57961             result.type = type;
57962             result.isSpread = isSpread || false;
57963             return result;
57964         }
57965         /**
57966          * Returns the effective arguments for an expression that works like a function invocation.
57967          */
57968         function getEffectiveCallArguments(node) {
57969             if (node.kind === 198 /* TaggedTemplateExpression */) {
57970                 var template = node.template;
57971                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
57972                 if (template.kind === 211 /* TemplateExpression */) {
57973                     ts.forEach(template.templateSpans, function (span) {
57974                         args_3.push(span.expression);
57975                     });
57976                 }
57977                 return args_3;
57978             }
57979             if (node.kind === 157 /* Decorator */) {
57980                 return getEffectiveDecoratorArguments(node);
57981             }
57982             if (ts.isJsxOpeningLikeElement(node)) {
57983                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
57984             }
57985             var args = node.arguments || ts.emptyArray;
57986             var length = args.length;
57987             if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
57988                 // We have a spread argument in the last position and no other spread arguments. If the type
57989                 // of the argument is a tuple type, spread the tuple elements into the argument list. We can
57990                 // call checkExpressionCached because spread expressions never have a contextual type.
57991                 var spreadArgument_1 = args[length - 1];
57992                 var type = flowLoopCount ? checkExpression(spreadArgument_1.expression) : checkExpressionCached(spreadArgument_1.expression);
57993                 if (isTupleType(type)) {
57994                     var typeArguments = getTypeArguments(type);
57995                     var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
57996                     var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
57997                     return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
57998                 }
57999             }
58000             return args;
58001         }
58002         /**
58003          * Returns the synthetic argument list for a decorator invocation.
58004          */
58005         function getEffectiveDecoratorArguments(node) {
58006             var parent = node.parent;
58007             var expr = node.expression;
58008             switch (parent.kind) {
58009                 case 245 /* ClassDeclaration */:
58010                 case 214 /* ClassExpression */:
58011                     // For a class decorator, the `target` is the type of the class (e.g. the
58012                     // "static" or "constructor" side of the class).
58013                     return [
58014                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
58015                     ];
58016                 case 156 /* Parameter */:
58017                     // A parameter declaration decorator will have three arguments (see
58018                     // `ParameterDecorator` in core.d.ts).
58019                     var func = parent.parent;
58020                     return [
58021                         createSyntheticExpression(expr, parent.parent.kind === 162 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
58022                         createSyntheticExpression(expr, anyType),
58023                         createSyntheticExpression(expr, numberType)
58024                     ];
58025                 case 159 /* PropertyDeclaration */:
58026                 case 161 /* MethodDeclaration */:
58027                 case 163 /* GetAccessor */:
58028                 case 164 /* SetAccessor */:
58029                     // A method or accessor declaration decorator will have two or three arguments (see
58030                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
58031                     // for ES3, we will only pass two arguments.
58032                     var hasPropDesc = parent.kind !== 159 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
58033                     return [
58034                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
58035                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
58036                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
58037                     ];
58038             }
58039             return ts.Debug.fail();
58040         }
58041         /**
58042          * Returns the argument count for a decorator node that works like a function invocation.
58043          */
58044         function getDecoratorArgumentCount(node, signature) {
58045             switch (node.parent.kind) {
58046                 case 245 /* ClassDeclaration */:
58047                 case 214 /* ClassExpression */:
58048                     return 1;
58049                 case 159 /* PropertyDeclaration */:
58050                     return 2;
58051                 case 161 /* MethodDeclaration */:
58052                 case 163 /* GetAccessor */:
58053                 case 164 /* SetAccessor */:
58054                     // For ES3 or decorators with only two parameters we supply only two arguments
58055                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
58056                 case 156 /* Parameter */:
58057                     return 3;
58058                 default:
58059                     return ts.Debug.fail();
58060             }
58061         }
58062         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
58063             var start;
58064             var length;
58065             var sourceFile = ts.getSourceFileOfNode(node);
58066             if (ts.isPropertyAccessExpression(node.expression)) {
58067                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
58068                 start = nameSpan.start;
58069                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
58070             }
58071             else {
58072                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
58073                 start = expressionSpan.start;
58074                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
58075             }
58076             return { start: start, length: length, sourceFile: sourceFile };
58077         }
58078         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
58079             if (ts.isCallExpression(node)) {
58080                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
58081                 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
58082             }
58083             else {
58084                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
58085             }
58086         }
58087         function getArgumentArityError(node, signatures, args) {
58088             var min = Number.POSITIVE_INFINITY;
58089             var max = Number.NEGATIVE_INFINITY;
58090             var belowArgCount = Number.NEGATIVE_INFINITY;
58091             var aboveArgCount = Number.POSITIVE_INFINITY;
58092             var argCount = args.length;
58093             var closestSignature;
58094             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
58095                 var sig = signatures_8[_i];
58096                 var minCount = getMinArgumentCount(sig);
58097                 var maxCount = getParameterCount(sig);
58098                 if (minCount < argCount && minCount > belowArgCount)
58099                     belowArgCount = minCount;
58100                 if (argCount < maxCount && maxCount < aboveArgCount)
58101                     aboveArgCount = maxCount;
58102                 if (minCount < min) {
58103                     min = minCount;
58104                     closestSignature = sig;
58105                 }
58106                 max = Math.max(max, maxCount);
58107             }
58108             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
58109             var paramRange = hasRestParameter ? min :
58110                 min < max ? min + "-" + max :
58111                     min;
58112             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
58113             if (argCount <= max && hasSpreadArgument) {
58114                 argCount--;
58115             }
58116             var spanArray;
58117             var related;
58118             var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
58119                 hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
58120                     ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
58121             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
58122                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
58123                 if (paramDecl) {
58124                     related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined);
58125                 }
58126             }
58127             if (min < argCount && argCount < max) {
58128                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
58129             }
58130             if (!hasSpreadArgument && argCount < min) {
58131                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
58132                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
58133             }
58134             if (hasRestParameter || hasSpreadArgument) {
58135                 spanArray = ts.createNodeArray(args);
58136                 if (hasSpreadArgument && argCount) {
58137                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
58138                     spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
58139                 }
58140             }
58141             else {
58142                 spanArray = ts.createNodeArray(args.slice(max));
58143             }
58144             spanArray.pos = ts.first(spanArray).pos;
58145             spanArray.end = ts.last(spanArray).end;
58146             if (spanArray.end === spanArray.pos) {
58147                 spanArray.end++;
58148             }
58149             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
58150             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
58151         }
58152         function getTypeArgumentArityError(node, signatures, typeArguments) {
58153             var argCount = typeArguments.length;
58154             // No overloads exist
58155             if (signatures.length === 1) {
58156                 var sig = signatures[0];
58157                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
58158                 var max = ts.length(sig.typeParameters);
58159                 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount);
58160             }
58161             // Overloads exist
58162             var belowArgCount = -Infinity;
58163             var aboveArgCount = Infinity;
58164             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
58165                 var sig = signatures_9[_i];
58166                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
58167                 var max = ts.length(sig.typeParameters);
58168                 if (min_2 > argCount) {
58169                     aboveArgCount = Math.min(aboveArgCount, min_2);
58170                 }
58171                 else if (max < argCount) {
58172                     belowArgCount = Math.max(belowArgCount, max);
58173                 }
58174             }
58175             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
58176                 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount);
58177             }
58178             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
58179         }
58180         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
58181             var isTaggedTemplate = node.kind === 198 /* TaggedTemplateExpression */;
58182             var isDecorator = node.kind === 157 /* Decorator */;
58183             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
58184             var reportErrors = !candidatesOutArray;
58185             var typeArguments;
58186             if (!isDecorator) {
58187                 typeArguments = node.typeArguments;
58188                 // We already perform checking on the type arguments on the class declaration itself.
58189                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 102 /* SuperKeyword */) {
58190                     ts.forEach(typeArguments, checkSourceElement);
58191                 }
58192             }
58193             var candidates = candidatesOutArray || [];
58194             // reorderCandidates fills up the candidates array directly
58195             reorderCandidates(signatures, candidates, callChainFlags);
58196             if (!candidates.length) {
58197                 if (reportErrors) {
58198                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
58199                 }
58200                 return resolveErrorCall(node);
58201             }
58202             var args = getEffectiveCallArguments(node);
58203             // The excludeArgument array contains true for each context sensitive argument (an argument
58204             // is context sensitive it is susceptible to a one-time permanent contextual typing).
58205             //
58206             // The idea is that we will perform type argument inference & assignability checking once
58207             // without using the susceptible parameters that are functions, and once more for those
58208             // parameters, contextually typing each as we go along.
58209             //
58210             // For a tagged template, then the first argument be 'undefined' if necessary because it
58211             // represents a TemplateStringsArray.
58212             //
58213             // For a decorator, no arguments are susceptible to contextual typing due to the fact
58214             // decorators are applied to a declaration by the emitter, and not to an expression.
58215             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
58216             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
58217             // The following variables are captured and modified by calls to chooseOverload.
58218             // If overload resolution or type argument inference fails, we want to report the
58219             // best error possible. The best error is one which says that an argument was not
58220             // assignable to a parameter. This implies that everything else about the overload
58221             // was fine. So if there is any overload that is only incorrect because of an
58222             // argument, we will report an error on that one.
58223             //
58224             //     function foo(s: string): void;
58225             //     function foo(n: number): void; // Report argument error on this overload
58226             //     function foo(): void;
58227             //     foo(true);
58228             //
58229             // If none of the overloads even made it that far, there are two possibilities.
58230             // There was a problem with type arguments for some overload, in which case
58231             // report an error on that. Or none of the overloads even had correct arity,
58232             // in which case give an arity error.
58233             //
58234             //     function foo<T extends string>(x: T): void; // Report type argument error
58235             //     function foo(): void;
58236             //     foo<number>(0);
58237             //
58238             var candidatesForArgumentError;
58239             var candidateForArgumentArityError;
58240             var candidateForTypeArgumentError;
58241             var result;
58242             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
58243             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
58244             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 196 /* CallExpression */ && node.arguments.hasTrailingComma;
58245             // Section 4.12.1:
58246             // if the candidate list contains one or more signatures for which the type of each argument
58247             // expression is a subtype of each corresponding parameter type, the return type of the first
58248             // of those signatures becomes the return type of the function call.
58249             // Otherwise, the return type of the first signature in the candidate list becomes the return
58250             // type of the function call.
58251             //
58252             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
58253             // is just important for choosing the best signature. So in the case where there is only one
58254             // signature, the subtype pass is useless. So skipping it is an optimization.
58255             if (candidates.length > 1) {
58256                 result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
58257             }
58258             if (!result) {
58259                 result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
58260             }
58261             if (result) {
58262                 return result;
58263             }
58264             // No signatures were applicable. Now report errors based on the last applicable signature with
58265             // no arguments excluded from assignability checks.
58266             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
58267             // skip the checkApplicableSignature check.
58268             if (reportErrors) {
58269                 if (candidatesForArgumentError) {
58270                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
58271                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
58272                         var chain_1;
58273                         if (candidatesForArgumentError.length > 3) {
58274                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
58275                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
58276                         }
58277                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
58278                         if (diags) {
58279                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
58280                                 var d = diags_1[_i];
58281                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
58282                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
58283                                 }
58284                                 diagnostics.add(d);
58285                             }
58286                         }
58287                         else {
58288                             ts.Debug.fail("No error for last overload signature");
58289                         }
58290                     }
58291                     else {
58292                         var allDiagnostics = [];
58293                         var max = 0;
58294                         var min_3 = Number.MAX_VALUE;
58295                         var minIndex = 0;
58296                         var i_1 = 0;
58297                         var _loop_17 = function (c) {
58298                             var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); };
58299                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
58300                             if (diags_2) {
58301                                 if (diags_2.length <= min_3) {
58302                                     min_3 = diags_2.length;
58303                                     minIndex = i_1;
58304                                 }
58305                                 max = Math.max(max, diags_2.length);
58306                                 allDiagnostics.push(diags_2);
58307                             }
58308                             else {
58309                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
58310                             }
58311                             i_1++;
58312                         };
58313                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
58314                             var c = candidatesForArgumentError_1[_a];
58315                             _loop_17(c);
58316                         }
58317                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
58318                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
58319                         var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call);
58320                         var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; });
58321                         if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) {
58322                             var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
58323                             diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related });
58324                         }
58325                         else {
58326                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related));
58327                         }
58328                     }
58329                 }
58330                 else if (candidateForArgumentArityError) {
58331                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
58332                 }
58333                 else if (candidateForTypeArgumentError) {
58334                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
58335                 }
58336                 else {
58337                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
58338                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
58339                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
58340                     }
58341                     else if (!isDecorator) {
58342                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
58343                     }
58344                     else if (fallbackError) {
58345                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
58346                     }
58347                 }
58348             }
58349             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
58350             function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
58351                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
58352                 candidatesForArgumentError = undefined;
58353                 candidateForArgumentArityError = undefined;
58354                 candidateForTypeArgumentError = undefined;
58355                 if (isSingleNonGenericCandidate) {
58356                     var candidate = candidates[0];
58357                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58358                         return undefined;
58359                     }
58360                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58361                         candidatesForArgumentError = [candidate];
58362                         return undefined;
58363                     }
58364                     return candidate;
58365                 }
58366                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
58367                     var candidate = candidates[candidateIndex];
58368                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58369                         continue;
58370                     }
58371                     var checkCandidate = void 0;
58372                     var inferenceContext = void 0;
58373                     if (candidate.typeParameters) {
58374                         var typeArgumentTypes = void 0;
58375                         if (ts.some(typeArguments)) {
58376                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
58377                             if (!typeArgumentTypes) {
58378                                 candidateForTypeArgumentError = candidate;
58379                                 continue;
58380                             }
58381                         }
58382                         else {
58383                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58384                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
58385                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
58386                         }
58387                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58388                         // If the original signature has a generic rest type, instantiation may produce a
58389                         // signature with different arity and we need to perform another arity check.
58390                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58391                             candidateForArgumentArityError = checkCandidate;
58392                             continue;
58393                         }
58394                     }
58395                     else {
58396                         checkCandidate = candidate;
58397                     }
58398                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58399                         // Give preference to error candidates that have no rest parameters (as they are more specific)
58400                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58401                         continue;
58402                     }
58403                     if (argCheckMode) {
58404                         // If one or more context sensitive arguments were excluded, we start including
58405                         // them now (and keeping do so for any subsequent candidates) and perform a second
58406                         // round of type inference and applicability checking for this particular candidate.
58407                         argCheckMode = 0 /* Normal */;
58408                         if (inferenceContext) {
58409                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
58410                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58411                             // If the original signature has a generic rest type, instantiation may produce a
58412                             // signature with different arity and we need to perform another arity check.
58413                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58414                                 candidateForArgumentArityError = checkCandidate;
58415                                 continue;
58416                             }
58417                         }
58418                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58419                             // Give preference to error candidates that have no rest parameters (as they are more specific)
58420                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58421                             continue;
58422                         }
58423                     }
58424                     candidates[candidateIndex] = checkCandidate;
58425                     return checkCandidate;
58426                 }
58427                 return undefined;
58428             }
58429         }
58430         // No signature was applicable. We have already reported the errors for the invalid signature.
58431         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
58432             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
58433             checkNodeDeferred(node);
58434             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
58435             // Don't do this if there is a `candidatesOutArray`,
58436             // because then we want the chosen best candidate to be one of the overloads, not a combination.
58437             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
58438                 ? pickLongestCandidateSignature(node, candidates, args)
58439                 : createUnionOfSignaturesForOverloadFailure(candidates);
58440         }
58441         function createUnionOfSignaturesForOverloadFailure(candidates) {
58442             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
58443             var thisParameter;
58444             if (thisParameters.length) {
58445                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
58446             }
58447             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
58448             var parameters = [];
58449             var _loop_18 = function (i) {
58450                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
58451                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
58452                     i < s.parameters.length ? s.parameters[i] : undefined; });
58453                 ts.Debug.assert(symbols.length !== 0);
58454                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
58455             };
58456             for (var i = 0; i < maxNonRestParam; i++) {
58457                 _loop_18(i);
58458             }
58459             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
58460             var flags = 0 /* None */;
58461             if (restParameterSymbols.length !== 0) {
58462                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
58463                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
58464                 flags |= 1 /* HasRestParameter */;
58465             }
58466             if (candidates.some(signatureHasLiteralTypes)) {
58467                 flags |= 2 /* HasLiteralTypes */;
58468             }
58469             return createSignature(candidates[0].declaration, 
58470             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
58471             thisParameter, parameters, 
58472             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
58473             /*typePredicate*/ undefined, minArgumentCount, flags);
58474         }
58475         function getNumNonRestParameters(signature) {
58476             var numParams = signature.parameters.length;
58477             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
58478         }
58479         function createCombinedSymbolFromTypes(sources, types) {
58480             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
58481         }
58482         function createCombinedSymbolForOverloadFailure(sources, type) {
58483             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
58484             return createSymbolWithType(ts.first(sources), type);
58485         }
58486         function pickLongestCandidateSignature(node, candidates, args) {
58487             // Pick the longest signature. This way we can get a contextual type for cases like:
58488             //     declare function f(a: { xa: number; xb: number; }, b: number);
58489             //     f({ |
58490             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
58491             //     declare function f<T>(k: keyof T);
58492             //     f<Foo>("
58493             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
58494             var candidate = candidates[bestIndex];
58495             var typeParameters = candidate.typeParameters;
58496             if (!typeParameters) {
58497                 return candidate;
58498             }
58499             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
58500             var instantiated = typeArgumentNodes
58501                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
58502                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
58503             candidates[bestIndex] = instantiated;
58504             return instantiated;
58505         }
58506         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
58507             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
58508             while (typeArguments.length > typeParameters.length) {
58509                 typeArguments.pop();
58510             }
58511             while (typeArguments.length < typeParameters.length) {
58512                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
58513             }
58514             return typeArguments;
58515         }
58516         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
58517             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58518             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
58519             return createSignatureInstantiation(candidate, typeArgumentTypes);
58520         }
58521         function getLongestCandidateIndex(candidates, argsCount) {
58522             var maxParamsIndex = -1;
58523             var maxParams = -1;
58524             for (var i = 0; i < candidates.length; i++) {
58525                 var candidate = candidates[i];
58526                 var paramCount = getParameterCount(candidate);
58527                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
58528                     return i;
58529                 }
58530                 if (paramCount > maxParams) {
58531                     maxParams = paramCount;
58532                     maxParamsIndex = i;
58533                 }
58534             }
58535             return maxParamsIndex;
58536         }
58537         function resolveCallExpression(node, candidatesOutArray, checkMode) {
58538             if (node.expression.kind === 102 /* SuperKeyword */) {
58539                 var superType = checkSuperExpression(node.expression);
58540                 if (isTypeAny(superType)) {
58541                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
58542                         var arg = _a[_i];
58543                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
58544                     }
58545                     return anySignature;
58546                 }
58547                 if (superType !== errorType) {
58548                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
58549                     // with the type arguments specified in the extends clause.
58550                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
58551                     if (baseTypeNode) {
58552                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
58553                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
58554                     }
58555                 }
58556                 return resolveUntypedCall(node);
58557             }
58558             var callChainFlags;
58559             var funcType = checkExpression(node.expression);
58560             if (ts.isCallChain(node)) {
58561                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
58562                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
58563                     ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
58564                         4 /* IsInnerCallChain */;
58565                 funcType = nonOptionalType;
58566             }
58567             else {
58568                 callChainFlags = 0 /* None */;
58569             }
58570             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
58571             if (funcType === silentNeverType) {
58572                 return silentNeverSignature;
58573             }
58574             var apparentType = getApparentType(funcType);
58575             if (apparentType === errorType) {
58576                 // Another error has already been reported
58577                 return resolveErrorCall(node);
58578             }
58579             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58580             // but we are not including call signatures that may have been added to the Object or
58581             // Function interface, since they have none by default. This is a bit of a leap of faith
58582             // that the user will not add any.
58583             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58584             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58585             // TS 1.0 Spec: 4.12
58586             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
58587             // types are provided for the argument expressions, and the result is always of type Any.
58588             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58589                 // The unknownType indicates that an error already occurred (and was reported).  No
58590                 // need to report another error in this case.
58591                 if (funcType !== errorType && node.typeArguments) {
58592                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58593                 }
58594                 return resolveUntypedCall(node);
58595             }
58596             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
58597             // TypeScript employs overload resolution in typed function calls in order to support functions
58598             // with multiple call signatures.
58599             if (!callSignatures.length) {
58600                 if (numConstructSignatures) {
58601                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58602                 }
58603                 else {
58604                     var relatedInformation = void 0;
58605                     if (node.arguments.length === 1) {
58606                         var text = ts.getSourceFileOfNode(node).text;
58607                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
58608                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
58609                         }
58610                     }
58611                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
58612                 }
58613                 return resolveErrorCall(node);
58614             }
58615             // When a call to a generic function is an argument to an outer call to a generic function for which
58616             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
58617             // its contextual type to its return type, deferring the inner call processing allows the best possible
58618             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
58619             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
58620             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
58621             // If no type arguments are specified in the inner call and at least one call signature is generic and
58622             // returns a function type, we choose to defer processing. This narrowly permits function composition
58623             // operators to flow inferences through return types, but otherwise processes calls right away. We
58624             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
58625             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
58626             // from which we never make inferences).
58627             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
58628                 skippedGenericFunction(node, checkMode);
58629                 return resolvingSignature;
58630             }
58631             // If the function is explicitly marked with `@class`, then it must be constructed.
58632             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
58633                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58634                 return resolveErrorCall(node);
58635             }
58636             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
58637         }
58638         function isGenericFunctionReturningFunction(signature) {
58639             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
58640         }
58641         /**
58642          * TS 1.0 spec: 4.12
58643          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
58644          * but is a subtype of the Function interface, the call is an untyped function call.
58645          */
58646         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
58647             // We exclude union types because we may have a union of function types that happen to have no common signatures.
58648             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
58649                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
58650         }
58651         function resolveNewExpression(node, candidatesOutArray, checkMode) {
58652             if (node.arguments && languageVersion < 1 /* ES5 */) {
58653                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
58654                 if (spreadIndex >= 0) {
58655                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
58656                 }
58657             }
58658             var expressionType = checkNonNullExpression(node.expression);
58659             if (expressionType === silentNeverType) {
58660                 return silentNeverSignature;
58661             }
58662             // If expressionType's apparent type(section 3.8.1) is an object type with one or
58663             // more construct signatures, the expression is processed in the same manner as a
58664             // function call, but using the construct signatures as the initial set of candidate
58665             // signatures for overload resolution. The result type of the function call becomes
58666             // the result type of the operation.
58667             expressionType = getApparentType(expressionType);
58668             if (expressionType === errorType) {
58669                 // Another error has already been reported
58670                 return resolveErrorCall(node);
58671             }
58672             // TS 1.0 spec: 4.11
58673             // If expressionType is of type Any, Args can be any argument
58674             // list and the result of the operation is of type Any.
58675             if (isTypeAny(expressionType)) {
58676                 if (node.typeArguments) {
58677                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58678                 }
58679                 return resolveUntypedCall(node);
58680             }
58681             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58682             // but we are not including construct signatures that may have been added to the Object or
58683             // Function interface, since they have none by default. This is a bit of a leap of faith
58684             // that the user will not add any.
58685             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
58686             if (constructSignatures.length) {
58687                 if (!isConstructorAccessible(node, constructSignatures[0])) {
58688                     return resolveErrorCall(node);
58689                 }
58690                 // If the expression is a class of abstract type, then it cannot be instantiated.
58691                 // Note, only class declarations can be declared abstract.
58692                 // In the case of a merged class-module or class-interface declaration,
58693                 // only the class declaration node will have the Abstract flag set.
58694                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
58695                 if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
58696                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
58697                     return resolveErrorCall(node);
58698                 }
58699                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
58700             }
58701             // If expressionType's apparent type is an object type with no construct signatures but
58702             // one or more call signatures, the expression is processed as a function call. A compile-time
58703             // error occurs if the result of the function call is not Void. The type of the result of the
58704             // operation is Any. It is an error to have a Void this type.
58705             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
58706             if (callSignatures.length) {
58707                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58708                 if (!noImplicitAny) {
58709                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
58710                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
58711                     }
58712                     if (getThisTypeOfSignature(signature) === voidType) {
58713                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
58714                     }
58715                 }
58716                 return signature;
58717             }
58718             invocationError(node.expression, expressionType, 1 /* Construct */);
58719             return resolveErrorCall(node);
58720         }
58721         function typeHasProtectedAccessibleBase(target, type) {
58722             var baseTypes = getBaseTypes(type);
58723             if (!ts.length(baseTypes)) {
58724                 return false;
58725             }
58726             var firstBase = baseTypes[0];
58727             if (firstBase.flags & 2097152 /* Intersection */) {
58728                 var types = firstBase.types;
58729                 var mixinFlags = findMixins(types);
58730                 var i = 0;
58731                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
58732                     var intersectionMember = _a[_i];
58733                     // We want to ignore mixin ctors
58734                     if (!mixinFlags[i]) {
58735                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
58736                             if (intersectionMember.symbol === target) {
58737                                 return true;
58738                             }
58739                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
58740                                 return true;
58741                             }
58742                         }
58743                     }
58744                     i++;
58745                 }
58746                 return false;
58747             }
58748             if (firstBase.symbol === target) {
58749                 return true;
58750             }
58751             return typeHasProtectedAccessibleBase(target, firstBase);
58752         }
58753         function isConstructorAccessible(node, signature) {
58754             if (!signature || !signature.declaration) {
58755                 return true;
58756             }
58757             var declaration = signature.declaration;
58758             var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
58759             // (1) Public constructors and (2) constructor functions are always accessible.
58760             if (!modifiers || declaration.kind !== 162 /* Constructor */) {
58761                 return true;
58762             }
58763             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
58764             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
58765             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
58766             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
58767                 var containingClass = ts.getContainingClass(node);
58768                 if (containingClass && modifiers & 16 /* Protected */) {
58769                     var containingType = getTypeOfNode(containingClass);
58770                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
58771                         return true;
58772                     }
58773                 }
58774                 if (modifiers & 8 /* Private */) {
58775                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58776                 }
58777                 if (modifiers & 16 /* Protected */) {
58778                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58779                 }
58780                 return false;
58781             }
58782             return true;
58783         }
58784         function invocationErrorDetails(apparentType, kind) {
58785             var errorInfo;
58786             var isCall = kind === 0 /* Call */;
58787             var awaitedType = getAwaitedType(apparentType);
58788             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
58789             if (apparentType.flags & 1048576 /* Union */) {
58790                 var types = apparentType.types;
58791                 var hasSignatures = false;
58792                 for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
58793                     var constituent = types_18[_i];
58794                     var signatures = getSignaturesOfType(constituent, kind);
58795                     if (signatures.length !== 0) {
58796                         hasSignatures = true;
58797                         if (errorInfo) {
58798                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
58799                             break;
58800                         }
58801                     }
58802                     else {
58803                         // Error on the first non callable constituent only
58804                         if (!errorInfo) {
58805                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58806                                 ts.Diagnostics.Type_0_has_no_call_signatures :
58807                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
58808                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58809                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
58810                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
58811                         }
58812                         if (hasSignatures) {
58813                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
58814                             break;
58815                         }
58816                     }
58817                 }
58818                 if (!hasSignatures) {
58819                     errorInfo = ts.chainDiagnosticMessages(
58820                     /* detials */ undefined, isCall ?
58821                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
58822                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
58823                 }
58824                 if (!errorInfo) {
58825                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58826                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
58827                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
58828                 }
58829             }
58830             else {
58831                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58832                     ts.Diagnostics.Type_0_has_no_call_signatures :
58833                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
58834             }
58835             return {
58836                 messageChain: ts.chainDiagnosticMessages(errorInfo, isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable),
58837                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
58838             };
58839         }
58840         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
58841             var _a = invocationErrorDetails(apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
58842             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
58843             if (relatedInfo) {
58844                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
58845             }
58846             if (ts.isCallExpression(errorTarget.parent)) {
58847                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
58848                 diagnostic.start = start;
58849                 diagnostic.length = length_7;
58850             }
58851             diagnostics.add(diagnostic);
58852             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
58853         }
58854         function invocationErrorRecovery(apparentType, kind, diagnostic) {
58855             if (!apparentType.symbol) {
58856                 return;
58857             }
58858             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
58859             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
58860             //  An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site
58861             if (importNode && !ts.isImportCall(importNode)) {
58862                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
58863                 if (!sigs || !sigs.length)
58864                     return;
58865                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.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));
58866             }
58867         }
58868         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
58869             var tagType = checkExpression(node.tag);
58870             var apparentType = getApparentType(tagType);
58871             if (apparentType === errorType) {
58872                 // Another error has already been reported
58873                 return resolveErrorCall(node);
58874             }
58875             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58876             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58877             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
58878                 return resolveUntypedCall(node);
58879             }
58880             if (!callSignatures.length) {
58881                 invocationError(node.tag, apparentType, 0 /* Call */);
58882                 return resolveErrorCall(node);
58883             }
58884             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58885         }
58886         /**
58887          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
58888          */
58889         function getDiagnosticHeadMessageForDecoratorResolution(node) {
58890             switch (node.parent.kind) {
58891                 case 245 /* ClassDeclaration */:
58892                 case 214 /* ClassExpression */:
58893                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
58894                 case 156 /* Parameter */:
58895                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
58896                 case 159 /* PropertyDeclaration */:
58897                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
58898                 case 161 /* MethodDeclaration */:
58899                 case 163 /* GetAccessor */:
58900                 case 164 /* SetAccessor */:
58901                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
58902                 default:
58903                     return ts.Debug.fail();
58904             }
58905         }
58906         /**
58907          * Resolves a decorator as if it were a call expression.
58908          */
58909         function resolveDecorator(node, candidatesOutArray, checkMode) {
58910             var funcType = checkExpression(node.expression);
58911             var apparentType = getApparentType(funcType);
58912             if (apparentType === errorType) {
58913                 return resolveErrorCall(node);
58914             }
58915             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58916             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58917             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58918                 return resolveUntypedCall(node);
58919             }
58920             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
58921                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
58922                 error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr);
58923                 return resolveErrorCall(node);
58924             }
58925             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
58926             if (!callSignatures.length) {
58927                 var errorDetails = invocationErrorDetails(apparentType, 0 /* Call */);
58928                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
58929                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
58930                 if (errorDetails.relatedMessage) {
58931                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
58932                 }
58933                 diagnostics.add(diag);
58934                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
58935                 return resolveErrorCall(node);
58936             }
58937             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
58938         }
58939         function createSignatureForJSXIntrinsic(node, result) {
58940             var namespace = getJsxNamespaceAt(node);
58941             var exports = namespace && getExportsOfSymbol(namespace);
58942             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
58943             // file would probably be preferable.
58944             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
58945             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
58946             var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(125 /* AnyKeyword */));
58947             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
58948             parameterSymbol.type = result;
58949             return createSignature(declaration, 
58950             /*typeParameters*/ undefined, 
58951             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
58952             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
58953         }
58954         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
58955             if (isJsxIntrinsicIdentifier(node.tagName)) {
58956                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
58957                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
58958                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
58959                 return fakeSignature;
58960             }
58961             var exprTypes = checkExpression(node.tagName);
58962             var apparentType = getApparentType(exprTypes);
58963             if (apparentType === errorType) {
58964                 return resolveErrorCall(node);
58965             }
58966             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
58967             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
58968                 return resolveUntypedCall(node);
58969             }
58970             if (signatures.length === 0) {
58971                 // We found no signatures at all, which is an error
58972                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
58973                 return resolveErrorCall(node);
58974             }
58975             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
58976         }
58977         /**
58978          * Sometimes, we have a decorator that could accept zero arguments,
58979          * but is receiving too many arguments as part of the decorator invocation.
58980          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
58981          */
58982         function isPotentiallyUncalledDecorator(decorator, signatures) {
58983             return signatures.length && ts.every(signatures, function (signature) {
58984                 return signature.minArgumentCount === 0 &&
58985                     !signatureHasRestParameter(signature) &&
58986                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
58987             });
58988         }
58989         function resolveSignature(node, candidatesOutArray, checkMode) {
58990             switch (node.kind) {
58991                 case 196 /* CallExpression */:
58992                     return resolveCallExpression(node, candidatesOutArray, checkMode);
58993                 case 197 /* NewExpression */:
58994                     return resolveNewExpression(node, candidatesOutArray, checkMode);
58995                 case 198 /* TaggedTemplateExpression */:
58996                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
58997                 case 157 /* Decorator */:
58998                     return resolveDecorator(node, candidatesOutArray, checkMode);
58999                 case 268 /* JsxOpeningElement */:
59000                 case 267 /* JsxSelfClosingElement */:
59001                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
59002             }
59003             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
59004         }
59005         /**
59006          * Resolve a signature of a given call-like expression.
59007          * @param node a call-like expression to try resolve a signature for
59008          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
59009          *                           the function will fill it up with appropriate candidate signatures
59010          * @return a signature of the call-like expression or undefined if one can't be found
59011          */
59012         function getResolvedSignature(node, candidatesOutArray, checkMode) {
59013             var links = getNodeLinks(node);
59014             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
59015             // However, it is possible that either candidatesOutArray was not passed in the first time,
59016             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
59017             // to correctly fill the candidatesOutArray.
59018             var cached = links.resolvedSignature;
59019             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
59020                 return cached;
59021             }
59022             links.resolvedSignature = resolvingSignature;
59023             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
59024             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
59025             // resolution should be deferred.
59026             if (result !== resolvingSignature) {
59027                 // If signature resolution originated in control flow type analysis (for example to compute the
59028                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
59029                 // types from the control flow analysis.
59030                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
59031             }
59032             return result;
59033         }
59034         /**
59035          * Indicates whether a declaration can be treated as a constructor in a JavaScript
59036          * file.
59037          */
59038         function isJSConstructor(node) {
59039             if (!node || !ts.isInJSFile(node)) {
59040                 return false;
59041             }
59042             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
59043                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
59044                     undefined;
59045             if (func) {
59046                 // If the node has a @class tag, treat it like a constructor.
59047                 if (ts.getJSDocClassTag(node))
59048                     return true;
59049                 // If the symbol of the node has members, treat it like a constructor.
59050                 var symbol = getSymbolOfNode(func);
59051                 return !!symbol && ts.hasEntries(symbol.members);
59052             }
59053             return false;
59054         }
59055         function mergeJSSymbols(target, source) {
59056             if (source) {
59057                 var links = getSymbolLinks(source);
59058                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) {
59059                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
59060                     inferred.exports = inferred.exports || ts.createSymbolTable();
59061                     inferred.members = inferred.members || ts.createSymbolTable();
59062                     inferred.flags |= source.flags & 32 /* Class */;
59063                     if (ts.hasEntries(source.exports)) {
59064                         mergeSymbolTable(inferred.exports, source.exports);
59065                     }
59066                     if (ts.hasEntries(source.members)) {
59067                         mergeSymbolTable(inferred.members, source.members);
59068                     }
59069                     (links.inferredClassSymbol || (links.inferredClassSymbol = ts.createMap())).set("" + getSymbolId(inferred), inferred);
59070                     return inferred;
59071                 }
59072                 return links.inferredClassSymbol.get("" + getSymbolId(target));
59073             }
59074         }
59075         function getAssignedClassSymbol(decl) {
59076             var assignmentSymbol = decl && decl.parent &&
59077                 (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
59078                     ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
59079                     ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
59080             var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
59081             var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
59082             return init ? getSymbolOfNode(init) : undefined;
59083         }
59084         function getAssignedJSPrototype(node) {
59085             if (!node.parent) {
59086                 return false;
59087             }
59088             var parent = node.parent;
59089             while (parent && parent.kind === 194 /* PropertyAccessExpression */) {
59090                 parent = parent.parent;
59091             }
59092             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
59093                 var right = ts.getInitializerOfBinaryExpression(parent);
59094                 return ts.isObjectLiteralExpression(right) && right;
59095             }
59096         }
59097         /**
59098          * Syntactically and semantically checks a call or new expression.
59099          * @param node The call/new expression to be checked.
59100          * @returns On success, the expression's signature's return type. On failure, anyType.
59101          */
59102         function checkCallExpression(node, checkMode) {
59103             if (!checkGrammarTypeArguments(node, node.typeArguments))
59104                 checkGrammarArguments(node.arguments);
59105             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
59106             if (signature === resolvingSignature) {
59107                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
59108                 // returns a function type. We defer checking and return nonInferrableType.
59109                 return nonInferrableType;
59110             }
59111             if (node.expression.kind === 102 /* SuperKeyword */) {
59112                 return voidType;
59113             }
59114             if (node.kind === 197 /* NewExpression */) {
59115                 var declaration = signature.declaration;
59116                 if (declaration &&
59117                     declaration.kind !== 162 /* Constructor */ &&
59118                     declaration.kind !== 166 /* ConstructSignature */ &&
59119                     declaration.kind !== 171 /* ConstructorType */ &&
59120                     !ts.isJSDocConstructSignature(declaration) &&
59121                     !isJSConstructor(declaration)) {
59122                     // When resolved signature is a call signature (and not a construct signature) the result type is any
59123                     if (noImplicitAny) {
59124                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
59125                     }
59126                     return anyType;
59127                 }
59128             }
59129             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
59130             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
59131                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
59132             }
59133             var returnType = getReturnTypeOfSignature(signature);
59134             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
59135             // as a fresh unique symbol literal type.
59136             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
59137                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
59138             }
59139             if (node.kind === 196 /* CallExpression */ && node.parent.kind === 226 /* ExpressionStatement */ &&
59140                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
59141                 if (!ts.isDottedName(node.expression)) {
59142                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
59143                 }
59144                 else if (!getEffectsSignature(node)) {
59145                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
59146                     getTypeOfDottedName(node.expression, diagnostic);
59147                 }
59148             }
59149             if (ts.isInJSFile(node)) {
59150                 var decl = ts.getDeclarationOfExpando(node);
59151                 if (decl) {
59152                     var jsSymbol = getSymbolOfNode(decl);
59153                     if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
59154                         var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
59155                         jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
59156                         return getIntersectionType([returnType, jsAssignmentType]);
59157                     }
59158                 }
59159             }
59160             return returnType;
59161         }
59162         function isSymbolOrSymbolForCall(node) {
59163             if (!ts.isCallExpression(node))
59164                 return false;
59165             var left = node.expression;
59166             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
59167                 left = left.expression;
59168             }
59169             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
59170                 return false;
59171             }
59172             // make sure `Symbol` is the global symbol
59173             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
59174             if (!globalESSymbol) {
59175                 return false;
59176             }
59177             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
59178         }
59179         function checkImportCallExpression(node) {
59180             // Check grammar of dynamic import
59181             if (!checkGrammarArguments(node.arguments))
59182                 checkGrammarImportCallExpression(node);
59183             if (node.arguments.length === 0) {
59184                 return createPromiseReturnType(node, anyType);
59185             }
59186             var specifier = node.arguments[0];
59187             var specifierType = checkExpressionCached(specifier);
59188             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
59189             for (var i = 1; i < node.arguments.length; ++i) {
59190                 checkExpressionCached(node.arguments[i]);
59191             }
59192             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
59193                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
59194             }
59195             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
59196             var moduleSymbol = resolveExternalModuleName(node, specifier);
59197             if (moduleSymbol) {
59198                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
59199                 if (esModuleSymbol) {
59200                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
59201                 }
59202             }
59203             return createPromiseReturnType(node, anyType);
59204         }
59205         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
59206             if (allowSyntheticDefaultImports && type && type !== errorType) {
59207                 var synthType = type;
59208                 if (!synthType.syntheticType) {
59209                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
59210                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
59211                     if (hasSyntheticDefault) {
59212                         var memberTable = ts.createSymbolTable();
59213                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
59214                         newSymbol.nameType = getLiteralType("default");
59215                         newSymbol.target = resolveSymbol(symbol);
59216                         memberTable.set("default" /* Default */, newSymbol);
59217                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
59218                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
59219                         anonymousSymbol.type = defaultContainingObject;
59220                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
59221                     }
59222                     else {
59223                         synthType.syntheticType = type;
59224                     }
59225                 }
59226                 return synthType.syntheticType;
59227             }
59228             return type;
59229         }
59230         function isCommonJsRequire(node) {
59231             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
59232                 return false;
59233             }
59234             // Make sure require is not a local function
59235             if (!ts.isIdentifier(node.expression))
59236                 return ts.Debug.fail();
59237             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
59238             if (resolvedRequire === requireSymbol) {
59239                 return true;
59240             }
59241             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
59242             if (resolvedRequire.flags & 2097152 /* Alias */) {
59243                 return false;
59244             }
59245             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
59246                 ? 244 /* FunctionDeclaration */
59247                 : resolvedRequire.flags & 3 /* Variable */
59248                     ? 242 /* VariableDeclaration */
59249                     : 0 /* Unknown */;
59250             if (targetDeclarationKind !== 0 /* Unknown */) {
59251                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
59252                 // function/variable declaration should be ambient
59253                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
59254             }
59255             return false;
59256         }
59257         function checkTaggedTemplateExpression(node) {
59258             if (!checkGrammarTaggedTemplateChain(node))
59259                 checkGrammarTypeArguments(node, node.typeArguments);
59260             if (languageVersion < 2 /* ES2015 */) {
59261                 checkExternalEmitHelpers(node, 131072 /* MakeTemplateObject */);
59262             }
59263             return getReturnTypeOfSignature(getResolvedSignature(node));
59264         }
59265         function checkAssertion(node) {
59266             return checkAssertionWorker(node, node.type, node.expression);
59267         }
59268         function isValidConstAssertionArgument(node) {
59269             switch (node.kind) {
59270                 case 10 /* StringLiteral */:
59271                 case 14 /* NoSubstitutionTemplateLiteral */:
59272                 case 8 /* NumericLiteral */:
59273                 case 9 /* BigIntLiteral */:
59274                 case 106 /* TrueKeyword */:
59275                 case 91 /* FalseKeyword */:
59276                 case 192 /* ArrayLiteralExpression */:
59277                 case 193 /* ObjectLiteralExpression */:
59278                     return true;
59279                 case 200 /* ParenthesizedExpression */:
59280                     return isValidConstAssertionArgument(node.expression);
59281                 case 207 /* PrefixUnaryExpression */:
59282                     var op = node.operator;
59283                     var arg = node.operand;
59284                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
59285                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
59286                 case 194 /* PropertyAccessExpression */:
59287                 case 195 /* ElementAccessExpression */:
59288                     var expr = node.expression;
59289                     if (ts.isIdentifier(expr)) {
59290                         var symbol = getSymbolAtLocation(expr);
59291                         if (symbol && symbol.flags & 2097152 /* Alias */) {
59292                             symbol = resolveAlias(symbol);
59293                         }
59294                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
59295                     }
59296             }
59297             return false;
59298         }
59299         function checkAssertionWorker(errNode, type, expression, checkMode) {
59300             var exprType = checkExpression(expression, checkMode);
59301             if (ts.isConstTypeReference(type)) {
59302                 if (!isValidConstAssertionArgument(expression)) {
59303                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
59304                 }
59305                 return getRegularTypeOfLiteralType(exprType);
59306             }
59307             checkSourceElement(type);
59308             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
59309             var targetType = getTypeFromTypeNode(type);
59310             if (produceDiagnostics && targetType !== errorType) {
59311                 var widenedType = getWidenedType(exprType);
59312                 if (!isTypeComparableTo(targetType, widenedType)) {
59313                     checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first);
59314                 }
59315             }
59316             return targetType;
59317         }
59318         function checkNonNullChain(node) {
59319             var leftType = checkExpression(node.expression);
59320             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
59321             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
59322         }
59323         function checkNonNullAssertion(node) {
59324             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
59325                 getNonNullableType(checkExpression(node.expression));
59326         }
59327         function checkMetaProperty(node) {
59328             checkGrammarMetaProperty(node);
59329             if (node.keywordToken === 99 /* NewKeyword */) {
59330                 return checkNewTargetMetaProperty(node);
59331             }
59332             if (node.keywordToken === 96 /* ImportKeyword */) {
59333                 return checkImportMetaProperty(node);
59334             }
59335             return ts.Debug.assertNever(node.keywordToken);
59336         }
59337         function checkNewTargetMetaProperty(node) {
59338             var container = ts.getNewTargetContainer(node);
59339             if (!container) {
59340                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
59341                 return errorType;
59342             }
59343             else if (container.kind === 162 /* Constructor */) {
59344                 var symbol = getSymbolOfNode(container.parent);
59345                 return getTypeOfSymbol(symbol);
59346             }
59347             else {
59348                 var symbol = getSymbolOfNode(container);
59349                 return getTypeOfSymbol(symbol);
59350             }
59351         }
59352         function checkImportMetaProperty(node) {
59353             if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
59354                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system);
59355             }
59356             var file = ts.getSourceFileOfNode(node);
59357             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
59358             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
59359             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
59360         }
59361         function getTypeOfParameter(symbol) {
59362             var type = getTypeOfSymbol(symbol);
59363             if (strictNullChecks) {
59364                 var declaration = symbol.valueDeclaration;
59365                 if (declaration && ts.hasInitializer(declaration)) {
59366                     return getOptionalType(type);
59367                 }
59368             }
59369             return type;
59370         }
59371         function getParameterNameAtPosition(signature, pos) {
59372             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59373             if (pos < paramCount) {
59374                 return signature.parameters[pos].escapedName;
59375             }
59376             var restParameter = signature.parameters[paramCount] || unknownSymbol;
59377             var restType = getTypeOfSymbol(restParameter);
59378             if (isTupleType(restType)) {
59379                 var associatedNames = restType.target.associatedNames;
59380                 var index = pos - paramCount;
59381                 return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
59382             }
59383             return restParameter.escapedName;
59384         }
59385         function getTypeAtPosition(signature, pos) {
59386             return tryGetTypeAtPosition(signature, pos) || anyType;
59387         }
59388         function tryGetTypeAtPosition(signature, pos) {
59389             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59390             if (pos < paramCount) {
59391                 return getTypeOfParameter(signature.parameters[pos]);
59392             }
59393             if (signatureHasRestParameter(signature)) {
59394                 // We want to return the value undefined for an out of bounds parameter position,
59395                 // so we need to check bounds here before calling getIndexedAccessType (which
59396                 // otherwise would return the type 'undefined').
59397                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
59398                 var index = pos - paramCount;
59399                 if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) {
59400                     return getIndexedAccessType(restType, getLiteralType(index));
59401                 }
59402             }
59403             return undefined;
59404         }
59405         function getRestTypeAtPosition(source, pos) {
59406             var paramCount = getParameterCount(source);
59407             var restType = getEffectiveRestType(source);
59408             var nonRestCount = paramCount - (restType ? 1 : 0);
59409             if (restType && pos === nonRestCount) {
59410                 return restType;
59411             }
59412             var types = [];
59413             var names = [];
59414             for (var i = pos; i < nonRestCount; i++) {
59415                 types.push(getTypeAtPosition(source, i));
59416                 names.push(getParameterNameAtPosition(source, i));
59417             }
59418             if (restType) {
59419                 types.push(getIndexedAccessType(restType, numberType));
59420                 names.push(getParameterNameAtPosition(source, nonRestCount));
59421             }
59422             var minArgumentCount = getMinArgumentCount(source);
59423             var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
59424             return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
59425         }
59426         function getParameterCount(signature) {
59427             var length = signature.parameters.length;
59428             if (signatureHasRestParameter(signature)) {
59429                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
59430                 if (isTupleType(restType)) {
59431                     return length + getTypeArguments(restType).length - 1;
59432                 }
59433             }
59434             return length;
59435         }
59436         function getMinArgumentCount(signature, strongArityForUntypedJS) {
59437             if (signatureHasRestParameter(signature)) {
59438                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59439                 if (isTupleType(restType)) {
59440                     var minLength = restType.target.minLength;
59441                     if (minLength > 0) {
59442                         return signature.parameters.length - 1 + minLength;
59443                     }
59444                 }
59445             }
59446             if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
59447                 return 0;
59448             }
59449             return signature.minArgumentCount;
59450         }
59451         function hasEffectiveRestParameter(signature) {
59452             if (signatureHasRestParameter(signature)) {
59453                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59454                 return !isTupleType(restType) || restType.target.hasRestElement;
59455             }
59456             return false;
59457         }
59458         function getEffectiveRestType(signature) {
59459             if (signatureHasRestParameter(signature)) {
59460                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59461                 return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
59462             }
59463             return undefined;
59464         }
59465         function getNonArrayRestType(signature) {
59466             var restType = getEffectiveRestType(signature);
59467             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
59468         }
59469         function getTypeOfFirstParameterOfSignature(signature) {
59470             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
59471         }
59472         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
59473             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
59474         }
59475         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
59476             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59477             for (var i = 0; i < len; i++) {
59478                 var declaration = signature.parameters[i].valueDeclaration;
59479                 if (declaration.type) {
59480                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
59481                     if (typeNode) {
59482                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
59483                     }
59484                 }
59485             }
59486             var restType = getEffectiveRestType(context);
59487             if (restType && restType.flags & 262144 /* TypeParameter */) {
59488                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
59489                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
59490                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
59491                 assignContextualParameterTypes(signature, instantiatedContext);
59492                 // We then infer from a tuple type representing the parameters that correspond to the contextual
59493                 // rest parameter.
59494                 var restPos = getParameterCount(context) - 1;
59495                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
59496             }
59497         }
59498         function assignContextualParameterTypes(signature, context) {
59499             signature.typeParameters = context.typeParameters;
59500             if (context.thisParameter) {
59501                 var parameter = signature.thisParameter;
59502                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
59503                     if (!parameter) {
59504                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
59505                     }
59506                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
59507                 }
59508             }
59509             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59510             for (var i = 0; i < len; i++) {
59511                 var parameter = signature.parameters[i];
59512                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59513                     var contextualParameterType = tryGetTypeAtPosition(context, i);
59514                     assignParameterType(parameter, contextualParameterType);
59515                 }
59516             }
59517             if (signatureHasRestParameter(signature)) {
59518                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
59519                 var parameter = ts.last(signature.parameters);
59520                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59521                     var contextualParameterType = getRestTypeAtPosition(context, len);
59522                     assignParameterType(parameter, contextualParameterType);
59523                 }
59524             }
59525         }
59526         function assignNonContextualParameterTypes(signature) {
59527             if (signature.thisParameter) {
59528                 assignParameterType(signature.thisParameter);
59529             }
59530             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
59531                 var parameter = _a[_i];
59532                 assignParameterType(parameter);
59533             }
59534         }
59535         function assignParameterType(parameter, type) {
59536             var links = getSymbolLinks(parameter);
59537             if (!links.type) {
59538                 var declaration = parameter.valueDeclaration;
59539                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
59540                 if (declaration.name.kind !== 75 /* Identifier */) {
59541                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
59542                     if (links.type === unknownType) {
59543                         links.type = getTypeFromBindingPattern(declaration.name);
59544                     }
59545                     assignBindingElementTypes(declaration.name);
59546                 }
59547             }
59548         }
59549         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
59550         // the destructured type into the contained binding elements.
59551         function assignBindingElementTypes(pattern) {
59552             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
59553                 var element = _a[_i];
59554                 if (!ts.isOmittedExpression(element)) {
59555                     if (element.name.kind === 75 /* Identifier */) {
59556                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
59557                     }
59558                     else {
59559                         assignBindingElementTypes(element.name);
59560                     }
59561                 }
59562             }
59563         }
59564         function createPromiseType(promisedType) {
59565             // creates a `Promise<T>` type where `T` is the promisedType argument
59566             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
59567             if (globalPromiseType !== emptyGenericType) {
59568                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59569                 promisedType = getAwaitedType(promisedType) || unknownType;
59570                 return createTypeReference(globalPromiseType, [promisedType]);
59571             }
59572             return unknownType;
59573         }
59574         function createPromiseLikeType(promisedType) {
59575             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
59576             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
59577             if (globalPromiseLikeType !== emptyGenericType) {
59578                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59579                 promisedType = getAwaitedType(promisedType) || unknownType;
59580                 return createTypeReference(globalPromiseLikeType, [promisedType]);
59581             }
59582             return unknownType;
59583         }
59584         function createPromiseReturnType(func, promisedType) {
59585             var promiseType = createPromiseType(promisedType);
59586             if (promiseType === unknownType) {
59587                 error(func, ts.isImportCall(func) ?
59588                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
59589                     ts.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);
59590                 return errorType;
59591             }
59592             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
59593                 error(func, ts.isImportCall(func) ?
59594                     ts.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 :
59595                     ts.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);
59596             }
59597             return promiseType;
59598         }
59599         function getReturnTypeFromBody(func, checkMode) {
59600             if (!func.body) {
59601                 return errorType;
59602             }
59603             var functionFlags = ts.getFunctionFlags(func);
59604             var isAsync = (functionFlags & 2 /* Async */) !== 0;
59605             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
59606             var returnType;
59607             var yieldType;
59608             var nextType;
59609             var fallbackReturnType = voidType;
59610             if (func.body.kind !== 223 /* Block */) { // Async or normal arrow function
59611                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59612                 if (isAsync) {
59613                     // From within an async function you can return either a non-promise value or a promise. Any
59614                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59615                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
59616                     // the native Promise<T> type later in this function.
59617                     returnType = checkAwaitedType(returnType, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
59618                 }
59619             }
59620             else if (isGenerator) { // Generator or AsyncGenerator function
59621                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
59622                 if (!returnTypes) {
59623                     fallbackReturnType = neverType;
59624                 }
59625                 else if (returnTypes.length > 0) {
59626                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
59627                 }
59628                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
59629                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
59630                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
59631             }
59632             else { // Async or normal function
59633                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
59634                 if (!types) {
59635                     // For an async function, the return type will not be never, but rather a Promise for never.
59636                     return functionFlags & 2 /* Async */
59637                         ? createPromiseReturnType(func, neverType) // Async function
59638                         : neverType; // Normal function
59639                 }
59640                 if (types.length === 0) {
59641                     // For an async function, the return type will not be void, but rather a Promise for void.
59642                     return functionFlags & 2 /* Async */
59643                         ? createPromiseReturnType(func, voidType) // Async function
59644                         : voidType; // Normal function
59645                 }
59646                 // Return a union of the return expression types.
59647                 returnType = getUnionType(types, 2 /* Subtype */);
59648             }
59649             if (returnType || yieldType || nextType) {
59650                 if (yieldType)
59651                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
59652                 if (returnType)
59653                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
59654                 if (nextType)
59655                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
59656                 if (returnType && isUnitType(returnType) ||
59657                     yieldType && isUnitType(yieldType) ||
59658                     nextType && isUnitType(nextType)) {
59659                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
59660                     var contextualType = !contextualSignature ? undefined :
59661                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
59662                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
59663                     if (isGenerator) {
59664                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
59665                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
59666                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
59667                     }
59668                     else {
59669                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
59670                     }
59671                 }
59672                 if (yieldType)
59673                     yieldType = getWidenedType(yieldType);
59674                 if (returnType)
59675                     returnType = getWidenedType(returnType);
59676                 if (nextType)
59677                     nextType = getWidenedType(nextType);
59678             }
59679             if (isGenerator) {
59680                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
59681             }
59682             else {
59683                 // From within an async function you can return either a non-promise value or a promise. Any
59684                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59685                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
59686                 return isAsync
59687                     ? createPromiseType(returnType || fallbackReturnType)
59688                     : returnType || fallbackReturnType;
59689             }
59690         }
59691         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
59692             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
59693             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
59694             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
59695             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
59696             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
59697             if (globalGeneratorType === emptyGenericType) {
59698                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
59699                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
59700                 // nextType.
59701                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
59702                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
59703                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
59704                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
59705                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
59706                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
59707                     if (globalType !== emptyGenericType) {
59708                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
59709                     }
59710                     // The global IterableIterator type doesn't exist, so report an error
59711                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
59712                     return emptyObjectType;
59713                 }
59714                 // The global Generator type doesn't exist, so report an error
59715                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
59716                 return emptyObjectType;
59717             }
59718             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
59719         }
59720         function checkAndAggregateYieldOperandTypes(func, checkMode) {
59721             var yieldTypes = [];
59722             var nextTypes = [];
59723             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
59724             ts.forEachYieldExpression(func.body, function (yieldExpression) {
59725                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
59726                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
59727                 var nextType;
59728                 if (yieldExpression.asteriskToken) {
59729                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
59730                     nextType = iterationTypes && iterationTypes.nextType;
59731                 }
59732                 else {
59733                     nextType = getContextualType(yieldExpression);
59734                 }
59735                 if (nextType)
59736                     ts.pushIfUnique(nextTypes, nextType);
59737             });
59738             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
59739         }
59740         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
59741             var errorNode = node.expression || node;
59742             // A `yield*` expression effectively yields everything that its operand yields
59743             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
59744             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
59745                 ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
59746                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
59747         }
59748         /**
59749          * Collect the TypeFacts learned from a typeof switch with
59750          * total clauses `witnesses`, and the active clause ranging
59751          * from `start` to `end`. Parameter `hasDefault` denotes
59752          * whether the active clause contains a default clause.
59753          */
59754         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
59755             var facts = 0 /* None */;
59756             // When in the default we only collect inequality facts
59757             // because default is 'in theory' a set of infinite
59758             // equalities.
59759             if (hasDefault) {
59760                 // Value is not equal to any types after the active clause.
59761                 for (var i = end; i < witnesses.length; i++) {
59762                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59763                 }
59764                 // Remove inequalities for types that appear in the
59765                 // active clause because they appear before other
59766                 // types collected so far.
59767                 for (var i = start; i < end; i++) {
59768                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
59769                 }
59770                 // Add inequalities for types before the active clause unconditionally.
59771                 for (var i = 0; i < start; i++) {
59772                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59773                 }
59774             }
59775             // When in an active clause without default the set of
59776             // equalities is finite.
59777             else {
59778                 // Add equalities for all types in the active clause.
59779                 for (var i = start; i < end; i++) {
59780                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
59781                 }
59782                 // Remove equalities for types that appear before the
59783                 // active clause.
59784                 for (var i = 0; i < start; i++) {
59785                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
59786                 }
59787             }
59788             return facts;
59789         }
59790         function isExhaustiveSwitchStatement(node) {
59791             var links = getNodeLinks(node);
59792             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
59793         }
59794         function computeExhaustiveSwitchStatement(node) {
59795             if (node.expression.kind === 204 /* TypeOfExpression */) {
59796                 var operandType = getTypeOfExpression(node.expression.expression);
59797                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
59798                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
59799                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
59800                 var type_3 = getBaseConstraintOfType(operandType) || operandType;
59801                 return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
59802             }
59803             var type = getTypeOfExpression(node.expression);
59804             if (!isLiteralType(type)) {
59805                 return false;
59806             }
59807             var switchTypes = getSwitchClauseTypes(node);
59808             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
59809                 return false;
59810             }
59811             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
59812         }
59813         function functionHasImplicitReturn(func) {
59814             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
59815         }
59816         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
59817         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
59818             var functionFlags = ts.getFunctionFlags(func);
59819             var aggregatedTypes = [];
59820             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
59821             var hasReturnOfTypeNever = false;
59822             ts.forEachReturnStatement(func.body, function (returnStatement) {
59823                 var expr = returnStatement.expression;
59824                 if (expr) {
59825                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59826                     if (functionFlags & 2 /* Async */) {
59827                         // From within an async function you can return either a non-promise value or a promise. Any
59828                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59829                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
59830                         // the native Promise<T> type by the caller.
59831                         type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
59832                     }
59833                     if (type.flags & 131072 /* Never */) {
59834                         hasReturnOfTypeNever = true;
59835                     }
59836                     ts.pushIfUnique(aggregatedTypes, type);
59837                 }
59838                 else {
59839                     hasReturnWithNoExpression = true;
59840                 }
59841             });
59842             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
59843                 return undefined;
59844             }
59845             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
59846                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
59847                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
59848                 ts.pushIfUnique(aggregatedTypes, undefinedType);
59849             }
59850             return aggregatedTypes;
59851         }
59852         function mayReturnNever(func) {
59853             switch (func.kind) {
59854                 case 201 /* FunctionExpression */:
59855                 case 202 /* ArrowFunction */:
59856                     return true;
59857                 case 161 /* MethodDeclaration */:
59858                     return func.parent.kind === 193 /* ObjectLiteralExpression */;
59859                 default:
59860                     return false;
59861             }
59862         }
59863         /**
59864          * TypeScript Specification 1.0 (6.3) - July 2014
59865          *   An explicitly typed function whose return type isn't the Void type,
59866          *   the Any type, or a union type containing the Void or Any type as a constituent
59867          *   must have at least one return statement somewhere in its body.
59868          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
59869          *
59870          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
59871          */
59872         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
59873             if (!produceDiagnostics) {
59874                 return;
59875             }
59876             var functionFlags = ts.getFunctionFlags(func);
59877             var type = returnType && unwrapReturnType(returnType, functionFlags);
59878             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
59879             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
59880                 return;
59881             }
59882             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
59883             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
59884             if (func.kind === 160 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 223 /* Block */ || !functionHasImplicitReturn(func)) {
59885                 return;
59886             }
59887             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
59888             if (type && type.flags & 131072 /* Never */) {
59889                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
59890             }
59891             else if (type && !hasExplicitReturn) {
59892                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
59893                 // this function does not conform to the specification.
59894                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
59895                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
59896             }
59897             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
59898                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
59899             }
59900             else if (compilerOptions.noImplicitReturns) {
59901                 if (!type) {
59902                     // If return type annotation is omitted check if function has any explicit return statements.
59903                     // If it does not have any - its inferred return type is void - don't do any checks.
59904                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
59905                     if (!hasExplicitReturn) {
59906                         return;
59907                     }
59908                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
59909                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
59910                         return;
59911                     }
59912                 }
59913                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
59914             }
59915         }
59916         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59917             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59918             checkNodeDeferred(node);
59919             // The identityMapper object is used to indicate that function expressions are wildcards
59920             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
59921                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
59922                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
59923                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
59924                     var contextualSignature = getContextualSignature(node);
59925                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
59926                         var links = getNodeLinks(node);
59927                         if (links.contextFreeType) {
59928                             return links.contextFreeType;
59929                         }
59930                         var returnType = getReturnTypeFromBody(node, checkMode);
59931                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
59932                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
59933                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
59934                         return links.contextFreeType = returnOnlyType;
59935                     }
59936                 }
59937                 return anyFunctionType;
59938             }
59939             // Grammar checking
59940             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
59941             if (!hasGrammarError && node.kind === 201 /* FunctionExpression */) {
59942                 checkGrammarForGenerator(node);
59943             }
59944             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
59945             return getTypeOfSymbol(getSymbolOfNode(node));
59946         }
59947         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59948             var links = getNodeLinks(node);
59949             // Check if function expression is contextually typed and assign parameter types if so.
59950             if (!(links.flags & 1024 /* ContextChecked */)) {
59951                 var contextualSignature = getContextualSignature(node);
59952                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
59953                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
59954                 // already assigned contextual types.
59955                 if (!(links.flags & 1024 /* ContextChecked */)) {
59956                     links.flags |= 1024 /* ContextChecked */;
59957                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
59958                     if (!signature) {
59959                         return;
59960                     }
59961                     if (isContextSensitive(node)) {
59962                         if (contextualSignature) {
59963                             var inferenceContext = getInferenceContext(node);
59964                             if (checkMode && checkMode & 2 /* Inferential */) {
59965                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
59966                             }
59967                             var instantiatedContextualSignature = inferenceContext ?
59968                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
59969                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
59970                         }
59971                         else {
59972                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
59973                             assignNonContextualParameterTypes(signature);
59974                         }
59975                     }
59976                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
59977                         var returnType = getReturnTypeFromBody(node, checkMode);
59978                         if (!signature.resolvedReturnType) {
59979                             signature.resolvedReturnType = returnType;
59980                         }
59981                     }
59982                     checkSignatureDeclaration(node);
59983                 }
59984             }
59985         }
59986         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
59987             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59988             var functionFlags = ts.getFunctionFlags(node);
59989             var returnType = getReturnTypeFromAnnotation(node);
59990             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
59991             if (node.body) {
59992                 if (!ts.getEffectiveReturnTypeNode(node)) {
59993                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
59994                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
59995                     // of a function. Because checking of function expression bodies is deferred, there was never an
59996                     // appropriate time to do this during the main walk of the file (see the comment at the top of
59997                     // checkFunctionExpressionBodies). So it must be done now.
59998                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
59999                 }
60000                 if (node.body.kind === 223 /* Block */) {
60001                     checkSourceElement(node.body);
60002                 }
60003                 else {
60004                     // From within an async function you can return either a non-promise value or a promise. Any
60005                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
60006                     // should not be checking assignability of a promise to the return type. Instead, we need to
60007                     // check assignability of the awaited type of the expression body against the promised type of
60008                     // its return type annotation.
60009                     var exprType = checkExpression(node.body);
60010                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
60011                     if (returnOrPromisedType) {
60012                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
60013                             var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
60014                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
60015                         }
60016                         else { // Normal function
60017                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
60018                         }
60019                     }
60020                 }
60021             }
60022         }
60023         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
60024             if (isAwaitValid === void 0) { isAwaitValid = false; }
60025             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
60026                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
60027                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
60028                 return false;
60029             }
60030             return true;
60031         }
60032         function isReadonlyAssignmentDeclaration(d) {
60033             if (!ts.isCallExpression(d)) {
60034                 return false;
60035             }
60036             if (!ts.isBindableObjectDefinePropertyCall(d)) {
60037                 return false;
60038             }
60039             var objectLitType = checkExpressionCached(d.arguments[2]);
60040             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
60041             if (valueType) {
60042                 var writableProp = getPropertyOfType(objectLitType, "writable");
60043                 var writableType = writableProp && getTypeOfSymbol(writableProp);
60044                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
60045                     return true;
60046                 }
60047                 // We include this definition whereupon we walk back and check the type at the declaration because
60048                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
60049                 // argument types, should the type be contextualized by the call itself.
60050                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
60051                     var initializer = writableProp.valueDeclaration.initializer;
60052                     var rawOriginalType = checkExpression(initializer);
60053                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
60054                         return true;
60055                     }
60056                 }
60057                 return false;
60058             }
60059             var setProp = getPropertyOfType(objectLitType, "set");
60060             return !setProp;
60061         }
60062         function isReadonlySymbol(symbol) {
60063             // The following symbols are considered read-only:
60064             // Properties with a 'readonly' modifier
60065             // Variables declared with 'const'
60066             // Get accessors without matching set accessors
60067             // Enum members
60068             // Object.defineProperty assignments with writable false or no setter
60069             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
60070             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
60071                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
60072                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
60073                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
60074                 symbol.flags & 8 /* EnumMember */ ||
60075                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
60076         }
60077         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
60078             var _a, _b;
60079             if (assignmentKind === 0 /* None */) {
60080                 // no assigment means it doesn't matter whether the entity is readonly
60081                 return false;
60082             }
60083             if (isReadonlySymbol(symbol)) {
60084                 // Allow assignments to readonly properties within constructors of the same class declaration.
60085                 if (symbol.flags & 4 /* Property */ &&
60086                     ts.isAccessExpression(expr) &&
60087                     expr.expression.kind === 104 /* ThisKeyword */) {
60088                     // Look for if this is the constructor for the class that `symbol` is a property of.
60089                     var ctor = ts.getContainingFunction(expr);
60090                     if (!(ctor && ctor.kind === 162 /* Constructor */)) {
60091                         return true;
60092                     }
60093                     if (symbol.valueDeclaration) {
60094                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
60095                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
60096                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
60097                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
60098                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
60099                         var isWriteableSymbol = isLocalPropertyDeclaration
60100                             || isLocalParameterProperty
60101                             || isLocalThisPropertyAssignment
60102                             || isLocalThisPropertyAssignmentConstructorFunction;
60103                         return !isWriteableSymbol;
60104                     }
60105                 }
60106                 return true;
60107             }
60108             if (ts.isAccessExpression(expr)) {
60109                 // references through namespace import should be readonly
60110                 var node = ts.skipParentheses(expr.expression);
60111                 if (node.kind === 75 /* Identifier */) {
60112                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
60113                     if (symbol_2.flags & 2097152 /* Alias */) {
60114                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
60115                         return !!declaration && declaration.kind === 256 /* NamespaceImport */;
60116                     }
60117                 }
60118             }
60119             return false;
60120         }
60121         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
60122             // References are combinations of identifiers, parentheses, and property accesses.
60123             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
60124             if (node.kind !== 75 /* Identifier */ && !ts.isAccessExpression(node)) {
60125                 error(expr, invalidReferenceMessage);
60126                 return false;
60127             }
60128             if (node.flags & 32 /* OptionalChain */) {
60129                 error(expr, invalidOptionalChainMessage);
60130                 return false;
60131             }
60132             return true;
60133         }
60134         function checkDeleteExpression(node) {
60135             checkExpression(node.expression);
60136             var expr = ts.skipParentheses(node.expression);
60137             if (!ts.isAccessExpression(expr)) {
60138                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
60139                 return booleanType;
60140             }
60141             // eslint-disable-next-line
60142             if (expr.kind === 194 /* PropertyAccessExpression */ && ts.isPrivateIdentifier(expr.name)) {
60143                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
60144             }
60145             var links = getNodeLinks(expr);
60146             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
60147             if (symbol && isReadonlySymbol(symbol)) {
60148                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
60149             }
60150             return booleanType;
60151         }
60152         function checkTypeOfExpression(node) {
60153             checkExpression(node.expression);
60154             return typeofType;
60155         }
60156         function checkVoidExpression(node) {
60157             checkExpression(node.expression);
60158             return undefinedWideningType;
60159         }
60160         function isTopLevelAwait(node) {
60161             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ true);
60162             return ts.isSourceFile(container);
60163         }
60164         function checkAwaitExpression(node) {
60165             // Grammar checking
60166             if (produceDiagnostics) {
60167                 if (!(node.flags & 32768 /* AwaitContext */)) {
60168                     if (isTopLevelAwait(node)) {
60169                         var sourceFile = ts.getSourceFileOfNode(node);
60170                         if (!hasParseDiagnostics(sourceFile)) {
60171                             var span = void 0;
60172                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
60173                                 if (!span)
60174                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60175                                 var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module);
60176                                 diagnostics.add(diagnostic);
60177                             }
60178                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
60179                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60180                                 var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher);
60181                                 diagnostics.add(diagnostic);
60182                             }
60183                         }
60184                     }
60185                     else {
60186                         // use of 'await' in non-async function
60187                         var sourceFile = ts.getSourceFileOfNode(node);
60188                         if (!hasParseDiagnostics(sourceFile)) {
60189                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60190                             var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules);
60191                             var func = ts.getContainingFunction(node);
60192                             if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
60193                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
60194                                 ts.addRelatedInfo(diagnostic, relatedInfo);
60195                             }
60196                             diagnostics.add(diagnostic);
60197                         }
60198                     }
60199                 }
60200                 if (isInParameterInitializerBeforeContainingFunction(node)) {
60201                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
60202                 }
60203             }
60204             var operandType = checkExpression(node.expression);
60205             var awaitedType = checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
60206             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
60207                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
60208             }
60209             return awaitedType;
60210         }
60211         function checkPrefixUnaryExpression(node) {
60212             var operandType = checkExpression(node.operand);
60213             if (operandType === silentNeverType) {
60214                 return silentNeverType;
60215             }
60216             switch (node.operand.kind) {
60217                 case 8 /* NumericLiteral */:
60218                     switch (node.operator) {
60219                         case 40 /* MinusToken */:
60220                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
60221                         case 39 /* PlusToken */:
60222                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
60223                     }
60224                     break;
60225                 case 9 /* BigIntLiteral */:
60226                     if (node.operator === 40 /* MinusToken */) {
60227                         return getFreshTypeOfLiteralType(getLiteralType({
60228                             negative: true,
60229                             base10Value: ts.parsePseudoBigInt(node.operand.text)
60230                         }));
60231                     }
60232             }
60233             switch (node.operator) {
60234                 case 39 /* PlusToken */:
60235                 case 40 /* MinusToken */:
60236                 case 54 /* TildeToken */:
60237                     checkNonNullType(operandType, node.operand);
60238                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
60239                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
60240                     }
60241                     if (node.operator === 39 /* PlusToken */) {
60242                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60243                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
60244                         }
60245                         return numberType;
60246                     }
60247                     return getUnaryResultType(operandType);
60248                 case 53 /* ExclamationToken */:
60249                     checkTruthinessExpression(node.operand);
60250                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
60251                     return facts === 4194304 /* Truthy */ ? falseType :
60252                         facts === 8388608 /* Falsy */ ? trueType :
60253                             booleanType;
60254                 case 45 /* PlusPlusToken */:
60255                 case 46 /* MinusMinusToken */:
60256                     var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type);
60257                     if (ok) {
60258                         // run check only if former checks succeeded to avoid reporting cascading errors
60259                         checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access);
60260                     }
60261                     return getUnaryResultType(operandType);
60262             }
60263             return errorType;
60264         }
60265         function checkPostfixUnaryExpression(node) {
60266             var operandType = checkExpression(node.operand);
60267             if (operandType === silentNeverType) {
60268                 return silentNeverType;
60269             }
60270             var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type);
60271             if (ok) {
60272                 // run check only if former checks succeeded to avoid reporting cascading errors
60273                 checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access);
60274             }
60275             return getUnaryResultType(operandType);
60276         }
60277         function getUnaryResultType(operandType) {
60278             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60279                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
60280                     ? numberOrBigIntType
60281                     : bigintType;
60282             }
60283             // If it's not a bigint type, implicit coercion will result in a number
60284             return numberType;
60285         }
60286         // Return true if type might be of the given kind. A union or intersection type might be of a given
60287         // kind if at least one constituent type is of the given kind.
60288         function maybeTypeOfKind(type, kind) {
60289             if (type.flags & kind) {
60290                 return true;
60291             }
60292             if (type.flags & 3145728 /* UnionOrIntersection */) {
60293                 var types = type.types;
60294                 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
60295                     var t = types_19[_i];
60296                     if (maybeTypeOfKind(t, kind)) {
60297                         return true;
60298                     }
60299                 }
60300             }
60301             return false;
60302         }
60303         function isTypeAssignableToKind(source, kind, strict) {
60304             if (source.flags & kind) {
60305                 return true;
60306             }
60307             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
60308                 return false;
60309             }
60310             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
60311                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
60312                 !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
60313                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
60314                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
60315                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
60316                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
60317                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
60318                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
60319                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
60320         }
60321         function allTypesAssignableToKind(source, kind, strict) {
60322             return source.flags & 1048576 /* Union */ ?
60323                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
60324                 isTypeAssignableToKind(source, kind, strict);
60325         }
60326         function isConstEnumObjectType(type) {
60327             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
60328         }
60329         function isConstEnumSymbol(symbol) {
60330             return (symbol.flags & 128 /* ConstEnum */) !== 0;
60331         }
60332         function checkInstanceOfExpression(left, right, leftType, rightType) {
60333             if (leftType === silentNeverType || rightType === silentNeverType) {
60334                 return silentNeverType;
60335             }
60336             // TypeScript 1.0 spec (April 2014): 4.15.4
60337             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
60338             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
60339             // The result is always of the Boolean primitive type.
60340             // NOTE: do not raise error if leftType is unknown as related error was already reported
60341             if (!isTypeAny(leftType) &&
60342                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
60343                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60344             }
60345             // NOTE: do not raise error if right is unknown as related error was already reported
60346             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
60347                 error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type);
60348             }
60349             return booleanType;
60350         }
60351         function checkInExpression(left, right, leftType, rightType) {
60352             if (leftType === silentNeverType || rightType === silentNeverType) {
60353                 return silentNeverType;
60354             }
60355             leftType = checkNonNullType(leftType, left);
60356             rightType = checkNonNullType(rightType, right);
60357             // TypeScript 1.0 spec (April 2014): 4.15.5
60358             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
60359             // and the right operand to be of type Any, an object type, or a type parameter type.
60360             // The result is always of the Boolean primitive type.
60361             if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) {
60362                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
60363             }
60364             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
60365                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60366             }
60367             return booleanType;
60368         }
60369         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
60370             var properties = node.properties;
60371             if (strictNullChecks && properties.length === 0) {
60372                 return checkNonNullType(sourceType, node);
60373             }
60374             for (var i = 0; i < properties.length; i++) {
60375                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
60376             }
60377             return sourceType;
60378         }
60379         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
60380         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
60381             if (rightIsThis === void 0) { rightIsThis = false; }
60382             var properties = node.properties;
60383             var property = properties[propertyIndex];
60384             if (property.kind === 281 /* PropertyAssignment */ || property.kind === 282 /* ShorthandPropertyAssignment */) {
60385                 var name = property.name;
60386                 var exprType = getLiteralTypeFromPropertyName(name);
60387                 if (isTypeUsableAsPropertyName(exprType)) {
60388                     var text = getPropertyNameFromType(exprType);
60389                     var prop = getPropertyOfType(objectLiteralType, text);
60390                     if (prop) {
60391                         markPropertyAsReferenced(prop, property, rightIsThis);
60392                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
60393                     }
60394                 }
60395                 var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
60396                 var type = getFlowTypeOfDestructuring(property, elementType);
60397                 return checkDestructuringAssignment(property.kind === 282 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
60398             }
60399             else if (property.kind === 283 /* SpreadAssignment */) {
60400                 if (propertyIndex < properties.length - 1) {
60401                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60402                 }
60403                 else {
60404                     if (languageVersion < 99 /* ESNext */) {
60405                         checkExternalEmitHelpers(property, 4 /* Rest */);
60406                     }
60407                     var nonRestNames = [];
60408                     if (allProperties) {
60409                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
60410                             var otherProperty = allProperties_1[_i];
60411                             if (!ts.isSpreadAssignment(otherProperty)) {
60412                                 nonRestNames.push(otherProperty.name);
60413                             }
60414                         }
60415                     }
60416                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
60417                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60418                     return checkDestructuringAssignment(property.expression, type);
60419                 }
60420             }
60421             else {
60422                 error(property, ts.Diagnostics.Property_assignment_expected);
60423             }
60424         }
60425         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
60426             var elements = node.elements;
60427             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
60428                 checkExternalEmitHelpers(node, 512 /* Read */);
60429             }
60430             // This elementType will be used if the specific property corresponding to this index is not
60431             // present (aka the tuple element property). This call also checks that the parentType is in
60432             // fact an iterable or array (depending on target language).
60433             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType;
60434             for (var i = 0; i < elements.length; i++) {
60435                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
60436             }
60437             return sourceType;
60438         }
60439         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
60440             var elements = node.elements;
60441             var element = elements[elementIndex];
60442             if (element.kind !== 215 /* OmittedExpression */) {
60443                 if (element.kind !== 213 /* SpreadElement */) {
60444                     var indexType = getLiteralType(elementIndex);
60445                     if (isArrayLikeType(sourceType)) {
60446                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
60447                         // when the element is a SyntaxKind.ElementAccessExpression.
60448                         var accessFlags = hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0;
60449                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, createSyntheticExpression(element, indexType), accessFlags) || errorType;
60450                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
60451                         var type = getFlowTypeOfDestructuring(element, assignedType);
60452                         return checkDestructuringAssignment(element, type, checkMode);
60453                     }
60454                     return checkDestructuringAssignment(element, elementType, checkMode);
60455                 }
60456                 if (elementIndex < elements.length - 1) {
60457                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60458                 }
60459                 else {
60460                     var restExpression = element.expression;
60461                     if (restExpression.kind === 209 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
60462                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
60463                     }
60464                     else {
60465                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60466                         var type = everyType(sourceType, isTupleType) ?
60467                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
60468                             createArrayType(elementType);
60469                         return checkDestructuringAssignment(restExpression, type, checkMode);
60470                     }
60471                 }
60472             }
60473             return undefined;
60474         }
60475         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
60476             var target;
60477             if (exprOrAssignment.kind === 282 /* ShorthandPropertyAssignment */) {
60478                 var prop = exprOrAssignment;
60479                 if (prop.objectAssignmentInitializer) {
60480                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
60481                     // undefined from the final type.
60482                     if (strictNullChecks &&
60483                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
60484                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
60485                     }
60486                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
60487                 }
60488                 target = exprOrAssignment.name;
60489             }
60490             else {
60491                 target = exprOrAssignment;
60492             }
60493             if (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
60494                 checkBinaryExpression(target, checkMode);
60495                 target = target.left;
60496             }
60497             if (target.kind === 193 /* ObjectLiteralExpression */) {
60498                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
60499             }
60500             if (target.kind === 192 /* ArrayLiteralExpression */) {
60501                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
60502             }
60503             return checkReferenceAssignment(target, sourceType, checkMode);
60504         }
60505         function checkReferenceAssignment(target, sourceType, checkMode) {
60506             var targetType = checkExpression(target, checkMode);
60507             var error = target.parent.kind === 283 /* SpreadAssignment */ ?
60508                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
60509                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
60510             var optionalError = target.parent.kind === 283 /* SpreadAssignment */ ?
60511                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
60512                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
60513             if (checkReferenceExpression(target, error, optionalError)) {
60514                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
60515             }
60516             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
60517                 checkExternalEmitHelpers(target.parent, 524288 /* ClassPrivateFieldSet */);
60518             }
60519             return sourceType;
60520         }
60521         /**
60522          * This is a *shallow* check: An expression is side-effect-free if the
60523          * evaluation of the expression *itself* cannot produce side effects.
60524          * For example, x++ / 3 is side-effect free because the / operator
60525          * does not have side effects.
60526          * The intent is to "smell test" an expression for correctness in positions where
60527          * its value is discarded (e.g. the left side of the comma operator).
60528          */
60529         function isSideEffectFree(node) {
60530             node = ts.skipParentheses(node);
60531             switch (node.kind) {
60532                 case 75 /* Identifier */:
60533                 case 10 /* StringLiteral */:
60534                 case 13 /* RegularExpressionLiteral */:
60535                 case 198 /* TaggedTemplateExpression */:
60536                 case 211 /* TemplateExpression */:
60537                 case 14 /* NoSubstitutionTemplateLiteral */:
60538                 case 8 /* NumericLiteral */:
60539                 case 9 /* BigIntLiteral */:
60540                 case 106 /* TrueKeyword */:
60541                 case 91 /* FalseKeyword */:
60542                 case 100 /* NullKeyword */:
60543                 case 146 /* UndefinedKeyword */:
60544                 case 201 /* FunctionExpression */:
60545                 case 214 /* ClassExpression */:
60546                 case 202 /* ArrowFunction */:
60547                 case 192 /* ArrayLiteralExpression */:
60548                 case 193 /* ObjectLiteralExpression */:
60549                 case 204 /* TypeOfExpression */:
60550                 case 218 /* NonNullExpression */:
60551                 case 267 /* JsxSelfClosingElement */:
60552                 case 266 /* JsxElement */:
60553                     return true;
60554                 case 210 /* ConditionalExpression */:
60555                     return isSideEffectFree(node.whenTrue) &&
60556                         isSideEffectFree(node.whenFalse);
60557                 case 209 /* BinaryExpression */:
60558                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
60559                         return false;
60560                     }
60561                     return isSideEffectFree(node.left) &&
60562                         isSideEffectFree(node.right);
60563                 case 207 /* PrefixUnaryExpression */:
60564                 case 208 /* PostfixUnaryExpression */:
60565                     // Unary operators ~, !, +, and - have no side effects.
60566                     // The rest do.
60567                     switch (node.operator) {
60568                         case 53 /* ExclamationToken */:
60569                         case 39 /* PlusToken */:
60570                         case 40 /* MinusToken */:
60571                         case 54 /* TildeToken */:
60572                             return true;
60573                     }
60574                     return false;
60575                 // Some forms listed here for clarity
60576                 case 205 /* VoidExpression */: // Explicit opt-out
60577                 case 199 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
60578                 case 217 /* AsExpression */: // Not SEF, but can produce useful type warnings
60579                 default:
60580                     return false;
60581             }
60582         }
60583         function isTypeEqualityComparableTo(source, target) {
60584             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
60585         }
60586         var CheckBinaryExpressionState;
60587         (function (CheckBinaryExpressionState) {
60588             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
60589             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
60590             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
60591         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
60592         function checkBinaryExpression(node, checkMode) {
60593             var workStacks = {
60594                 expr: [node],
60595                 state: [0 /* MaybeCheckLeft */],
60596                 leftType: [undefined]
60597             };
60598             var stackIndex = 0;
60599             var lastResult;
60600             while (stackIndex >= 0) {
60601                 node = workStacks.expr[stackIndex];
60602                 switch (workStacks.state[stackIndex]) {
60603                     case 0 /* MaybeCheckLeft */: {
60604                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
60605                             finishInvocation(checkExpression(node.right, checkMode));
60606                             break;
60607                         }
60608                         checkGrammarNullishCoalesceWithLogicalExpression(node);
60609                         var operator = node.operatorToken.kind;
60610                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 193 /* ObjectLiteralExpression */ || node.left.kind === 192 /* ArrayLiteralExpression */)) {
60611                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 104 /* ThisKeyword */));
60612                             break;
60613                         }
60614                         advanceState(1 /* CheckRight */);
60615                         maybeCheckExpression(node.left);
60616                         break;
60617                     }
60618                     case 1 /* CheckRight */: {
60619                         var leftType = lastResult;
60620                         workStacks.leftType[stackIndex] = leftType;
60621                         var operator = node.operatorToken.kind;
60622                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60623                             checkTruthinessOfType(leftType, node.left);
60624                         }
60625                         advanceState(2 /* FinishCheck */);
60626                         maybeCheckExpression(node.right);
60627                         break;
60628                     }
60629                     case 2 /* FinishCheck */: {
60630                         var leftType = workStacks.leftType[stackIndex];
60631                         var rightType = lastResult;
60632                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
60633                         break;
60634                     }
60635                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
60636                 }
60637             }
60638             return lastResult;
60639             function finishInvocation(result) {
60640                 lastResult = result;
60641                 stackIndex--;
60642             }
60643             /**
60644              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
60645              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
60646              */
60647             function advanceState(nextState) {
60648                 workStacks.state[stackIndex] = nextState;
60649             }
60650             function maybeCheckExpression(node) {
60651                 if (ts.isBinaryExpression(node)) {
60652                     stackIndex++;
60653                     workStacks.expr[stackIndex] = node;
60654                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
60655                     workStacks.leftType[stackIndex] = undefined;
60656                 }
60657                 else {
60658                     lastResult = checkExpression(node, checkMode);
60659                 }
60660             }
60661         }
60662         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
60663             var left = node.left, operatorToken = node.operatorToken, right = node.right;
60664             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
60665                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60666                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60667                 }
60668                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60669                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60670                 }
60671             }
60672         }
60673         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
60674         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
60675         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
60676             var operator = operatorToken.kind;
60677             if (operator === 62 /* EqualsToken */ && (left.kind === 193 /* ObjectLiteralExpression */ || left.kind === 192 /* ArrayLiteralExpression */)) {
60678                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 104 /* ThisKeyword */);
60679             }
60680             var leftType;
60681             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60682                 leftType = checkTruthinessExpression(left, checkMode);
60683             }
60684             else {
60685                 leftType = checkExpression(left, checkMode);
60686             }
60687             var rightType = checkExpression(right, checkMode);
60688             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
60689         }
60690         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
60691             var operator = operatorToken.kind;
60692             switch (operator) {
60693                 case 41 /* AsteriskToken */:
60694                 case 42 /* AsteriskAsteriskToken */:
60695                 case 65 /* AsteriskEqualsToken */:
60696                 case 66 /* AsteriskAsteriskEqualsToken */:
60697                 case 43 /* SlashToken */:
60698                 case 67 /* SlashEqualsToken */:
60699                 case 44 /* PercentToken */:
60700                 case 68 /* PercentEqualsToken */:
60701                 case 40 /* MinusToken */:
60702                 case 64 /* MinusEqualsToken */:
60703                 case 47 /* LessThanLessThanToken */:
60704                 case 69 /* LessThanLessThanEqualsToken */:
60705                 case 48 /* GreaterThanGreaterThanToken */:
60706                 case 70 /* GreaterThanGreaterThanEqualsToken */:
60707                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60708                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60709                 case 51 /* BarToken */:
60710                 case 73 /* BarEqualsToken */:
60711                 case 52 /* CaretToken */:
60712                 case 74 /* CaretEqualsToken */:
60713                 case 50 /* AmpersandToken */:
60714                 case 72 /* AmpersandEqualsToken */:
60715                     if (leftType === silentNeverType || rightType === silentNeverType) {
60716                         return silentNeverType;
60717                     }
60718                     leftType = checkNonNullType(leftType, left);
60719                     rightType = checkNonNullType(rightType, right);
60720                     var suggestedOperator = void 0;
60721                     // if a user tries to apply a bitwise operator to 2 boolean operands
60722                     // try and return them a helpful suggestion
60723                     if ((leftType.flags & 528 /* BooleanLike */) &&
60724                         (rightType.flags & 528 /* BooleanLike */) &&
60725                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
60726                         error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator));
60727                         return numberType;
60728                     }
60729                     else {
60730                         // otherwise just check each operand separately and report errors as normal
60731                         var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, /*isAwaitValid*/ true);
60732                         var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, /*isAwaitValid*/ true);
60733                         var resultType_1;
60734                         // If both are any or unknown, allow operation; assume it will resolve to number
60735                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
60736                             // Or, if neither could be bigint, implicit coercion results in a number result
60737                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
60738                             resultType_1 = numberType;
60739                         }
60740                         // At least one is assignable to bigint, so check that both are
60741                         else if (bothAreBigIntLike(leftType, rightType)) {
60742                             switch (operator) {
60743                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60744                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60745                                     reportOperatorError();
60746                             }
60747                             resultType_1 = bigintType;
60748                         }
60749                         // Exactly one of leftType/rightType is assignable to bigint
60750                         else {
60751                             reportOperatorError(bothAreBigIntLike);
60752                             resultType_1 = errorType;
60753                         }
60754                         if (leftOk && rightOk) {
60755                             checkAssignmentOperator(resultType_1);
60756                         }
60757                         return resultType_1;
60758                     }
60759                 case 39 /* PlusToken */:
60760                 case 63 /* PlusEqualsToken */:
60761                     if (leftType === silentNeverType || rightType === silentNeverType) {
60762                         return silentNeverType;
60763                     }
60764                     if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
60765                         leftType = checkNonNullType(leftType, left);
60766                         rightType = checkNonNullType(rightType, right);
60767                     }
60768                     var resultType = void 0;
60769                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
60770                         // Operands of an enum type are treated as having the primitive type Number.
60771                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
60772                         resultType = numberType;
60773                     }
60774                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
60775                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
60776                         resultType = bigintType;
60777                     }
60778                     else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
60779                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
60780                         resultType = stringType;
60781                     }
60782                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
60783                         // Otherwise, the result is of type Any.
60784                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
60785                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
60786                     }
60787                     // Symbols are not allowed at all in arithmetic expressions
60788                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
60789                         return resultType;
60790                     }
60791                     if (!resultType) {
60792                         // Types that have a reasonably good chance of being a valid operand type.
60793                         // If both types have an awaited type of one of these, we'll assume the user
60794                         // might be missing an await without doing an exhaustive check that inserting
60795                         // await(s) will actually be a completely valid binary expression.
60796                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 3 /* AnyOrUnknown */;
60797                         reportOperatorError(function (left, right) {
60798                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
60799                                 isTypeAssignableToKind(right, closeEnoughKind_1);
60800                         });
60801                         return anyType;
60802                     }
60803                     if (operator === 63 /* PlusEqualsToken */) {
60804                         checkAssignmentOperator(resultType);
60805                     }
60806                     return resultType;
60807                 case 29 /* LessThanToken */:
60808                 case 31 /* GreaterThanToken */:
60809                 case 32 /* LessThanEqualsToken */:
60810                 case 33 /* GreaterThanEqualsToken */:
60811                     if (checkForDisallowedESSymbolOperand(operator)) {
60812                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
60813                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
60814                         reportOperatorErrorUnless(function (left, right) {
60815                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
60816                         });
60817                     }
60818                     return booleanType;
60819                 case 34 /* EqualsEqualsToken */:
60820                 case 35 /* ExclamationEqualsToken */:
60821                 case 36 /* EqualsEqualsEqualsToken */:
60822                 case 37 /* ExclamationEqualsEqualsToken */:
60823                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
60824                     return booleanType;
60825                 case 98 /* InstanceOfKeyword */:
60826                     return checkInstanceOfExpression(left, right, leftType, rightType);
60827                 case 97 /* InKeyword */:
60828                     return checkInExpression(left, right, leftType, rightType);
60829                 case 55 /* AmpersandAmpersandToken */:
60830                     return getTypeFacts(leftType) & 4194304 /* Truthy */ ?
60831                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
60832                         leftType;
60833                 case 56 /* BarBarToken */:
60834                     return getTypeFacts(leftType) & 8388608 /* Falsy */ ?
60835                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
60836                         leftType;
60837                 case 60 /* QuestionQuestionToken */:
60838                     return getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
60839                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
60840                         leftType;
60841                 case 62 /* EqualsToken */:
60842                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
60843                     checkAssignmentDeclaration(declKind, rightType);
60844                     if (isAssignmentDeclaration(declKind)) {
60845                         if (!(rightType.flags & 524288 /* Object */) ||
60846                             declKind !== 2 /* ModuleExports */ &&
60847                                 declKind !== 6 /* Prototype */ &&
60848                                 !isEmptyObjectType(rightType) &&
60849                                 !isFunctionObjectType(rightType) &&
60850                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
60851                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
60852                             checkAssignmentOperator(rightType);
60853                         }
60854                         return leftType;
60855                     }
60856                     else {
60857                         checkAssignmentOperator(rightType);
60858                         return getRegularTypeOfObjectLiteral(rightType);
60859                     }
60860                 case 27 /* CommaToken */:
60861                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
60862                         error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
60863                     }
60864                     return rightType;
60865                 default:
60866                     return ts.Debug.fail();
60867             }
60868             function bothAreBigIntLike(left, right) {
60869                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
60870             }
60871             function checkAssignmentDeclaration(kind, rightType) {
60872                 if (kind === 2 /* ModuleExports */) {
60873                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
60874                         var prop = _a[_i];
60875                         var propType = getTypeOfSymbol(prop);
60876                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
60877                             var name = prop.escapedName;
60878                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
60879                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
60880                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
60881                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
60882                             }
60883                         }
60884                     }
60885                 }
60886             }
60887             function isEvalNode(node) {
60888                 return node.kind === 75 /* Identifier */ && node.escapedText === "eval";
60889             }
60890             // Return true if there was no error, false if there was an error.
60891             function checkForDisallowedESSymbolOperand(operator) {
60892                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
60893                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
60894                         undefined;
60895                 if (offendingSymbolOperand) {
60896                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
60897                     return false;
60898                 }
60899                 return true;
60900             }
60901             function getSuggestedBooleanOperator(operator) {
60902                 switch (operator) {
60903                     case 51 /* BarToken */:
60904                     case 73 /* BarEqualsToken */:
60905                         return 56 /* BarBarToken */;
60906                     case 52 /* CaretToken */:
60907                     case 74 /* CaretEqualsToken */:
60908                         return 37 /* ExclamationEqualsEqualsToken */;
60909                     case 50 /* AmpersandToken */:
60910                     case 72 /* AmpersandEqualsToken */:
60911                         return 55 /* AmpersandAmpersandToken */;
60912                     default:
60913                         return undefined;
60914                 }
60915             }
60916             function checkAssignmentOperator(valueType) {
60917                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
60918                     // TypeScript 1.0 spec (April 2014): 4.17
60919                     // An assignment of the form
60920                     //    VarExpr = ValueExpr
60921                     // requires VarExpr to be classified as a reference
60922                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
60923                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
60924                     if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)
60925                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
60926                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
60927                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
60928                     }
60929                 }
60930             }
60931             function isAssignmentDeclaration(kind) {
60932                 switch (kind) {
60933                     case 2 /* ModuleExports */:
60934                         return true;
60935                     case 1 /* ExportsProperty */:
60936                     case 5 /* Property */:
60937                     case 6 /* Prototype */:
60938                     case 3 /* PrototypeProperty */:
60939                     case 4 /* ThisProperty */:
60940                         var symbol = getSymbolOfNode(left);
60941                         var init = ts.getAssignedExpandoInitializer(right);
60942                         return init && ts.isObjectLiteralExpression(init) &&
60943                             symbol && ts.hasEntries(symbol.exports);
60944                     default:
60945                         return false;
60946                 }
60947             }
60948             /**
60949              * Returns true if an error is reported
60950              */
60951             function reportOperatorErrorUnless(typesAreCompatible) {
60952                 if (!typesAreCompatible(leftType, rightType)) {
60953                     reportOperatorError(typesAreCompatible);
60954                     return true;
60955                 }
60956                 return false;
60957             }
60958             function reportOperatorError(isRelated) {
60959                 var _a;
60960                 var wouldWorkWithAwait = false;
60961                 var errNode = errorNode || operatorToken;
60962                 if (isRelated) {
60963                     var awaitedLeftType = getAwaitedType(leftType);
60964                     var awaitedRightType = getAwaitedType(rightType);
60965                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
60966                         && !!(awaitedLeftType && awaitedRightType)
60967                         && isRelated(awaitedLeftType, awaitedRightType);
60968                 }
60969                 var effectiveLeft = leftType;
60970                 var effectiveRight = rightType;
60971                 if (!wouldWorkWithAwait && isRelated) {
60972                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
60973                 }
60974                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
60975                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
60976                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
60977                 }
60978             }
60979             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
60980                 var typeName;
60981                 switch (operatorToken.kind) {
60982                     case 36 /* EqualsEqualsEqualsToken */:
60983                     case 34 /* EqualsEqualsToken */:
60984                         typeName = "false";
60985                         break;
60986                     case 37 /* ExclamationEqualsEqualsToken */:
60987                     case 35 /* ExclamationEqualsToken */:
60988                         typeName = "true";
60989                 }
60990                 if (typeName) {
60991                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
60992                 }
60993                 return undefined;
60994             }
60995         }
60996         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
60997             var effectiveLeft = leftType;
60998             var effectiveRight = rightType;
60999             var leftBase = getBaseTypeOfLiteralType(leftType);
61000             var rightBase = getBaseTypeOfLiteralType(rightType);
61001             if (!isRelated(leftBase, rightBase)) {
61002                 effectiveLeft = leftBase;
61003                 effectiveRight = rightBase;
61004             }
61005             return [effectiveLeft, effectiveRight];
61006         }
61007         function checkYieldExpression(node) {
61008             // Grammar checking
61009             if (produceDiagnostics) {
61010                 if (!(node.flags & 8192 /* YieldContext */)) {
61011                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
61012                 }
61013                 if (isInParameterInitializerBeforeContainingFunction(node)) {
61014                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
61015                 }
61016             }
61017             var func = ts.getContainingFunction(node);
61018             if (!func)
61019                 return anyType;
61020             var functionFlags = ts.getFunctionFlags(func);
61021             if (!(functionFlags & 1 /* Generator */)) {
61022                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
61023                 return anyType;
61024             }
61025             var isAsync = (functionFlags & 2 /* Async */) !== 0;
61026             if (node.asteriskToken) {
61027                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
61028                 // and __asyncValues helpers
61029                 if (isAsync && languageVersion < 99 /* ESNext */) {
61030                     checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
61031                 }
61032                 // Generator functions prior to ES2015 require the __values helper
61033                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
61034                     checkExternalEmitHelpers(node, 256 /* Values */);
61035                 }
61036             }
61037             // There is no point in doing an assignability check if the function
61038             // has no explicit return type because the return type is directly computed
61039             // from the yield expressions.
61040             var returnType = getReturnTypeFromAnnotation(func);
61041             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
61042             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
61043             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
61044             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
61045             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
61046             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
61047             if (returnType && yieldedType) {
61048                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
61049             }
61050             if (node.asteriskToken) {
61051                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
61052                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
61053                     || anyType;
61054             }
61055             else if (returnType) {
61056                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
61057                     || anyType;
61058             }
61059             return getContextualIterationType(2 /* Next */, func) || anyType;
61060         }
61061         function checkConditionalExpression(node, checkMode) {
61062             var type = checkTruthinessExpression(node.condition);
61063             checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
61064             var type1 = checkExpression(node.whenTrue, checkMode);
61065             var type2 = checkExpression(node.whenFalse, checkMode);
61066             return getUnionType([type1, type2], 2 /* Subtype */);
61067         }
61068         function checkTemplateExpression(node) {
61069             // We just want to check each expressions, but we are unconcerned with
61070             // the type of each expression, as any value may be coerced into a string.
61071             // It is worth asking whether this is what we really want though.
61072             // A place where we actually *are* concerned with the expressions' types are
61073             // in tagged templates.
61074             ts.forEach(node.templateSpans, function (templateSpan) {
61075                 if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
61076                     error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
61077                 }
61078             });
61079             return stringType;
61080         }
61081         function getContextNode(node) {
61082             if (node.kind === 274 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
61083                 return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes)
61084             }
61085             return node;
61086         }
61087         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
61088             var context = getContextNode(node);
61089             var saveContextualType = context.contextualType;
61090             var saveInferenceContext = context.inferenceContext;
61091             try {
61092                 context.contextualType = contextualType;
61093                 context.inferenceContext = inferenceContext;
61094                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
61095                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
61096                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
61097                 // here would be to not mark contextually typed literals as fresh in the first place.
61098                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
61099                     getRegularTypeOfLiteralType(type) : type;
61100                 return result;
61101             }
61102             finally {
61103                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61104                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61105                 // may hold onto the checker that created it.
61106                 context.contextualType = saveContextualType;
61107                 context.inferenceContext = saveInferenceContext;
61108             }
61109         }
61110         function checkExpressionCached(node, checkMode) {
61111             var links = getNodeLinks(node);
61112             if (!links.resolvedType) {
61113                 if (checkMode && checkMode !== 0 /* Normal */) {
61114                     return checkExpression(node, checkMode);
61115                 }
61116                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
61117                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
61118                 // to the top of the stack ensures all transient types are computed from a known point.
61119                 var saveFlowLoopStart = flowLoopStart;
61120                 var saveFlowTypeCache = flowTypeCache;
61121                 flowLoopStart = flowLoopCount;
61122                 flowTypeCache = undefined;
61123                 links.resolvedType = checkExpression(node, checkMode);
61124                 flowTypeCache = saveFlowTypeCache;
61125                 flowLoopStart = saveFlowLoopStart;
61126             }
61127             return links.resolvedType;
61128         }
61129         function isTypeAssertion(node) {
61130             node = ts.skipParentheses(node);
61131             return node.kind === 199 /* TypeAssertionExpression */ || node.kind === 217 /* AsExpression */;
61132         }
61133         function checkDeclarationInitializer(declaration, contextualType) {
61134             var initializer = ts.getEffectiveInitializer(declaration);
61135             var type = getQuickTypeOfExpression(initializer) ||
61136                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
61137             return ts.isParameter(declaration) && declaration.name.kind === 190 /* ArrayBindingPattern */ &&
61138                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
61139                 padTupleType(type, declaration.name) : type;
61140         }
61141         function padTupleType(type, pattern) {
61142             var patternElements = pattern.elements;
61143             var arity = getTypeReferenceArity(type);
61144             var elementTypes = arity ? getTypeArguments(type).slice() : [];
61145             for (var i = arity; i < patternElements.length; i++) {
61146                 var e = patternElements[i];
61147                 if (i < patternElements.length - 1 || !(e.kind === 191 /* BindingElement */ && e.dotDotDotToken)) {
61148                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
61149                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
61150                         reportImplicitAny(e, anyType);
61151                     }
61152                 }
61153             }
61154             return createTupleType(elementTypes, type.target.minLength, /*hasRestElement*/ false, type.target.readonly);
61155         }
61156         function widenTypeInferredFromInitializer(declaration, type) {
61157             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
61158             if (ts.isInJSFile(declaration)) {
61159                 if (widened.flags & 98304 /* Nullable */) {
61160                     reportImplicitAny(declaration, anyType);
61161                     return anyType;
61162                 }
61163                 else if (isEmptyArrayLiteralType(widened)) {
61164                     reportImplicitAny(declaration, anyArrayType);
61165                     return anyArrayType;
61166                 }
61167             }
61168             return widened;
61169         }
61170         function isLiteralOfContextualType(candidateType, contextualType) {
61171             if (contextualType) {
61172                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
61173                     var types = contextualType.types;
61174                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
61175                 }
61176                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
61177                     // If the contextual type is a type variable constrained to a primitive type, consider
61178                     // this a literal context for literals of that primitive type. For example, given a
61179                     // type parameter 'T extends string', infer string literal types for T.
61180                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
61181                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61182                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61183                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61184                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
61185                         isLiteralOfContextualType(candidateType, constraint);
61186                 }
61187                 // If the contextual type is a literal of a particular primitive type, we consider this a
61188                 // literal context for all literals of that primitive type.
61189                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61190                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61191                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61192                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
61193                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
61194             }
61195             return false;
61196         }
61197         function isConstContext(node) {
61198             var parent = node.parent;
61199             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
61200                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
61201                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
61202         }
61203         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
61204             var type = checkExpression(node, checkMode, forceTuple);
61205             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
61206                 isTypeAssertion(node) ? type :
61207                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
61208         }
61209         function checkPropertyAssignment(node, checkMode) {
61210             // Do not use hasDynamicName here, because that returns false for well known symbols.
61211             // We want to perform checkComputedPropertyName for all computed properties, including
61212             // well known symbols.
61213             if (node.name.kind === 154 /* ComputedPropertyName */) {
61214                 checkComputedPropertyName(node.name);
61215             }
61216             return checkExpressionForMutableLocation(node.initializer, checkMode);
61217         }
61218         function checkObjectLiteralMethod(node, checkMode) {
61219             // Grammar checking
61220             checkGrammarMethod(node);
61221             // Do not use hasDynamicName here, because that returns false for well known symbols.
61222             // We want to perform checkComputedPropertyName for all computed properties, including
61223             // well known symbols.
61224             if (node.name.kind === 154 /* ComputedPropertyName */) {
61225                 checkComputedPropertyName(node.name);
61226             }
61227             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61228             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61229         }
61230         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
61231             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
61232                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
61233                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
61234                 var signature = callSignature || constructSignature;
61235                 if (signature && signature.typeParameters) {
61236                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
61237                     if (contextualType) {
61238                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
61239                         if (contextualSignature && !contextualSignature.typeParameters) {
61240                             if (checkMode & 8 /* SkipGenericFunctions */) {
61241                                 skippedGenericFunction(node, checkMode);
61242                                 return anyFunctionType;
61243                             }
61244                             var context = getInferenceContext(node);
61245                             // We have an expression that is an argument of a generic function for which we are performing
61246                             // type argument inference. The expression is of a function type with a single generic call
61247                             // signature and a contextual function type with a single non-generic call signature. Now check
61248                             // if the outer function returns a function type with a single non-generic call signature and
61249                             // if some of the outer function type parameters have no inferences so far. If so, we can
61250                             // potentially add inferred type parameters to the outer function return type.
61251                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
61252                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
61253                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
61254                                 // Instantiate the signature with its own type parameters as type arguments, possibly
61255                                 // renaming the type parameters to ensure they have unique names.
61256                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
61257                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
61258                                 // Infer from the parameters of the instantiated signature to the parameters of the
61259                                 // contextual signature starting with an empty set of inference candidates.
61260                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
61261                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
61262                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
61263                                 });
61264                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
61265                                     // We have inference candidates, indicating that one or more type parameters are referenced
61266                                     // in the parameter types of the contextual signature. Now also infer from the return type.
61267                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
61268                                         inferTypes(inferences_3, source, target);
61269                                     });
61270                                     // If the type parameters for which we produced candidates do not have any inferences yet,
61271                                     // we adopt the new inference candidates and add the type parameters of the expression type
61272                                     // to the set of inferred type parameters for the outer function return type.
61273                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
61274                                         mergeInferences(context.inferences, inferences_3);
61275                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
61276                                         return getOrCreateTypeFromSignature(instantiatedSignature);
61277                                     }
61278                                 }
61279                             }
61280                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
61281                         }
61282                     }
61283                 }
61284             }
61285             return type;
61286         }
61287         function skippedGenericFunction(node, checkMode) {
61288             if (checkMode & 2 /* Inferential */) {
61289                 // We have skipped a generic function during inferential typing. Obtain the inference context and
61290                 // indicate this has occurred such that we know a second pass of inference is be needed.
61291                 var context = getInferenceContext(node);
61292                 context.flags |= 4 /* SkippedGenericFunction */;
61293             }
61294         }
61295         function hasInferenceCandidates(info) {
61296             return !!(info.candidates || info.contraCandidates);
61297         }
61298         function hasOverlappingInferences(a, b) {
61299             for (var i = 0; i < a.length; i++) {
61300                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
61301                     return true;
61302                 }
61303             }
61304             return false;
61305         }
61306         function mergeInferences(target, source) {
61307             for (var i = 0; i < target.length; i++) {
61308                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
61309                     target[i] = source[i];
61310                 }
61311             }
61312         }
61313         function getUniqueTypeParameters(context, typeParameters) {
61314             var result = [];
61315             var oldTypeParameters;
61316             var newTypeParameters;
61317             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
61318                 var tp = typeParameters_2[_i];
61319                 var name = tp.symbol.escapedName;
61320                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
61321                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
61322                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
61323                     var newTypeParameter = createTypeParameter(symbol);
61324                     newTypeParameter.target = tp;
61325                     oldTypeParameters = ts.append(oldTypeParameters, tp);
61326                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
61327                     result.push(newTypeParameter);
61328                 }
61329                 else {
61330                     result.push(tp);
61331                 }
61332             }
61333             if (newTypeParameters) {
61334                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
61335                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
61336                     var tp = newTypeParameters_1[_a];
61337                     tp.mapper = mapper;
61338                 }
61339             }
61340             return result;
61341         }
61342         function hasTypeParameterByName(typeParameters, name) {
61343             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
61344         }
61345         function getUniqueTypeParameterName(typeParameters, baseName) {
61346             var len = baseName.length;
61347             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
61348                 len--;
61349             var s = baseName.slice(0, len);
61350             for (var index = 1; true; index++) {
61351                 var augmentedName = (s + index);
61352                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
61353                     return augmentedName;
61354                 }
61355             }
61356         }
61357         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
61358             var signature = getSingleCallSignature(funcType);
61359             if (signature && !signature.typeParameters) {
61360                 return getReturnTypeOfSignature(signature);
61361             }
61362         }
61363         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
61364             var funcType = checkExpression(expr.expression);
61365             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
61366             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
61367             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
61368         }
61369         /**
61370          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61371          * with computing the type and may not fully check all contained sub-expressions for errors.
61372          */
61373         function getTypeOfExpression(node) {
61374             // Don't bother caching types that require no flow analysis and are quick to compute.
61375             var quickType = getQuickTypeOfExpression(node);
61376             if (quickType) {
61377                 return quickType;
61378             }
61379             // If a type has been cached for the node, return it.
61380             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
61381                 var cachedType = flowTypeCache[getNodeId(node)];
61382                 if (cachedType) {
61383                     return cachedType;
61384                 }
61385             }
61386             var startInvocationCount = flowInvocationCount;
61387             var type = checkExpression(node);
61388             // If control flow analysis was required to determine the type, it is worth caching.
61389             if (flowInvocationCount !== startInvocationCount) {
61390                 var cache = flowTypeCache || (flowTypeCache = []);
61391                 cache[getNodeId(node)] = type;
61392                 node.flags |= 67108864 /* TypeCached */;
61393             }
61394             return type;
61395         }
61396         function getQuickTypeOfExpression(node) {
61397             var expr = ts.skipParentheses(node);
61398             // Optimize for the common case of a call to a function with a single non-generic call
61399             // signature where we can just fetch the return type without checking the arguments.
61400             if (ts.isCallExpression(expr) && expr.expression.kind !== 102 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
61401                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
61402                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
61403                 if (type) {
61404                     return type;
61405                 }
61406             }
61407             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
61408                 return getTypeFromTypeNode(expr.type);
61409             }
61410             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
61411                 node.kind === 106 /* TrueKeyword */ || node.kind === 91 /* FalseKeyword */) {
61412                 return checkExpression(node);
61413             }
61414             return undefined;
61415         }
61416         /**
61417          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61418          * with computing the type and may not fully check all contained sub-expressions for errors.
61419          * It is intended for uses where you know there is no contextual type,
61420          * and requesting the contextual type might cause a circularity or other bad behaviour.
61421          * It sets the contextual type of the node to any before calling getTypeOfExpression.
61422          */
61423         function getContextFreeTypeOfExpression(node) {
61424             var links = getNodeLinks(node);
61425             if (links.contextFreeType) {
61426                 return links.contextFreeType;
61427             }
61428             var saveContextualType = node.contextualType;
61429             node.contextualType = anyType;
61430             try {
61431                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
61432                 return type;
61433             }
61434             finally {
61435                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61436                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61437                 // may hold onto the checker that created it.
61438                 node.contextualType = saveContextualType;
61439             }
61440         }
61441         function checkExpression(node, checkMode, forceTuple) {
61442             var saveCurrentNode = currentNode;
61443             currentNode = node;
61444             instantiationCount = 0;
61445             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
61446             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61447             if (isConstEnumObjectType(type)) {
61448                 checkConstEnumAccess(node, type);
61449             }
61450             currentNode = saveCurrentNode;
61451             return type;
61452         }
61453         function checkConstEnumAccess(node, type) {
61454             // enum object type for const enums are only permitted in:
61455             // - 'left' in property access
61456             // - 'object' in indexed access
61457             // - target in rhs of import statement
61458             var ok = (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.expression === node) ||
61459                 (node.parent.kind === 195 /* ElementAccessExpression */ && node.parent.expression === node) ||
61460                 ((node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
61461                     (node.parent.kind === 172 /* TypeQuery */ && node.parent.exprName === node)) ||
61462                 (node.parent.kind === 263 /* ExportSpecifier */); // We allow reexporting const enums
61463             if (!ok) {
61464                 error(node, ts.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);
61465             }
61466             if (compilerOptions.isolatedModules) {
61467                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
61468                 var constEnumDeclaration = type.symbol.valueDeclaration;
61469                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
61470                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
61471                 }
61472             }
61473         }
61474         function checkParenthesizedExpression(node, checkMode) {
61475             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
61476             if (tag) {
61477                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
61478             }
61479             return checkExpression(node.expression, checkMode);
61480         }
61481         function checkExpressionWorker(node, checkMode, forceTuple) {
61482             var kind = node.kind;
61483             if (cancellationToken) {
61484                 // Only bother checking on a few construct kinds.  We don't want to be excessively
61485                 // hitting the cancellation token on every node we check.
61486                 switch (kind) {
61487                     case 214 /* ClassExpression */:
61488                     case 201 /* FunctionExpression */:
61489                     case 202 /* ArrowFunction */:
61490                         cancellationToken.throwIfCancellationRequested();
61491                 }
61492             }
61493             switch (kind) {
61494                 case 75 /* Identifier */:
61495                     return checkIdentifier(node);
61496                 case 104 /* ThisKeyword */:
61497                     return checkThisExpression(node);
61498                 case 102 /* SuperKeyword */:
61499                     return checkSuperExpression(node);
61500                 case 100 /* NullKeyword */:
61501                     return nullWideningType;
61502                 case 14 /* NoSubstitutionTemplateLiteral */:
61503                 case 10 /* StringLiteral */:
61504                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
61505                 case 8 /* NumericLiteral */:
61506                     checkGrammarNumericLiteral(node);
61507                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
61508                 case 9 /* BigIntLiteral */:
61509                     checkGrammarBigIntLiteral(node);
61510                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
61511                 case 106 /* TrueKeyword */:
61512                     return trueType;
61513                 case 91 /* FalseKeyword */:
61514                     return falseType;
61515                 case 211 /* TemplateExpression */:
61516                     return checkTemplateExpression(node);
61517                 case 13 /* RegularExpressionLiteral */:
61518                     return globalRegExpType;
61519                 case 192 /* ArrayLiteralExpression */:
61520                     return checkArrayLiteral(node, checkMode, forceTuple);
61521                 case 193 /* ObjectLiteralExpression */:
61522                     return checkObjectLiteral(node, checkMode);
61523                 case 194 /* PropertyAccessExpression */:
61524                     return checkPropertyAccessExpression(node);
61525                 case 153 /* QualifiedName */:
61526                     return checkQualifiedName(node);
61527                 case 195 /* ElementAccessExpression */:
61528                     return checkIndexedAccess(node);
61529                 case 196 /* CallExpression */:
61530                     if (node.expression.kind === 96 /* ImportKeyword */) {
61531                         return checkImportCallExpression(node);
61532                     }
61533                 // falls through
61534                 case 197 /* NewExpression */:
61535                     return checkCallExpression(node, checkMode);
61536                 case 198 /* TaggedTemplateExpression */:
61537                     return checkTaggedTemplateExpression(node);
61538                 case 200 /* ParenthesizedExpression */:
61539                     return checkParenthesizedExpression(node, checkMode);
61540                 case 214 /* ClassExpression */:
61541                     return checkClassExpression(node);
61542                 case 201 /* FunctionExpression */:
61543                 case 202 /* ArrowFunction */:
61544                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61545                 case 204 /* TypeOfExpression */:
61546                     return checkTypeOfExpression(node);
61547                 case 199 /* TypeAssertionExpression */:
61548                 case 217 /* AsExpression */:
61549                     return checkAssertion(node);
61550                 case 218 /* NonNullExpression */:
61551                     return checkNonNullAssertion(node);
61552                 case 219 /* MetaProperty */:
61553                     return checkMetaProperty(node);
61554                 case 203 /* DeleteExpression */:
61555                     return checkDeleteExpression(node);
61556                 case 205 /* VoidExpression */:
61557                     return checkVoidExpression(node);
61558                 case 206 /* AwaitExpression */:
61559                     return checkAwaitExpression(node);
61560                 case 207 /* PrefixUnaryExpression */:
61561                     return checkPrefixUnaryExpression(node);
61562                 case 208 /* PostfixUnaryExpression */:
61563                     return checkPostfixUnaryExpression(node);
61564                 case 209 /* BinaryExpression */:
61565                     return checkBinaryExpression(node, checkMode);
61566                 case 210 /* ConditionalExpression */:
61567                     return checkConditionalExpression(node, checkMode);
61568                 case 213 /* SpreadElement */:
61569                     return checkSpreadExpression(node, checkMode);
61570                 case 215 /* OmittedExpression */:
61571                     return undefinedWideningType;
61572                 case 212 /* YieldExpression */:
61573                     return checkYieldExpression(node);
61574                 case 220 /* SyntheticExpression */:
61575                     return node.type;
61576                 case 276 /* JsxExpression */:
61577                     return checkJsxExpression(node, checkMode);
61578                 case 266 /* JsxElement */:
61579                     return checkJsxElement(node, checkMode);
61580                 case 267 /* JsxSelfClosingElement */:
61581                     return checkJsxSelfClosingElement(node, checkMode);
61582                 case 270 /* JsxFragment */:
61583                     return checkJsxFragment(node);
61584                 case 274 /* JsxAttributes */:
61585                     return checkJsxAttributes(node, checkMode);
61586                 case 268 /* JsxOpeningElement */:
61587                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
61588             }
61589             return errorType;
61590         }
61591         // DECLARATION AND STATEMENT TYPE CHECKING
61592         function checkTypeParameter(node) {
61593             // Grammar Checking
61594             if (node.expression) {
61595                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
61596             }
61597             checkSourceElement(node.constraint);
61598             checkSourceElement(node.default);
61599             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
61600             // Resolve base constraint to reveal circularity errors
61601             getBaseConstraintOfType(typeParameter);
61602             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
61603                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
61604             }
61605             var constraintType = getConstraintOfTypeParameter(typeParameter);
61606             var defaultType = getDefaultFromTypeParameter(typeParameter);
61607             if (constraintType && defaultType) {
61608                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
61609             }
61610             if (produceDiagnostics) {
61611                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
61612             }
61613         }
61614         function checkParameter(node) {
61615             // Grammar checking
61616             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
61617             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
61618             // or if its FunctionBody is strict code(11.1.5).
61619             checkGrammarDecoratorsAndModifiers(node);
61620             checkVariableLikeDeclaration(node);
61621             var func = ts.getContainingFunction(node);
61622             if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
61623                 if (!(func.kind === 162 /* Constructor */ && ts.nodeIsPresent(func.body))) {
61624                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
61625                 }
61626                 if (func.kind === 162 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
61627                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
61628                 }
61629             }
61630             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
61631                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
61632             }
61633             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
61634                 if (func.parameters.indexOf(node) !== 0) {
61635                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
61636                 }
61637                 if (func.kind === 162 /* Constructor */ || func.kind === 166 /* ConstructSignature */ || func.kind === 171 /* ConstructorType */) {
61638                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
61639                 }
61640                 if (func.kind === 202 /* ArrowFunction */) {
61641                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
61642                 }
61643                 if (func.kind === 163 /* GetAccessor */ || func.kind === 164 /* SetAccessor */) {
61644                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
61645                 }
61646             }
61647             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
61648             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
61649             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
61650                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
61651             }
61652         }
61653         function checkTypePredicate(node) {
61654             var parent = getTypePredicateParent(node);
61655             if (!parent) {
61656                 // The parent must not be valid.
61657                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
61658                 return;
61659             }
61660             var signature = getSignatureFromDeclaration(parent);
61661             var typePredicate = getTypePredicateOfSignature(signature);
61662             if (!typePredicate) {
61663                 return;
61664             }
61665             checkSourceElement(node.type);
61666             var parameterName = node.parameterName;
61667             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
61668                 getTypeFromThisTypeNode(parameterName);
61669             }
61670             else {
61671                 if (typePredicate.parameterIndex >= 0) {
61672                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
61673                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
61674                     }
61675                     else {
61676                         if (typePredicate.type) {
61677                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
61678                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
61679                             /*headMessage*/ undefined, leadingError);
61680                         }
61681                     }
61682                 }
61683                 else if (parameterName) {
61684                     var hasReportedError = false;
61685                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
61686                         var name = _a[_i].name;
61687                         if (ts.isBindingPattern(name) &&
61688                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
61689                             hasReportedError = true;
61690                             break;
61691                         }
61692                     }
61693                     if (!hasReportedError) {
61694                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
61695                     }
61696                 }
61697             }
61698         }
61699         function getTypePredicateParent(node) {
61700             switch (node.parent.kind) {
61701                 case 202 /* ArrowFunction */:
61702                 case 165 /* CallSignature */:
61703                 case 244 /* FunctionDeclaration */:
61704                 case 201 /* FunctionExpression */:
61705                 case 170 /* FunctionType */:
61706                 case 161 /* MethodDeclaration */:
61707                 case 160 /* MethodSignature */:
61708                     var parent = node.parent;
61709                     if (node === parent.type) {
61710                         return parent;
61711                     }
61712             }
61713         }
61714         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
61715             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
61716                 var element = _a[_i];
61717                 if (ts.isOmittedExpression(element)) {
61718                     continue;
61719                 }
61720                 var name = element.name;
61721                 if (name.kind === 75 /* Identifier */ && name.escapedText === predicateVariableName) {
61722                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
61723                     return true;
61724                 }
61725                 else if (name.kind === 190 /* ArrayBindingPattern */ || name.kind === 189 /* ObjectBindingPattern */) {
61726                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
61727                         return true;
61728                     }
61729                 }
61730             }
61731         }
61732         function checkSignatureDeclaration(node) {
61733             // Grammar checking
61734             if (node.kind === 167 /* IndexSignature */) {
61735                 checkGrammarIndexSignature(node);
61736             }
61737             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
61738             else if (node.kind === 170 /* FunctionType */ || node.kind === 244 /* FunctionDeclaration */ || node.kind === 171 /* ConstructorType */ ||
61739                 node.kind === 165 /* CallSignature */ || node.kind === 162 /* Constructor */ ||
61740                 node.kind === 166 /* ConstructSignature */) {
61741                 checkGrammarFunctionLikeDeclaration(node);
61742             }
61743             var functionFlags = ts.getFunctionFlags(node);
61744             if (!(functionFlags & 4 /* Invalid */)) {
61745                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
61746                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
61747                     checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
61748                 }
61749                 // Async functions prior to ES2017 require the __awaiter helper
61750                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
61751                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
61752                 }
61753                 // Generator functions, Async functions, and Async Generator functions prior to
61754                 // ES2015 require the __generator helper
61755                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
61756                     checkExternalEmitHelpers(node, 128 /* Generator */);
61757                 }
61758             }
61759             checkTypeParameters(node.typeParameters);
61760             ts.forEach(node.parameters, checkParameter);
61761             // TODO(rbuckton): Should we start checking JSDoc types?
61762             if (node.type) {
61763                 checkSourceElement(node.type);
61764             }
61765             if (produceDiagnostics) {
61766                 checkCollisionWithArgumentsInGeneratedCode(node);
61767                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
61768                 if (noImplicitAny && !returnTypeNode) {
61769                     switch (node.kind) {
61770                         case 166 /* ConstructSignature */:
61771                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61772                             break;
61773                         case 165 /* CallSignature */:
61774                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61775                             break;
61776                     }
61777                 }
61778                 if (returnTypeNode) {
61779                     var functionFlags_1 = ts.getFunctionFlags(node);
61780                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
61781                         var returnType = getTypeFromTypeNode(returnTypeNode);
61782                         if (returnType === voidType) {
61783                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
61784                         }
61785                         else {
61786                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
61787                             // However, that would not catch the error in the following case.
61788                             //
61789                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
61790                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
61791                             //
61792                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
61793                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
61794                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
61795                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
61796                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
61797                         }
61798                     }
61799                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
61800                         checkAsyncFunctionReturnType(node, returnTypeNode);
61801                     }
61802                 }
61803                 if (node.kind !== 167 /* IndexSignature */ && node.kind !== 300 /* JSDocFunctionType */) {
61804                     registerForUnusedIdentifiersCheck(node);
61805                 }
61806             }
61807         }
61808         function checkClassForDuplicateDeclarations(node) {
61809             var instanceNames = ts.createUnderscoreEscapedMap();
61810             var staticNames = ts.createUnderscoreEscapedMap();
61811             // instance and static private identifiers share the same scope
61812             var privateIdentifiers = ts.createUnderscoreEscapedMap();
61813             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61814                 var member = _a[_i];
61815                 if (member.kind === 162 /* Constructor */) {
61816                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
61817                         var param = _c[_b];
61818                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
61819                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
61820                         }
61821                     }
61822                 }
61823                 else {
61824                     var isStatic = ts.hasModifier(member, 32 /* Static */);
61825                     var name = member.name;
61826                     if (!name) {
61827                         return;
61828                     }
61829                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
61830                         isStatic ? staticNames :
61831                             instanceNames;
61832                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
61833                     if (memberName) {
61834                         switch (member.kind) {
61835                             case 163 /* GetAccessor */:
61836                                 addName(names, name, memberName, 1 /* GetAccessor */);
61837                                 break;
61838                             case 164 /* SetAccessor */:
61839                                 addName(names, name, memberName, 2 /* SetAccessor */);
61840                                 break;
61841                             case 159 /* PropertyDeclaration */:
61842                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
61843                                 break;
61844                             case 161 /* MethodDeclaration */:
61845                                 addName(names, name, memberName, 8 /* Method */);
61846                                 break;
61847                         }
61848                     }
61849                 }
61850             }
61851             function addName(names, location, name, meaning) {
61852                 var prev = names.get(name);
61853                 if (prev) {
61854                     if (prev & 8 /* Method */) {
61855                         if (meaning !== 8 /* Method */) {
61856                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61857                         }
61858                     }
61859                     else if (prev & meaning) {
61860                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61861                     }
61862                     else {
61863                         names.set(name, prev | meaning);
61864                     }
61865                 }
61866                 else {
61867                     names.set(name, meaning);
61868                 }
61869             }
61870         }
61871         /**
61872          * Static members being set on a constructor function may conflict with built-in properties
61873          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
61874          * built-in properties. This check issues a transpile error when a class has a static
61875          * member with the same name as a non-writable built-in property.
61876          *
61877          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
61878          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
61879          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
61880          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
61881          */
61882         function checkClassForStaticPropertyNameConflicts(node) {
61883             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61884                 var member = _a[_i];
61885                 var memberNameNode = member.name;
61886                 var isStatic = ts.hasModifier(member, 32 /* Static */);
61887                 if (isStatic && memberNameNode) {
61888                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
61889                     switch (memberName) {
61890                         case "name":
61891                         case "length":
61892                         case "caller":
61893                         case "arguments":
61894                         case "prototype":
61895                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
61896                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
61897                             error(memberNameNode, message, memberName, className);
61898                             break;
61899                     }
61900                 }
61901             }
61902         }
61903         function checkObjectTypeForDuplicateDeclarations(node) {
61904             var names = ts.createMap();
61905             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61906                 var member = _a[_i];
61907                 if (member.kind === 158 /* PropertySignature */) {
61908                     var memberName = void 0;
61909                     var name = member.name;
61910                     switch (name.kind) {
61911                         case 10 /* StringLiteral */:
61912                         case 8 /* NumericLiteral */:
61913                             memberName = name.text;
61914                             break;
61915                         case 75 /* Identifier */:
61916                             memberName = ts.idText(name);
61917                             break;
61918                         default:
61919                             continue;
61920                     }
61921                     if (names.get(memberName)) {
61922                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
61923                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
61924                     }
61925                     else {
61926                         names.set(memberName, true);
61927                     }
61928                 }
61929             }
61930         }
61931         function checkTypeForDuplicateIndexSignatures(node) {
61932             if (node.kind === 246 /* InterfaceDeclaration */) {
61933                 var nodeSymbol = getSymbolOfNode(node);
61934                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
61935                 // to prevent this run check only for the first declaration of a given kind
61936                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
61937                     return;
61938                 }
61939             }
61940             // TypeScript 1.0 spec (April 2014)
61941             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
61942             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
61943             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
61944             if (indexSymbol) {
61945                 var seenNumericIndexer = false;
61946                 var seenStringIndexer = false;
61947                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
61948                     var decl = _a[_i];
61949                     var declaration = decl;
61950                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
61951                         switch (declaration.parameters[0].type.kind) {
61952                             case 143 /* StringKeyword */:
61953                                 if (!seenStringIndexer) {
61954                                     seenStringIndexer = true;
61955                                 }
61956                                 else {
61957                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
61958                                 }
61959                                 break;
61960                             case 140 /* NumberKeyword */:
61961                                 if (!seenNumericIndexer) {
61962                                     seenNumericIndexer = true;
61963                                 }
61964                                 else {
61965                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
61966                                 }
61967                                 break;
61968                         }
61969                     }
61970                 }
61971             }
61972         }
61973         function checkPropertyDeclaration(node) {
61974             // Grammar checking
61975             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
61976                 checkGrammarComputedPropertyName(node.name);
61977             checkVariableLikeDeclaration(node);
61978             // Private class fields transformation relies on WeakMaps.
61979             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
61980                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
61981                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
61982                 }
61983             }
61984         }
61985         function checkPropertySignature(node) {
61986             if (ts.isPrivateIdentifier(node.name)) {
61987                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
61988             }
61989             return checkPropertyDeclaration(node);
61990         }
61991         function checkMethodDeclaration(node) {
61992             // Grammar checking
61993             if (!checkGrammarMethod(node))
61994                 checkGrammarComputedPropertyName(node.name);
61995             if (ts.isPrivateIdentifier(node.name)) {
61996                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
61997             }
61998             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
61999             checkFunctionOrMethodDeclaration(node);
62000             // Abstract methods cannot have an implementation.
62001             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
62002             if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 161 /* MethodDeclaration */ && node.body) {
62003                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
62004             }
62005         }
62006         function checkConstructorDeclaration(node) {
62007             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
62008             checkSignatureDeclaration(node);
62009             // Grammar check for checking only related to constructorDeclaration
62010             if (!checkGrammarConstructorTypeParameters(node))
62011                 checkGrammarConstructorTypeAnnotation(node);
62012             checkSourceElement(node.body);
62013             var symbol = getSymbolOfNode(node);
62014             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
62015             // Only type check the symbol once
62016             if (node === firstDeclaration) {
62017                 checkFunctionOrConstructorSymbol(symbol);
62018             }
62019             // exit early in the case of signature - super checks are not relevant to them
62020             if (ts.nodeIsMissing(node.body)) {
62021                 return;
62022             }
62023             if (!produceDiagnostics) {
62024                 return;
62025             }
62026             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
62027                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
62028                     return true;
62029                 }
62030                 return n.kind === 159 /* PropertyDeclaration */ &&
62031                     !ts.hasModifier(n, 32 /* Static */) &&
62032                     !!n.initializer;
62033             }
62034             // TS 1.0 spec (April 2014): 8.3.2
62035             // Constructors of classes with no extends clause may not contain super calls, whereas
62036             // constructors of derived classes must contain at least one super call somewhere in their function body.
62037             var containingClassDecl = node.parent;
62038             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
62039                 captureLexicalThis(node.parent, containingClassDecl);
62040                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
62041                 var superCall = getSuperCallInConstructor(node);
62042                 if (superCall) {
62043                     if (classExtendsNull) {
62044                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
62045                     }
62046                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
62047                     // if both of the following are true:
62048                     // - The containing class is a derived class.
62049                     // - The constructor declares parameter properties
62050                     //   or the containing class declares instance member variables with initializers.
62051                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
62052                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
62053                             ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }));
62054                     // Skip past any prologue directives to find the first statement
62055                     // to ensure that it was a super call.
62056                     if (superCallShouldBeFirst) {
62057                         var statements = node.body.statements;
62058                         var superCallStatement = void 0;
62059                         for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
62060                             var statement = statements_3[_i];
62061                             if (statement.kind === 226 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
62062                                 superCallStatement = statement;
62063                                 break;
62064                             }
62065                             if (!ts.isPrologueDirective(statement)) {
62066                                 break;
62067                             }
62068                         }
62069                         if (!superCallStatement) {
62070                             error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers);
62071                         }
62072                     }
62073                 }
62074                 else if (!classExtendsNull) {
62075                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
62076                 }
62077             }
62078         }
62079         function checkAccessorDeclaration(node) {
62080             if (produceDiagnostics) {
62081                 // Grammar checking accessors
62082                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
62083                     checkGrammarComputedPropertyName(node.name);
62084                 checkDecorators(node);
62085                 checkSignatureDeclaration(node);
62086                 if (node.kind === 163 /* GetAccessor */) {
62087                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
62088                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
62089                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
62090                         }
62091                     }
62092                 }
62093                 // Do not use hasDynamicName here, because that returns false for well known symbols.
62094                 // We want to perform checkComputedPropertyName for all computed properties, including
62095                 // well known symbols.
62096                 if (node.name.kind === 154 /* ComputedPropertyName */) {
62097                     checkComputedPropertyName(node.name);
62098                 }
62099                 if (ts.isPrivateIdentifier(node.name)) {
62100                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
62101                 }
62102                 if (!hasNonBindableDynamicName(node)) {
62103                     // TypeScript 1.0 spec (April 2014): 8.4.3
62104                     // Accessors for the same member name must specify the same accessibility.
62105                     var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
62106                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
62107                     if (otherAccessor) {
62108                         var nodeFlags = ts.getModifierFlags(node);
62109                         var otherFlags = ts.getModifierFlags(otherAccessor);
62110                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
62111                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
62112                         }
62113                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
62114                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
62115                         }
62116                         // TypeScript 1.0 spec (April 2014): 4.5
62117                         // If both accessors include type annotations, the specified types must be identical.
62118                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
62119                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
62120                     }
62121                 }
62122                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
62123                 if (node.kind === 163 /* GetAccessor */) {
62124                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
62125                 }
62126             }
62127             checkSourceElement(node.body);
62128         }
62129         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
62130             var firstType = getAnnotatedType(first);
62131             var secondType = getAnnotatedType(second);
62132             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
62133                 error(first, message);
62134             }
62135         }
62136         function checkMissingDeclaration(node) {
62137             checkDecorators(node);
62138         }
62139         function getEffectiveTypeArguments(node, typeParameters) {
62140             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
62141         }
62142         function checkTypeArgumentConstraints(node, typeParameters) {
62143             var typeArguments;
62144             var mapper;
62145             var result = true;
62146             for (var i = 0; i < typeParameters.length; i++) {
62147                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
62148                 if (constraint) {
62149                     if (!typeArguments) {
62150                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
62151                         mapper = createTypeMapper(typeParameters, typeArguments);
62152                     }
62153                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
62154                 }
62155             }
62156             return result;
62157         }
62158         function getTypeParametersForTypeReference(node) {
62159             var type = getTypeFromTypeReference(node);
62160             if (type !== errorType) {
62161                 var symbol = getNodeLinks(node).resolvedSymbol;
62162                 if (symbol) {
62163                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
62164                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
62165                 }
62166             }
62167             return undefined;
62168         }
62169         function checkTypeReferenceNode(node) {
62170             checkGrammarTypeArguments(node, node.typeArguments);
62171             if (node.kind === 169 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
62172                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
62173             }
62174             ts.forEach(node.typeArguments, checkSourceElement);
62175             var type = getTypeFromTypeReference(node);
62176             if (type !== errorType) {
62177                 if (node.typeArguments && produceDiagnostics) {
62178                     var typeParameters = getTypeParametersForTypeReference(node);
62179                     if (typeParameters) {
62180                         checkTypeArgumentConstraints(node, typeParameters);
62181                     }
62182                 }
62183                 if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
62184                     error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
62185                 }
62186             }
62187         }
62188         function getTypeArgumentConstraint(node) {
62189             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
62190             if (!typeReferenceNode)
62191                 return undefined;
62192             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
62193             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
62194             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
62195         }
62196         function checkTypeQuery(node) {
62197             getTypeFromTypeQueryNode(node);
62198         }
62199         function checkTypeLiteral(node) {
62200             ts.forEach(node.members, checkSourceElement);
62201             if (produceDiagnostics) {
62202                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
62203                 checkIndexConstraints(type);
62204                 checkTypeForDuplicateIndexSignatures(node);
62205                 checkObjectTypeForDuplicateDeclarations(node);
62206             }
62207         }
62208         function checkArrayType(node) {
62209             checkSourceElement(node.elementType);
62210         }
62211         function checkTupleType(node) {
62212             var elementTypes = node.elementTypes;
62213             var seenOptionalElement = false;
62214             for (var i = 0; i < elementTypes.length; i++) {
62215                 var e = elementTypes[i];
62216                 if (e.kind === 177 /* RestType */) {
62217                     if (i !== elementTypes.length - 1) {
62218                         grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
62219                         break;
62220                     }
62221                     if (!isArrayType(getTypeFromTypeNode(e.type))) {
62222                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
62223                     }
62224                 }
62225                 else if (e.kind === 176 /* OptionalType */) {
62226                     seenOptionalElement = true;
62227                 }
62228                 else if (seenOptionalElement) {
62229                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
62230                     break;
62231                 }
62232             }
62233             ts.forEach(node.elementTypes, checkSourceElement);
62234         }
62235         function checkUnionOrIntersectionType(node) {
62236             ts.forEach(node.types, checkSourceElement);
62237         }
62238         function checkIndexedAccessIndexType(type, accessNode) {
62239             if (!(type.flags & 8388608 /* IndexedAccess */)) {
62240                 return type;
62241             }
62242             // Check if the index type is assignable to 'keyof T' for the object type.
62243             var objectType = type.objectType;
62244             var indexType = type.indexType;
62245             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
62246                 if (accessNode.kind === 195 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
62247                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
62248                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
62249                 }
62250                 return type;
62251             }
62252             // Check if we're indexing with a numeric type and if either object or index types
62253             // is a generic type with a constraint that has a numeric index signature.
62254             var apparentObjectType = getApparentType(objectType);
62255             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
62256                 return type;
62257             }
62258             if (isGenericObjectType(objectType)) {
62259                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
62260                 if (propertyName_1) {
62261                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
62262                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
62263                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
62264                         return errorType;
62265                     }
62266                 }
62267             }
62268             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
62269             return errorType;
62270         }
62271         function checkIndexedAccessType(node) {
62272             checkSourceElement(node.objectType);
62273             checkSourceElement(node.indexType);
62274             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
62275         }
62276         function checkMappedType(node) {
62277             checkSourceElement(node.typeParameter);
62278             checkSourceElement(node.type);
62279             if (!node.type) {
62280                 reportImplicitAny(node, anyType);
62281             }
62282             var type = getTypeFromMappedTypeNode(node);
62283             var constraintType = getConstraintTypeFromMappedType(type);
62284             checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
62285         }
62286         function checkThisType(node) {
62287             getTypeFromThisTypeNode(node);
62288         }
62289         function checkTypeOperator(node) {
62290             checkGrammarTypeOperatorNode(node);
62291             checkSourceElement(node.type);
62292         }
62293         function checkConditionalType(node) {
62294             ts.forEachChild(node, checkSourceElement);
62295         }
62296         function checkInferType(node) {
62297             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 180 /* ConditionalType */ && n.parent.extendsType === n; })) {
62298                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
62299             }
62300             checkSourceElement(node.typeParameter);
62301             registerForUnusedIdentifiersCheck(node);
62302         }
62303         function checkImportType(node) {
62304             checkSourceElement(node.argument);
62305             getTypeFromTypeNode(node);
62306         }
62307         function isPrivateWithinAmbient(node) {
62308             return (ts.hasModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
62309         }
62310         function getEffectiveDeclarationFlags(n, flagsToCheck) {
62311             var flags = ts.getCombinedModifierFlags(n);
62312             // children of classes (even ambient classes) should not be marked as ambient or export
62313             // because those flags have no useful semantics there.
62314             if (n.parent.kind !== 246 /* InterfaceDeclaration */ &&
62315                 n.parent.kind !== 245 /* ClassDeclaration */ &&
62316                 n.parent.kind !== 214 /* ClassExpression */ &&
62317                 n.flags & 8388608 /* Ambient */) {
62318                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
62319                     // It is nested in an ambient context, which means it is automatically exported
62320                     flags |= 1 /* Export */;
62321                 }
62322                 flags |= 2 /* Ambient */;
62323             }
62324             return flags & flagsToCheck;
62325         }
62326         function checkFunctionOrConstructorSymbol(symbol) {
62327             if (!produceDiagnostics) {
62328                 return;
62329             }
62330             function getCanonicalOverload(overloads, implementation) {
62331                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
62332                 // Error on all deviations from this canonical set of flags
62333                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
62334                 // report the errors on those. To achieve this, we will say that the implementation is
62335                 // the canonical signature only if it is in the same container as the first overload
62336                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
62337                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
62338             }
62339             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
62340                 // Error if some overloads have a flag that is not shared by all overloads. To find the
62341                 // deviations, we XOR someOverloadFlags with allOverloadFlags
62342                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
62343                 if (someButNotAllOverloadFlags !== 0) {
62344                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
62345                     ts.forEach(overloads, function (o) {
62346                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
62347                         if (deviation & 1 /* Export */) {
62348                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
62349                         }
62350                         else if (deviation & 2 /* Ambient */) {
62351                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
62352                         }
62353                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
62354                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
62355                         }
62356                         else if (deviation & 128 /* Abstract */) {
62357                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
62358                         }
62359                     });
62360                 }
62361             }
62362             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
62363                 if (someHaveQuestionToken !== allHaveQuestionToken) {
62364                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
62365                     ts.forEach(overloads, function (o) {
62366                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
62367                         if (deviation) {
62368                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
62369                         }
62370                     });
62371                 }
62372             }
62373             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
62374             var someNodeFlags = 0 /* None */;
62375             var allNodeFlags = flagsToCheck;
62376             var someHaveQuestionToken = false;
62377             var allHaveQuestionToken = true;
62378             var hasOverloads = false;
62379             var bodyDeclaration;
62380             var lastSeenNonAmbientDeclaration;
62381             var previousDeclaration;
62382             var declarations = symbol.declarations;
62383             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
62384             function reportImplementationExpectedError(node) {
62385                 if (node.name && ts.nodeIsMissing(node.name)) {
62386                     return;
62387                 }
62388                 var seen = false;
62389                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
62390                     if (seen) {
62391                         return c;
62392                     }
62393                     else {
62394                         seen = c === node;
62395                     }
62396                 });
62397                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
62398                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
62399                 if (subsequentNode && subsequentNode.pos === node.end) {
62400                     if (subsequentNode.kind === node.kind) {
62401                         var errorNode_1 = subsequentNode.name || subsequentNode;
62402                         var subsequentName = subsequentNode.name;
62403                         if (node.name && subsequentName && (
62404                         // both are private identifiers
62405                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
62406                             // Both are computed property names
62407                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
62408                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
62409                             // Both are literal property names that are the same.
62410                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
62411                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
62412                             var reportError = (node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */) &&
62413                                 ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
62414                             // we can get here in two cases
62415                             // 1. mixed static and instance class members
62416                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
62417                             // here we'll report error only for the first case since for second we should already report error in binder
62418                             if (reportError) {
62419                                 var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
62420                                 error(errorNode_1, diagnostic);
62421                             }
62422                             return;
62423                         }
62424                         if (ts.nodeIsPresent(subsequentNode.body)) {
62425                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
62426                             return;
62427                         }
62428                     }
62429                 }
62430                 var errorNode = node.name || node;
62431                 if (isConstructor) {
62432                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
62433                 }
62434                 else {
62435                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
62436                     // the node in question is abstract.
62437                     if (ts.hasModifier(node, 128 /* Abstract */)) {
62438                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
62439                     }
62440                     else {
62441                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
62442                     }
62443                 }
62444             }
62445             var duplicateFunctionDeclaration = false;
62446             var multipleConstructorImplementation = false;
62447             var hasNonAmbientClass = false;
62448             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
62449                 var current = declarations_4[_i];
62450                 var node = current;
62451                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
62452                 var inAmbientContextOrInterface = node.parent.kind === 246 /* InterfaceDeclaration */ || node.parent.kind === 173 /* TypeLiteral */ || inAmbientContext;
62453                 if (inAmbientContextOrInterface) {
62454                     // check if declarations are consecutive only if they are non-ambient
62455                     // 1. ambient declarations can be interleaved
62456                     // i.e. this is legal
62457                     //     declare function foo();
62458                     //     declare function bar();
62459                     //     declare function foo();
62460                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
62461                     previousDeclaration = undefined;
62462                 }
62463                 if ((node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */) && !inAmbientContext) {
62464                     hasNonAmbientClass = true;
62465                 }
62466                 if (node.kind === 244 /* FunctionDeclaration */ || node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */ || node.kind === 162 /* Constructor */) {
62467                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
62468                     someNodeFlags |= currentNodeFlags;
62469                     allNodeFlags &= currentNodeFlags;
62470                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
62471                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
62472                     if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
62473                         if (isConstructor) {
62474                             multipleConstructorImplementation = true;
62475                         }
62476                         else {
62477                             duplicateFunctionDeclaration = true;
62478                         }
62479                     }
62480                     else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
62481                         reportImplementationExpectedError(previousDeclaration);
62482                     }
62483                     if (ts.nodeIsPresent(node.body)) {
62484                         if (!bodyDeclaration) {
62485                             bodyDeclaration = node;
62486                         }
62487                     }
62488                     else {
62489                         hasOverloads = true;
62490                     }
62491                     previousDeclaration = node;
62492                     if (!inAmbientContextOrInterface) {
62493                         lastSeenNonAmbientDeclaration = node;
62494                     }
62495                 }
62496             }
62497             if (multipleConstructorImplementation) {
62498                 ts.forEach(declarations, function (declaration) {
62499                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
62500                 });
62501             }
62502             if (duplicateFunctionDeclaration) {
62503                 ts.forEach(declarations, function (declaration) {
62504                     error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
62505                 });
62506             }
62507             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
62508                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
62509                 // TODO: The below just replicates our older error from when classes and functions were
62510                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
62511                 // might be warranted. :shrug:
62512                 ts.forEach(declarations, function (declaration) {
62513                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
62514                 });
62515             }
62516             // Abstract methods can't have an implementation -- in particular, they don't need one.
62517             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
62518                 !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
62519                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
62520             }
62521             if (hasOverloads) {
62522                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
62523                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
62524                 if (bodyDeclaration) {
62525                     var signatures = getSignaturesOfSymbol(symbol);
62526                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
62527                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
62528                         var signature = signatures_10[_a];
62529                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
62530                             ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
62531                             break;
62532                         }
62533                     }
62534                 }
62535             }
62536         }
62537         function checkExportsOnMergedDeclarations(node) {
62538             if (!produceDiagnostics) {
62539                 return;
62540             }
62541             // if localSymbol is defined on node then node itself is exported - check is required
62542             var symbol = node.localSymbol;
62543             if (!symbol) {
62544                 // local symbol is undefined => this declaration is non-exported.
62545                 // however symbol might contain other declarations that are exported
62546                 symbol = getSymbolOfNode(node);
62547                 if (!symbol.exportSymbol) {
62548                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
62549                     return;
62550                 }
62551             }
62552             // run the check only for the first declaration in the list
62553             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
62554                 return;
62555             }
62556             var exportedDeclarationSpaces = 0 /* None */;
62557             var nonExportedDeclarationSpaces = 0 /* None */;
62558             var defaultExportedDeclarationSpaces = 0 /* None */;
62559             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
62560                 var d = _a[_i];
62561                 var declarationSpaces = getDeclarationSpaces(d);
62562                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
62563                 if (effectiveDeclarationFlags & 1 /* Export */) {
62564                     if (effectiveDeclarationFlags & 512 /* Default */) {
62565                         defaultExportedDeclarationSpaces |= declarationSpaces;
62566                     }
62567                     else {
62568                         exportedDeclarationSpaces |= declarationSpaces;
62569                     }
62570                 }
62571                 else {
62572                     nonExportedDeclarationSpaces |= declarationSpaces;
62573                 }
62574             }
62575             // Spaces for anything not declared a 'default export'.
62576             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
62577             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
62578             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
62579             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
62580                 // declaration spaces for exported and non-exported declarations intersect
62581                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
62582                     var d = _c[_b];
62583                     var declarationSpaces = getDeclarationSpaces(d);
62584                     var name = ts.getNameOfDeclaration(d);
62585                     // Only error on the declarations that contributed to the intersecting spaces.
62586                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
62587                         error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name));
62588                     }
62589                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
62590                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
62591                     }
62592                 }
62593             }
62594             function getDeclarationSpaces(decl) {
62595                 var d = decl;
62596                 switch (d.kind) {
62597                     case 246 /* InterfaceDeclaration */:
62598                     case 247 /* TypeAliasDeclaration */:
62599                     // A jsdoc typedef and callback are, by definition, type aliases.
62600                     // falls through
62601                     case 322 /* JSDocTypedefTag */:
62602                     case 315 /* JSDocCallbackTag */:
62603                     case 316 /* JSDocEnumTag */:
62604                         return 2 /* ExportType */;
62605                     case 249 /* ModuleDeclaration */:
62606                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
62607                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
62608                             : 4 /* ExportNamespace */;
62609                     case 245 /* ClassDeclaration */:
62610                     case 248 /* EnumDeclaration */:
62611                     case 284 /* EnumMember */:
62612                         return 2 /* ExportType */ | 1 /* ExportValue */;
62613                     case 290 /* SourceFile */:
62614                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
62615                     case 259 /* ExportAssignment */:
62616                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
62617                         if (!ts.isEntityNameExpression(d.expression)) {
62618                             return 1 /* ExportValue */;
62619                         }
62620                         d = d.expression;
62621                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
62622                     // falls through
62623                     case 253 /* ImportEqualsDeclaration */:
62624                     case 256 /* NamespaceImport */:
62625                     case 255 /* ImportClause */:
62626                         var result_10 = 0 /* None */;
62627                         var target = resolveAlias(getSymbolOfNode(d));
62628                         ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); });
62629                         return result_10;
62630                     case 242 /* VariableDeclaration */:
62631                     case 191 /* BindingElement */:
62632                     case 244 /* FunctionDeclaration */:
62633                     case 258 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
62634                     case 75 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
62635                         // Identifiers are used as declarations of assignment declarations whose parents may be
62636                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
62637                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
62638                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
62639                         // all of which are pretty much always values, or at least imply a value meaning.
62640                         // It may be apprpriate to treat these as aliases in the future.
62641                         return 1 /* ExportValue */;
62642                     default:
62643                         return ts.Debug.failBadSyntaxKind(d);
62644                 }
62645             }
62646         }
62647         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
62648             var promisedType = getPromisedTypeOfPromise(type, errorNode);
62649             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62650         }
62651         /**
62652          * Gets the "promised type" of a promise.
62653          * @param type The type of the promise.
62654          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
62655          */
62656         function getPromisedTypeOfPromise(type, errorNode) {
62657             //
62658             //  { // type
62659             //      then( // thenFunction
62660             //          onfulfilled: ( // onfulfilledParameterType
62661             //              value: T // valueParameterType
62662             //          ) => any
62663             //      ): any;
62664             //  }
62665             //
62666             if (isTypeAny(type)) {
62667                 return undefined;
62668             }
62669             var typeAsPromise = type;
62670             if (typeAsPromise.promisedTypeOfPromise) {
62671                 return typeAsPromise.promisedTypeOfPromise;
62672             }
62673             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
62674                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
62675             }
62676             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
62677             if (isTypeAny(thenFunction)) {
62678                 return undefined;
62679             }
62680             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
62681             if (thenSignatures.length === 0) {
62682                 if (errorNode) {
62683                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
62684                 }
62685                 return undefined;
62686             }
62687             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
62688             if (isTypeAny(onfulfilledParameterType)) {
62689                 return undefined;
62690             }
62691             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
62692             if (onfulfilledParameterSignatures.length === 0) {
62693                 if (errorNode) {
62694                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
62695                 }
62696                 return undefined;
62697             }
62698             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
62699         }
62700         /**
62701          * Gets the "awaited type" of a type.
62702          * @param type The type to await.
62703          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
62704          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
62705          * The runtime behavior of the `await` keyword.
62706          */
62707         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62708             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
62709             return awaitedType || errorType;
62710         }
62711         /**
62712          * Determines whether a type has a callable `then` member.
62713          */
62714         function isThenableType(type) {
62715             var thenFunction = getTypeOfPropertyOfType(type, "then");
62716             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
62717         }
62718         /**
62719          * Gets the "awaited type" of a type.
62720          *
62721          * The "awaited type" of an expression is its "promised type" if the expression is a
62722          * Promise-like type; otherwise, it is the type of the expression. If the "promised
62723          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
62724          * non-promise type is found.
62725          *
62726          * This is used to reflect the runtime behavior of the `await` keyword.
62727          */
62728         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62729             if (isTypeAny(type)) {
62730                 return type;
62731             }
62732             var typeAsAwaitable = type;
62733             if (typeAsAwaitable.awaitedTypeOfType) {
62734                 return typeAsAwaitable.awaitedTypeOfType;
62735             }
62736             // For a union, get a union of the awaited types of each constituent.
62737             //
62738             return typeAsAwaitable.awaitedTypeOfType =
62739                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
62740         }
62741         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
62742             var typeAsAwaitable = type;
62743             if (typeAsAwaitable.awaitedTypeOfType) {
62744                 return typeAsAwaitable.awaitedTypeOfType;
62745             }
62746             var promisedType = getPromisedTypeOfPromise(type);
62747             if (promisedType) {
62748                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
62749                     // Verify that we don't have a bad actor in the form of a promise whose
62750                     // promised type is the same as the promise type, or a mutually recursive
62751                     // promise. If so, we return undefined as we cannot guess the shape. If this
62752                     // were the actual case in the JavaScript, this Promise would never resolve.
62753                     //
62754                     // An example of a bad actor with a singly-recursive promise type might
62755                     // be:
62756                     //
62757                     //  interface BadPromise {
62758                     //      then(
62759                     //          onfulfilled: (value: BadPromise) => any,
62760                     //          onrejected: (error: any) => any): BadPromise;
62761                     //  }
62762                     //
62763                     // The above interface will pass the PromiseLike check, and return a
62764                     // promised type of `BadPromise`. Since this is a self reference, we
62765                     // don't want to keep recursing ad infinitum.
62766                     //
62767                     // An example of a bad actor in the form of a mutually-recursive
62768                     // promise type might be:
62769                     //
62770                     //  interface BadPromiseA {
62771                     //      then(
62772                     //          onfulfilled: (value: BadPromiseB) => any,
62773                     //          onrejected: (error: any) => any): BadPromiseB;
62774                     //  }
62775                     //
62776                     //  interface BadPromiseB {
62777                     //      then(
62778                     //          onfulfilled: (value: BadPromiseA) => any,
62779                     //          onrejected: (error: any) => any): BadPromiseA;
62780                     //  }
62781                     //
62782                     if (errorNode) {
62783                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
62784                     }
62785                     return undefined;
62786                 }
62787                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
62788                 // See the comments above for more information.
62789                 awaitedTypeStack.push(type.id);
62790                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62791                 awaitedTypeStack.pop();
62792                 if (!awaitedType) {
62793                     return undefined;
62794                 }
62795                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
62796             }
62797             // The type was not a promise, so it could not be unwrapped any further.
62798             // As long as the type does not have a callable "then" property, it is
62799             // safe to return the type; otherwise, an error is reported and we return
62800             // undefined.
62801             //
62802             // An example of a non-promise "thenable" might be:
62803             //
62804             //  await { then(): void {} }
62805             //
62806             // The "thenable" does not match the minimal definition for a promise. When
62807             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
62808             // will never settle. We treat this as an error to help flag an early indicator
62809             // of a runtime problem. If the user wants to return this value from an async
62810             // function, they would need to wrap it in some other value. If they want it to
62811             // be treated as a promise, they can cast to <any>.
62812             if (isThenableType(type)) {
62813                 if (errorNode) {
62814                     if (!diagnosticMessage)
62815                         return ts.Debug.fail();
62816                     error(errorNode, diagnosticMessage, arg0);
62817                 }
62818                 return undefined;
62819             }
62820             return typeAsAwaitable.awaitedTypeOfType = type;
62821         }
62822         /**
62823          * Checks the return type of an async function to ensure it is a compatible
62824          * Promise implementation.
62825          *
62826          * This checks that an async function has a valid Promise-compatible return type.
62827          * An async function has a valid Promise-compatible return type if the resolved value
62828          * of the return type has a construct signature that takes in an `initializer` function
62829          * that in turn supplies a `resolve` function as one of its arguments and results in an
62830          * object with a callable `then` signature.
62831          *
62832          * @param node The signature to check
62833          */
62834         function checkAsyncFunctionReturnType(node, returnTypeNode) {
62835             // As part of our emit for an async function, we will need to emit the entity name of
62836             // the return type annotation as an expression. To meet the necessary runtime semantics
62837             // for __awaiter, we must also check that the type of the declaration (e.g. the static
62838             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
62839             //
62840             // An example might be (from lib.es6.d.ts):
62841             //
62842             //  interface Promise<T> { ... }
62843             //  interface PromiseConstructor {
62844             //      new <T>(...): Promise<T>;
62845             //  }
62846             //  declare var Promise: PromiseConstructor;
62847             //
62848             // When an async function declares a return type annotation of `Promise<T>`, we
62849             // need to get the type of the `Promise` variable declaration above, which would
62850             // be `PromiseConstructor`.
62851             //
62852             // The same case applies to a class:
62853             //
62854             //  declare class Promise<T> {
62855             //      constructor(...);
62856             //      then<U>(...): Promise<U>;
62857             //  }
62858             //
62859             var returnType = getTypeFromTypeNode(returnTypeNode);
62860             if (languageVersion >= 2 /* ES2015 */) {
62861                 if (returnType === errorType) {
62862                     return;
62863                 }
62864                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
62865                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
62866                     // The promise type was not a valid type reference to the global promise type, so we
62867                     // report an error and return the unknown type.
62868                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
62869                     return;
62870                 }
62871             }
62872             else {
62873                 // Always mark the type node as referenced if it points to a value
62874                 markTypeNodeAsReferenced(returnTypeNode);
62875                 if (returnType === errorType) {
62876                     return;
62877                 }
62878                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
62879                 if (promiseConstructorName === undefined) {
62880                     error(returnTypeNode, ts.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, typeToString(returnType));
62881                     return;
62882                 }
62883                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
62884                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
62885                 if (promiseConstructorType === errorType) {
62886                     if (promiseConstructorName.kind === 75 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
62887                         error(returnTypeNode, ts.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);
62888                     }
62889                     else {
62890                         error(returnTypeNode, ts.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, ts.entityNameToString(promiseConstructorName));
62891                     }
62892                     return;
62893                 }
62894                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
62895                 if (globalPromiseConstructorLikeType === emptyObjectType) {
62896                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
62897                     // compatibility with __awaiter.
62898                     error(returnTypeNode, ts.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, ts.entityNameToString(promiseConstructorName));
62899                     return;
62900                 }
62901                 if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.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)) {
62902                     return;
62903                 }
62904                 // Verify there is no local declaration that could collide with the promise constructor.
62905                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
62906                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
62907                 if (collidingSymbol) {
62908                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
62909                     return;
62910                 }
62911             }
62912             checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
62913         }
62914         /** Check a decorator */
62915         function checkDecorator(node) {
62916             var signature = getResolvedSignature(node);
62917             var returnType = getReturnTypeOfSignature(signature);
62918             if (returnType.flags & 1 /* Any */) {
62919                 return;
62920             }
62921             var expectedReturnType;
62922             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
62923             var errorInfo;
62924             switch (node.parent.kind) {
62925                 case 245 /* ClassDeclaration */:
62926                     var classSymbol = getSymbolOfNode(node.parent);
62927                     var classConstructorType = getTypeOfSymbol(classSymbol);
62928                     expectedReturnType = getUnionType([classConstructorType, voidType]);
62929                     break;
62930                 case 156 /* Parameter */:
62931                     expectedReturnType = voidType;
62932                     errorInfo = ts.chainDiagnosticMessages(
62933                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
62934                     break;
62935                 case 159 /* PropertyDeclaration */:
62936                     expectedReturnType = voidType;
62937                     errorInfo = ts.chainDiagnosticMessages(
62938                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
62939                     break;
62940                 case 161 /* MethodDeclaration */:
62941                 case 163 /* GetAccessor */:
62942                 case 164 /* SetAccessor */:
62943                     var methodType = getTypeOfNode(node.parent);
62944                     var descriptorType = createTypedPropertyDescriptorType(methodType);
62945                     expectedReturnType = getUnionType([descriptorType, voidType]);
62946                     break;
62947                 default:
62948                     return ts.Debug.fail();
62949             }
62950             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
62951         }
62952         /**
62953          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
62954          * marked as referenced to prevent import elision.
62955          */
62956         function markTypeNodeAsReferenced(node) {
62957             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
62958         }
62959         function markEntityNameOrEntityExpressionAsReference(typeName) {
62960             if (!typeName)
62961                 return;
62962             var rootName = ts.getFirstIdentifier(typeName);
62963             var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
62964             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
62965             if (rootSymbol
62966                 && rootSymbol.flags & 2097152 /* Alias */
62967                 && symbolIsValue(rootSymbol)
62968                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
62969                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
62970                 markAliasSymbolAsReferenced(rootSymbol);
62971             }
62972         }
62973         /**
62974          * This function marks the type used for metadata decorator as referenced if it is import
62975          * from external module.
62976          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
62977          * union and intersection type
62978          * @param node
62979          */
62980         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
62981             var entityName = getEntityNameForDecoratorMetadata(node);
62982             if (entityName && ts.isEntityName(entityName)) {
62983                 markEntityNameOrEntityExpressionAsReference(entityName);
62984             }
62985         }
62986         function getEntityNameForDecoratorMetadata(node) {
62987             if (node) {
62988                 switch (node.kind) {
62989                     case 179 /* IntersectionType */:
62990                     case 178 /* UnionType */:
62991                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
62992                     case 180 /* ConditionalType */:
62993                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
62994                     case 182 /* ParenthesizedType */:
62995                         return getEntityNameForDecoratorMetadata(node.type);
62996                     case 169 /* TypeReference */:
62997                         return node.typeName;
62998                 }
62999             }
63000         }
63001         function getEntityNameForDecoratorMetadataFromTypeList(types) {
63002             var commonEntityName;
63003             for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
63004                 var typeNode = types_20[_i];
63005                 while (typeNode.kind === 182 /* ParenthesizedType */) {
63006                     typeNode = typeNode.type; // Skip parens if need be
63007                 }
63008                 if (typeNode.kind === 137 /* NeverKeyword */) {
63009                     continue; // Always elide `never` from the union/intersection if possible
63010                 }
63011                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
63012                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
63013                 }
63014                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
63015                 if (!individualEntityName) {
63016                     // Individual is something like string number
63017                     // So it would be serialized to either that type or object
63018                     // Safe to return here
63019                     return undefined;
63020                 }
63021                 if (commonEntityName) {
63022                     // Note this is in sync with the transformation that happens for type node.
63023                     // Keep this in sync with serializeUnionOrIntersectionType
63024                     // Verify if they refer to same entity and is identifier
63025                     // return undefined if they dont match because we would emit object
63026                     if (!ts.isIdentifier(commonEntityName) ||
63027                         !ts.isIdentifier(individualEntityName) ||
63028                         commonEntityName.escapedText !== individualEntityName.escapedText) {
63029                         return undefined;
63030                     }
63031                 }
63032                 else {
63033                     commonEntityName = individualEntityName;
63034                 }
63035             }
63036             return commonEntityName;
63037         }
63038         function getParameterTypeNodeForDecoratorCheck(node) {
63039             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
63040             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
63041         }
63042         /** Check the decorators of a node */
63043         function checkDecorators(node) {
63044             if (!node.decorators) {
63045                 return;
63046             }
63047             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
63048             // checkGrammarDecorators.
63049             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
63050                 return;
63051             }
63052             if (!compilerOptions.experimentalDecorators) {
63053                 error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning);
63054             }
63055             var firstDecorator = node.decorators[0];
63056             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
63057             if (node.kind === 156 /* Parameter */) {
63058                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
63059             }
63060             if (compilerOptions.emitDecoratorMetadata) {
63061                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
63062                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
63063                 switch (node.kind) {
63064                     case 245 /* ClassDeclaration */:
63065                         var constructor = ts.getFirstConstructorWithBody(node);
63066                         if (constructor) {
63067                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
63068                                 var parameter = _a[_i];
63069                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63070                             }
63071                         }
63072                         break;
63073                     case 163 /* GetAccessor */:
63074                     case 164 /* SetAccessor */:
63075                         var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
63076                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
63077                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
63078                         break;
63079                     case 161 /* MethodDeclaration */:
63080                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
63081                             var parameter = _c[_b];
63082                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63083                         }
63084                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
63085                         break;
63086                     case 159 /* PropertyDeclaration */:
63087                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
63088                         break;
63089                     case 156 /* Parameter */:
63090                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
63091                         var containingSignature = node.parent;
63092                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
63093                             var parameter = _e[_d];
63094                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63095                         }
63096                         break;
63097                 }
63098             }
63099             ts.forEach(node.decorators, checkDecorator);
63100         }
63101         function checkFunctionDeclaration(node) {
63102             if (produceDiagnostics) {
63103                 checkFunctionOrMethodDeclaration(node);
63104                 checkGrammarForGenerator(node);
63105                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63106                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63107             }
63108         }
63109         function checkJSDocTypeAliasTag(node) {
63110             if (!node.typeExpression) {
63111                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
63112                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
63113             }
63114             if (node.name) {
63115                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
63116             }
63117             checkSourceElement(node.typeExpression);
63118         }
63119         function checkJSDocTemplateTag(node) {
63120             checkSourceElement(node.constraint);
63121             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
63122                 var tp = _a[_i];
63123                 checkSourceElement(tp);
63124             }
63125         }
63126         function checkJSDocTypeTag(node) {
63127             checkSourceElement(node.typeExpression);
63128         }
63129         function checkJSDocParameterTag(node) {
63130             checkSourceElement(node.typeExpression);
63131             if (!ts.getParameterSymbolFromJSDoc(node)) {
63132                 var decl = ts.getHostSignatureFromJSDoc(node);
63133                 // don't issue an error for invalid hosts -- just functions --
63134                 // and give a better error message when the host function mentions `arguments`
63135                 // but the tag doesn't have an array type
63136                 if (decl) {
63137                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
63138                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
63139                         return;
63140                     }
63141                     if (!containsArgumentsReference(decl)) {
63142                         if (ts.isQualifiedName(node.name)) {
63143                             error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left));
63144                         }
63145                         else {
63146                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
63147                         }
63148                     }
63149                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
63150                         node.typeExpression && node.typeExpression.type &&
63151                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
63152                         error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 153 /* QualifiedName */ ? node.name.right : node.name));
63153                     }
63154                 }
63155             }
63156         }
63157         function checkJSDocPropertyTag(node) {
63158             checkSourceElement(node.typeExpression);
63159         }
63160         function checkJSDocFunctionType(node) {
63161             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
63162                 reportImplicitAny(node, anyType);
63163             }
63164             checkSignatureDeclaration(node);
63165         }
63166         function checkJSDocImplementsTag(node) {
63167             var classLike = ts.getEffectiveJSDocHost(node);
63168             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63169                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63170             }
63171         }
63172         function checkJSDocAugmentsTag(node) {
63173             var classLike = ts.getEffectiveJSDocHost(node);
63174             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63175                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63176                 return;
63177             }
63178             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
63179             ts.Debug.assert(augmentsTags.length > 0);
63180             if (augmentsTags.length > 1) {
63181                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
63182             }
63183             var name = getIdentifierFromEntityNameExpression(node.class.expression);
63184             var extend = ts.getClassExtendsHeritageElement(classLike);
63185             if (extend) {
63186                 var className = getIdentifierFromEntityNameExpression(extend.expression);
63187                 if (className && name.escapedText !== className.escapedText) {
63188                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
63189                 }
63190             }
63191         }
63192         function getIdentifierFromEntityNameExpression(node) {
63193             switch (node.kind) {
63194                 case 75 /* Identifier */:
63195                     return node;
63196                 case 194 /* PropertyAccessExpression */:
63197                     return node.name;
63198                 default:
63199                     return undefined;
63200             }
63201         }
63202         function checkFunctionOrMethodDeclaration(node) {
63203             checkDecorators(node);
63204             checkSignatureDeclaration(node);
63205             var functionFlags = ts.getFunctionFlags(node);
63206             // Do not use hasDynamicName here, because that returns false for well known symbols.
63207             // We want to perform checkComputedPropertyName for all computed properties, including
63208             // well known symbols.
63209             if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
63210                 // This check will account for methods in class/interface declarations,
63211                 // as well as accessors in classes/object literals
63212                 checkComputedPropertyName(node.name);
63213             }
63214             if (!hasNonBindableDynamicName(node)) {
63215                 // first we want to check the local symbol that contain this declaration
63216                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
63217                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
63218                 var symbol = getSymbolOfNode(node);
63219                 var localSymbol = node.localSymbol || symbol;
63220                 // Since the javascript won't do semantic analysis like typescript,
63221                 // if the javascript file comes before the typescript file and both contain same name functions,
63222                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
63223                 var firstDeclaration = ts.find(localSymbol.declarations, 
63224                 // Get first non javascript function declaration
63225                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
63226                 // Only type check the symbol once
63227                 if (node === firstDeclaration) {
63228                     checkFunctionOrConstructorSymbol(localSymbol);
63229                 }
63230                 if (symbol.parent) {
63231                     // run check once for the first declaration
63232                     if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
63233                         // run check on export symbol to check that modifiers agree across all exported declarations
63234                         checkFunctionOrConstructorSymbol(symbol);
63235                     }
63236                 }
63237             }
63238             var body = node.kind === 160 /* MethodSignature */ ? undefined : node.body;
63239             checkSourceElement(body);
63240             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
63241             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
63242                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
63243                 // in an ambient context
63244                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
63245                     reportImplicitAny(node, anyType);
63246                 }
63247                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
63248                     // A generator with a body and no type annotation can still cause errors. It can error if the
63249                     // yielded values have no common supertype, or it can give an implicit any error if it has no
63250                     // yielded values. The only way to trigger these errors is to try checking its return type.
63251                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
63252                 }
63253             }
63254             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
63255             if (ts.isInJSFile(node)) {
63256                 var typeTag = ts.getJSDocTypeTag(node);
63257                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
63258                     error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
63259                 }
63260             }
63261         }
63262         function registerForUnusedIdentifiersCheck(node) {
63263             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
63264             if (produceDiagnostics) {
63265                 var sourceFile = ts.getSourceFileOfNode(node);
63266                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
63267                 if (!potentiallyUnusedIdentifiers) {
63268                     potentiallyUnusedIdentifiers = [];
63269                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
63270                 }
63271                 // TODO: GH#22580
63272                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
63273                 potentiallyUnusedIdentifiers.push(node);
63274             }
63275         }
63276         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
63277             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
63278                 var node = potentiallyUnusedIdentifiers_1[_i];
63279                 switch (node.kind) {
63280                     case 245 /* ClassDeclaration */:
63281                     case 214 /* ClassExpression */:
63282                         checkUnusedClassMembers(node, addDiagnostic);
63283                         checkUnusedTypeParameters(node, addDiagnostic);
63284                         break;
63285                     case 290 /* SourceFile */:
63286                     case 249 /* ModuleDeclaration */:
63287                     case 223 /* Block */:
63288                     case 251 /* CaseBlock */:
63289                     case 230 /* ForStatement */:
63290                     case 231 /* ForInStatement */:
63291                     case 232 /* ForOfStatement */:
63292                         checkUnusedLocalsAndParameters(node, addDiagnostic);
63293                         break;
63294                     case 162 /* Constructor */:
63295                     case 201 /* FunctionExpression */:
63296                     case 244 /* FunctionDeclaration */:
63297                     case 202 /* ArrowFunction */:
63298                     case 161 /* MethodDeclaration */:
63299                     case 163 /* GetAccessor */:
63300                     case 164 /* SetAccessor */:
63301                         if (node.body) { // Don't report unused parameters in overloads
63302                             checkUnusedLocalsAndParameters(node, addDiagnostic);
63303                         }
63304                         checkUnusedTypeParameters(node, addDiagnostic);
63305                         break;
63306                     case 160 /* MethodSignature */:
63307                     case 165 /* CallSignature */:
63308                     case 166 /* ConstructSignature */:
63309                     case 170 /* FunctionType */:
63310                     case 171 /* ConstructorType */:
63311                     case 247 /* TypeAliasDeclaration */:
63312                     case 246 /* InterfaceDeclaration */:
63313                         checkUnusedTypeParameters(node, addDiagnostic);
63314                         break;
63315                     case 181 /* InferType */:
63316                         checkUnusedInferTypeParameter(node, addDiagnostic);
63317                         break;
63318                     default:
63319                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
63320                 }
63321             }
63322         }
63323         function errorUnusedLocal(declaration, name, addDiagnostic) {
63324             var node = ts.getNameOfDeclaration(declaration) || declaration;
63325             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
63326             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
63327         }
63328         function isIdentifierThatStartsWithUnderscore(node) {
63329             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
63330         }
63331         function checkUnusedClassMembers(node, addDiagnostic) {
63332             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
63333                 var member = _a[_i];
63334                 switch (member.kind) {
63335                     case 161 /* MethodDeclaration */:
63336                     case 159 /* PropertyDeclaration */:
63337                     case 163 /* GetAccessor */:
63338                     case 164 /* SetAccessor */:
63339                         if (member.kind === 164 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
63340                             // Already would have reported an error on the getter.
63341                             break;
63342                         }
63343                         var symbol = getSymbolOfNode(member);
63344                         if (!symbol.isReferenced
63345                             && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
63346                             && !(member.flags & 8388608 /* Ambient */)) {
63347                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
63348                         }
63349                         break;
63350                     case 162 /* Constructor */:
63351                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
63352                             var parameter = _c[_b];
63353                             if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
63354                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
63355                             }
63356                         }
63357                         break;
63358                     case 167 /* IndexSignature */:
63359                     case 222 /* SemicolonClassElement */:
63360                         // Can't be private
63361                         break;
63362                     default:
63363                         ts.Debug.fail();
63364                 }
63365             }
63366         }
63367         function checkUnusedInferTypeParameter(node, addDiagnostic) {
63368             var typeParameter = node.typeParameter;
63369             if (isTypeParameterUnused(typeParameter)) {
63370                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
63371             }
63372         }
63373         function checkUnusedTypeParameters(node, addDiagnostic) {
63374             // Only report errors on the last declaration for the type parameter container;
63375             // this ensures that all uses have been accounted for.
63376             if (ts.last(getSymbolOfNode(node).declarations) !== node)
63377                 return;
63378             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
63379             var seenParentsWithEveryUnused = new ts.NodeSet();
63380             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
63381                 var typeParameter = typeParameters_3[_i];
63382                 if (!isTypeParameterUnused(typeParameter))
63383                     continue;
63384                 var name = ts.idText(typeParameter.name);
63385                 var parent = typeParameter.parent;
63386                 if (parent.kind !== 181 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
63387                     if (seenParentsWithEveryUnused.tryAdd(parent)) {
63388                         var range = ts.isJSDocTemplateTag(parent)
63389                             // Whole @template tag
63390                             ? ts.rangeOfNode(parent)
63391                             // Include the `<>` in the error message
63392                             : ts.rangeOfTypeParameters(parent.typeParameters);
63393                         var only = parent.typeParameters.length === 1;
63394                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
63395                         var arg0 = only ? name : undefined;
63396                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
63397                     }
63398                 }
63399                 else {
63400                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
63401                 }
63402             }
63403         }
63404         function isTypeParameterUnused(typeParameter) {
63405             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
63406         }
63407         function addToGroup(map, key, value, getKey) {
63408             var keyString = String(getKey(key));
63409             var group = map.get(keyString);
63410             if (group) {
63411                 group[1].push(value);
63412             }
63413             else {
63414                 map.set(keyString, [key, [value]]);
63415             }
63416         }
63417         function tryGetRootParameterDeclaration(node) {
63418             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
63419         }
63420         function isValidUnusedLocalDeclaration(declaration) {
63421             if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
63422                 return !!ts.findAncestor(declaration.parent, function (ancestor) {
63423                     return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
63424                         ts.isForOfStatement(ancestor) ? true : "quit";
63425                 });
63426             }
63427             return ts.isAmbientModule(declaration) ||
63428                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
63429         }
63430         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
63431             // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
63432             var unusedImports = ts.createMap();
63433             var unusedDestructures = ts.createMap();
63434             var unusedVariables = ts.createMap();
63435             nodeWithLocals.locals.forEach(function (local) {
63436                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
63437                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
63438                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
63439                     return;
63440                 }
63441                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
63442                     var declaration = _a[_i];
63443                     if (isValidUnusedLocalDeclaration(declaration)) {
63444                         continue;
63445                     }
63446                     if (isImportedDeclaration(declaration)) {
63447                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
63448                     }
63449                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
63450                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
63451                         var lastElement = ts.last(declaration.parent.elements);
63452                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
63453                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
63454                         }
63455                     }
63456                     else if (ts.isVariableDeclaration(declaration)) {
63457                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
63458                     }
63459                     else {
63460                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
63461                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
63462                         if (parameter && name) {
63463                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
63464                                 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
63465                             }
63466                         }
63467                         else {
63468                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
63469                         }
63470                     }
63471                 }
63472             });
63473             unusedImports.forEach(function (_a) {
63474                 var importClause = _a[0], unuseds = _a[1];
63475                 var importDecl = importClause.parent;
63476                 var nDeclarations = (importClause.name ? 1 : 0) +
63477                     (importClause.namedBindings ?
63478                         (importClause.namedBindings.kind === 256 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
63479                         : 0);
63480                 if (nDeclarations === unuseds.length) {
63481                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
63482                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
63483                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
63484                 }
63485                 else {
63486                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
63487                         var unused = unuseds_1[_i];
63488                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
63489                     }
63490                 }
63491             });
63492             unusedDestructures.forEach(function (_a) {
63493                 var bindingPattern = _a[0], bindingElements = _a[1];
63494                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
63495                 if (bindingPattern.elements.length === bindingElements.length) {
63496                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 242 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 243 /* VariableDeclarationList */) {
63497                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
63498                     }
63499                     else {
63500                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
63501                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
63502                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
63503                     }
63504                 }
63505                 else {
63506                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
63507                         var e = bindingElements_1[_i];
63508                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
63509                     }
63510                 }
63511             });
63512             unusedVariables.forEach(function (_a) {
63513                 var declarationList = _a[0], declarations = _a[1];
63514                 if (declarationList.declarations.length === declarations.length) {
63515                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
63516                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
63517                         : ts.createDiagnosticForNode(declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
63518                 }
63519                 else {
63520                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
63521                         var decl = declarations_5[_i];
63522                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
63523                     }
63524                 }
63525             });
63526         }
63527         function bindingNameText(name) {
63528             switch (name.kind) {
63529                 case 75 /* Identifier */:
63530                     return ts.idText(name);
63531                 case 190 /* ArrayBindingPattern */:
63532                 case 189 /* ObjectBindingPattern */:
63533                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
63534                 default:
63535                     return ts.Debug.assertNever(name);
63536             }
63537         }
63538         function isImportedDeclaration(node) {
63539             return node.kind === 255 /* ImportClause */ || node.kind === 258 /* ImportSpecifier */ || node.kind === 256 /* NamespaceImport */;
63540         }
63541         function importClauseFromImported(decl) {
63542             return decl.kind === 255 /* ImportClause */ ? decl : decl.kind === 256 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
63543         }
63544         function checkBlock(node) {
63545             // Grammar checking for SyntaxKind.Block
63546             if (node.kind === 223 /* Block */) {
63547                 checkGrammarStatementInAmbientContext(node);
63548             }
63549             if (ts.isFunctionOrModuleBlock(node)) {
63550                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
63551                 ts.forEach(node.statements, checkSourceElement);
63552                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
63553             }
63554             else {
63555                 ts.forEach(node.statements, checkSourceElement);
63556             }
63557             if (node.locals) {
63558                 registerForUnusedIdentifiersCheck(node);
63559             }
63560         }
63561         function checkCollisionWithArgumentsInGeneratedCode(node) {
63562             // no rest parameters \ declaration context \ overload - no codegen impact
63563             if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
63564                 return;
63565             }
63566             ts.forEach(node.parameters, function (p) {
63567                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
63568                     error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
63569                 }
63570             });
63571         }
63572         function needCollisionCheckForIdentifier(node, identifier, name) {
63573             if (!(identifier && identifier.escapedText === name)) {
63574                 return false;
63575             }
63576             if (node.kind === 159 /* PropertyDeclaration */ ||
63577                 node.kind === 158 /* PropertySignature */ ||
63578                 node.kind === 161 /* MethodDeclaration */ ||
63579                 node.kind === 160 /* MethodSignature */ ||
63580                 node.kind === 163 /* GetAccessor */ ||
63581                 node.kind === 164 /* SetAccessor */) {
63582                 // it is ok to have member named '_super' or '_this' - member access is always qualified
63583                 return false;
63584             }
63585             if (node.flags & 8388608 /* Ambient */) {
63586                 // ambient context - no codegen impact
63587                 return false;
63588             }
63589             var root = ts.getRootDeclaration(node);
63590             if (root.kind === 156 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
63591                 // just an overload - no codegen impact
63592                 return false;
63593             }
63594             return true;
63595         }
63596         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
63597         function checkIfThisIsCapturedInEnclosingScope(node) {
63598             ts.findAncestor(node, function (current) {
63599                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
63600                     var isDeclaration_1 = node.kind !== 75 /* Identifier */;
63601                     if (isDeclaration_1) {
63602                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
63603                     }
63604                     else {
63605                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
63606                     }
63607                     return true;
63608                 }
63609                 return false;
63610             });
63611         }
63612         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
63613             ts.findAncestor(node, function (current) {
63614                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
63615                     var isDeclaration_2 = node.kind !== 75 /* Identifier */;
63616                     if (isDeclaration_2) {
63617                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
63618                     }
63619                     else {
63620                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
63621                     }
63622                     return true;
63623                 }
63624                 return false;
63625             });
63626         }
63627         function checkWeakMapCollision(node) {
63628             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
63629             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
63630                 error(node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
63631             }
63632         }
63633         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
63634             // No need to check for require or exports for ES6 modules and later
63635             if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
63636                 return;
63637             }
63638             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
63639                 return;
63640             }
63641             // Uninstantiated modules shouldnt do this check
63642             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63643                 return;
63644             }
63645             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63646             var parent = getDeclarationContainer(node);
63647             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
63648                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
63649                 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
63650             }
63651         }
63652         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
63653             if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
63654                 return;
63655             }
63656             // Uninstantiated modules shouldnt do this check
63657             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63658                 return;
63659             }
63660             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63661             var parent = getDeclarationContainer(node);
63662             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
63663                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
63664                 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
63665             }
63666         }
63667         function checkVarDeclaredNamesNotShadowed(node) {
63668             // - ScriptBody : StatementList
63669             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63670             // also occurs in the VarDeclaredNames of StatementList.
63671             // - Block : { StatementList }
63672             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63673             // also occurs in the VarDeclaredNames of StatementList.
63674             // Variable declarations are hoisted to the top of their function scope. They can shadow
63675             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
63676             // by the binder as the declaration scope is different.
63677             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
63678             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
63679             // block declared value. this is fine for let, but not const.
63680             // Only consider declarations with initializers, uninitialized const declarations will not
63681             // step on a let/const variable.
63682             // Do not consider const and const declarations, as duplicate block-scoped declarations
63683             // are handled by the binder.
63684             // We are only looking for const declarations that step on let\const declarations from a
63685             // different scope. e.g.:
63686             //      {
63687             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
63688             //          const x = 0; // symbol for this declaration will be 'symbol'
63689             //      }
63690             // skip block-scoped variables and parameters
63691             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
63692                 return;
63693             }
63694             // skip variable declarations that don't have initializers
63695             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
63696             // so we'll always treat binding elements as initialized
63697             if (node.kind === 242 /* VariableDeclaration */ && !node.initializer) {
63698                 return;
63699             }
63700             var symbol = getSymbolOfNode(node);
63701             if (symbol.flags & 1 /* FunctionScopedVariable */) {
63702                 if (!ts.isIdentifier(node.name))
63703                     return ts.Debug.fail();
63704                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
63705                 if (localDeclarationSymbol &&
63706                     localDeclarationSymbol !== symbol &&
63707                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
63708                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
63709                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 243 /* VariableDeclarationList */);
63710                         var container = varDeclList.parent.kind === 225 /* VariableStatement */ && varDeclList.parent.parent
63711                             ? varDeclList.parent.parent
63712                             : undefined;
63713                         // names of block-scoped and function scoped variables can collide only
63714                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
63715                         var namesShareScope = container &&
63716                             (container.kind === 223 /* Block */ && ts.isFunctionLike(container.parent) ||
63717                                 container.kind === 250 /* ModuleBlock */ ||
63718                                 container.kind === 249 /* ModuleDeclaration */ ||
63719                                 container.kind === 290 /* SourceFile */);
63720                         // here we know that function scoped variable is shadowed by block scoped one
63721                         // if they are defined in the same scope - binder has already reported redeclaration error
63722                         // otherwise if variable has an initializer - show error that initialization will fail
63723                         // since LHS will be block scoped name instead of function scoped
63724                         if (!namesShareScope) {
63725                             var name = symbolToString(localDeclarationSymbol);
63726                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
63727                         }
63728                     }
63729                 }
63730             }
63731         }
63732         function convertAutoToAny(type) {
63733             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
63734         }
63735         // Check variable, parameter, or property declaration
63736         function checkVariableLikeDeclaration(node) {
63737             checkDecorators(node);
63738             if (!ts.isBindingElement(node)) {
63739                 checkSourceElement(node.type);
63740             }
63741             // JSDoc `function(string, string): string` syntax results in parameters with no name
63742             if (!node.name) {
63743                 return;
63744             }
63745             // For a computed property, just check the initializer and exit
63746             // Do not use hasDynamicName here, because that returns false for well known symbols.
63747             // We want to perform checkComputedPropertyName for all computed properties, including
63748             // well known symbols.
63749             if (node.name.kind === 154 /* ComputedPropertyName */) {
63750                 checkComputedPropertyName(node.name);
63751                 if (node.initializer) {
63752                     checkExpressionCached(node.initializer);
63753                 }
63754             }
63755             if (node.kind === 191 /* BindingElement */) {
63756                 if (node.parent.kind === 189 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
63757                     checkExternalEmitHelpers(node, 4 /* Rest */);
63758                 }
63759                 // check computed properties inside property names of binding elements
63760                 if (node.propertyName && node.propertyName.kind === 154 /* ComputedPropertyName */) {
63761                     checkComputedPropertyName(node.propertyName);
63762                 }
63763                 // check private/protected variable access
63764                 var parent = node.parent.parent;
63765                 var parentType = getTypeForBindingElementParent(parent);
63766                 var name = node.propertyName || node.name;
63767                 if (parentType && !ts.isBindingPattern(name)) {
63768                     var exprType = getLiteralTypeFromPropertyName(name);
63769                     if (isTypeUsableAsPropertyName(exprType)) {
63770                         var nameText = getPropertyNameFromType(exprType);
63771                         var property = getPropertyOfType(parentType, nameText);
63772                         if (property) {
63773                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
63774                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 102 /* SuperKeyword */, parentType, property);
63775                         }
63776                     }
63777                 }
63778             }
63779             // For a binding pattern, check contained binding elements
63780             if (ts.isBindingPattern(node.name)) {
63781                 if (node.name.kind === 190 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
63782                     checkExternalEmitHelpers(node, 512 /* Read */);
63783                 }
63784                 ts.forEach(node.name.elements, checkSourceElement);
63785             }
63786             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
63787             if (node.initializer && ts.getRootDeclaration(node).kind === 156 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
63788                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
63789                 return;
63790             }
63791             // For a binding pattern, validate the initializer and exit
63792             if (ts.isBindingPattern(node.name)) {
63793                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 231 /* ForInStatement */;
63794                 var needCheckWidenedType = node.name.elements.length === 0;
63795                 if (needCheckInitializer || needCheckWidenedType) {
63796                     // Don't validate for-in initializer as it is already an error
63797                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
63798                     if (needCheckInitializer) {
63799                         var initializerType = checkExpressionCached(node.initializer);
63800                         if (strictNullChecks && needCheckWidenedType) {
63801                             checkNonNullNonVoidType(initializerType, node);
63802                         }
63803                         else {
63804                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
63805                         }
63806                     }
63807                     // check the binding pattern with empty elements
63808                     if (needCheckWidenedType) {
63809                         if (ts.isArrayBindingPattern(node.name)) {
63810                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
63811                         }
63812                         else if (strictNullChecks) {
63813                             checkNonNullNonVoidType(widenedType, node);
63814                         }
63815                     }
63816                 }
63817                 return;
63818             }
63819             var symbol = getSymbolOfNode(node);
63820             var type = convertAutoToAny(getTypeOfSymbol(symbol));
63821             if (node === symbol.valueDeclaration) {
63822                 // Node is the primary declaration of the symbol, just validate the initializer
63823                 // Don't validate for-in initializer as it is already an error
63824                 var initializer = ts.getEffectiveInitializer(node);
63825                 if (initializer) {
63826                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
63827                         ts.isObjectLiteralExpression(initializer) &&
63828                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
63829                         ts.hasEntries(symbol.exports);
63830                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 231 /* ForInStatement */) {
63831                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
63832                     }
63833                 }
63834                 if (symbol.declarations.length > 1) {
63835                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
63836                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63837                     }
63838                 }
63839             }
63840             else {
63841                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
63842                 // initializer is consistent with type associated with the node
63843                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
63844                 if (type !== errorType && declarationType !== errorType &&
63845                     !isTypeIdenticalTo(type, declarationType) &&
63846                     !(symbol.flags & 67108864 /* Assignment */)) {
63847                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
63848                 }
63849                 if (node.initializer) {
63850                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
63851                 }
63852                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
63853                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63854                 }
63855             }
63856             if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */) {
63857                 // We know we don't have a binding pattern or computed name here
63858                 checkExportsOnMergedDeclarations(node);
63859                 if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
63860                     checkVarDeclaredNamesNotShadowed(node);
63861                 }
63862                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63863                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63864                 if (!compilerOptions.noEmit && languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
63865                     potentialWeakMapCollisions.push(node);
63866                 }
63867             }
63868         }
63869         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
63870             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
63871             var message = nextDeclaration.kind === 159 /* PropertyDeclaration */ || nextDeclaration.kind === 158 /* PropertySignature */
63872                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
63873                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
63874             var declName = ts.declarationNameToString(nextDeclarationName);
63875             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
63876             if (firstDeclaration) {
63877                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
63878             }
63879         }
63880         function areDeclarationFlagsIdentical(left, right) {
63881             if ((left.kind === 156 /* Parameter */ && right.kind === 242 /* VariableDeclaration */) ||
63882                 (left.kind === 242 /* VariableDeclaration */ && right.kind === 156 /* Parameter */)) {
63883                 // Differences in optionality between parameters and variables are allowed.
63884                 return true;
63885             }
63886             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
63887                 return false;
63888             }
63889             var interestingFlags = 8 /* Private */ |
63890                 16 /* Protected */ |
63891                 256 /* Async */ |
63892                 128 /* Abstract */ |
63893                 64 /* Readonly */ |
63894                 32 /* Static */;
63895             return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
63896         }
63897         function checkVariableDeclaration(node) {
63898             checkGrammarVariableDeclaration(node);
63899             return checkVariableLikeDeclaration(node);
63900         }
63901         function checkBindingElement(node) {
63902             checkGrammarBindingElement(node);
63903             return checkVariableLikeDeclaration(node);
63904         }
63905         function checkVariableStatement(node) {
63906             // Grammar checking
63907             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
63908                 checkGrammarForDisallowedLetOrConstStatement(node);
63909             ts.forEach(node.declarationList.declarations, checkSourceElement);
63910         }
63911         function checkExpressionStatement(node) {
63912             // Grammar checking
63913             checkGrammarStatementInAmbientContext(node);
63914             checkExpression(node.expression);
63915         }
63916         function checkIfStatement(node) {
63917             // Grammar checking
63918             checkGrammarStatementInAmbientContext(node);
63919             var type = checkTruthinessExpression(node.expression);
63920             checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
63921             checkSourceElement(node.thenStatement);
63922             if (node.thenStatement.kind === 224 /* EmptyStatement */) {
63923                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
63924             }
63925             checkSourceElement(node.elseStatement);
63926         }
63927         function checkTestingKnownTruthyCallableType(condExpr, body, type) {
63928             if (!strictNullChecks) {
63929                 return;
63930             }
63931             var testedNode = ts.isIdentifier(condExpr)
63932                 ? condExpr
63933                 : ts.isPropertyAccessExpression(condExpr)
63934                     ? condExpr.name
63935                     : undefined;
63936             if (!testedNode) {
63937                 return;
63938             }
63939             var possiblyFalsy = getFalsyFlags(type);
63940             if (possiblyFalsy) {
63941                 return;
63942             }
63943             // While it technically should be invalid for any known-truthy value
63944             // to be tested, we de-scope to functions unrefenced in the block as a
63945             // heuristic to identify the most common bugs. There are too many
63946             // false positives for values sourced from type definitions without
63947             // strictNullChecks otherwise.
63948             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
63949             if (callSignatures.length === 0) {
63950                 return;
63951             }
63952             var testedFunctionSymbol = getSymbolAtLocation(testedNode);
63953             if (!testedFunctionSymbol) {
63954                 return;
63955             }
63956             var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
63957                 if (ts.isIdentifier(childNode)) {
63958                     var childSymbol = getSymbolAtLocation(childNode);
63959                     if (childSymbol && childSymbol === testedFunctionSymbol) {
63960                         // If the test was a simple identifier, the above check is sufficient
63961                         if (ts.isIdentifier(condExpr)) {
63962                             return true;
63963                         }
63964                         // Otherwise we need to ensure the symbol is called on the same target
63965                         var testedExpression = testedNode.parent;
63966                         var childExpression = childNode.parent;
63967                         while (testedExpression && childExpression) {
63968                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
63969                                 testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) {
63970                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
63971                             }
63972                             if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
63973                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
63974                                     return false;
63975                                 }
63976                                 childExpression = childExpression.expression;
63977                                 testedExpression = testedExpression.expression;
63978                             }
63979                             else {
63980                                 return false;
63981                             }
63982                         }
63983                     }
63984                 }
63985                 return ts.forEachChild(childNode, check);
63986             });
63987             if (!functionIsUsedInBody) {
63988                 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
63989             }
63990         }
63991         function checkDoStatement(node) {
63992             // Grammar checking
63993             checkGrammarStatementInAmbientContext(node);
63994             checkSourceElement(node.statement);
63995             checkTruthinessExpression(node.expression);
63996         }
63997         function checkWhileStatement(node) {
63998             // Grammar checking
63999             checkGrammarStatementInAmbientContext(node);
64000             checkTruthinessExpression(node.expression);
64001             checkSourceElement(node.statement);
64002         }
64003         function checkTruthinessOfType(type, node) {
64004             if (type.flags & 16384 /* Void */) {
64005                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
64006             }
64007             return type;
64008         }
64009         function checkTruthinessExpression(node, checkMode) {
64010             return checkTruthinessOfType(checkExpression(node, checkMode), node);
64011         }
64012         function checkForStatement(node) {
64013             // Grammar checking
64014             if (!checkGrammarStatementInAmbientContext(node)) {
64015                 if (node.initializer && node.initializer.kind === 243 /* VariableDeclarationList */) {
64016                     checkGrammarVariableDeclarationList(node.initializer);
64017                 }
64018             }
64019             if (node.initializer) {
64020                 if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64021                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
64022                 }
64023                 else {
64024                     checkExpression(node.initializer);
64025                 }
64026             }
64027             if (node.condition)
64028                 checkTruthinessExpression(node.condition);
64029             if (node.incrementor)
64030                 checkExpression(node.incrementor);
64031             checkSourceElement(node.statement);
64032             if (node.locals) {
64033                 registerForUnusedIdentifiersCheck(node);
64034             }
64035         }
64036         function checkForOfStatement(node) {
64037             checkGrammarForInOrForOfStatement(node);
64038             if (node.awaitModifier) {
64039                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
64040                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
64041                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
64042                     checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
64043                 }
64044             }
64045             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
64046                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
64047                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
64048             }
64049             // Check the LHS and RHS
64050             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
64051             // via checkRightHandSideOfForOf.
64052             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
64053             // Then check that the RHS is assignable to it.
64054             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64055                 checkForInOrForOfVariableDeclaration(node);
64056             }
64057             else {
64058                 var varExpr = node.initializer;
64059                 var iteratedType = checkRightHandSideOfForOf(node);
64060                 // There may be a destructuring assignment on the left side
64061                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64062                     // iteratedType may be undefined. In this case, we still want to check the structure of
64063                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
64064                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
64065                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
64066                 }
64067                 else {
64068                     var leftType = checkExpression(varExpr);
64069                     checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access);
64070                     // iteratedType will be undefined if the rightType was missing properties/signatures
64071                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
64072                     // because we accessed properties from anyType, or it may have led to an error inside
64073                     // getElementTypeOfIterable.
64074                     if (iteratedType) {
64075                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
64076                     }
64077                 }
64078             }
64079             checkSourceElement(node.statement);
64080             if (node.locals) {
64081                 registerForUnusedIdentifiersCheck(node);
64082             }
64083         }
64084         function checkForInStatement(node) {
64085             // Grammar checking
64086             checkGrammarForInOrForOfStatement(node);
64087             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
64088             // TypeScript 1.0 spec (April 2014): 5.4
64089             // In a 'for-in' statement of the form
64090             // for (let VarDecl in Expr) Statement
64091             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
64092             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64093             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64094                 var variable = node.initializer.declarations[0];
64095                 if (variable && ts.isBindingPattern(variable.name)) {
64096                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64097                 }
64098                 checkForInOrForOfVariableDeclaration(node);
64099             }
64100             else {
64101                 // In a 'for-in' statement of the form
64102                 // for (Var in Expr) Statement
64103                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
64104                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64105                 var varExpr = node.initializer;
64106                 var leftType = checkExpression(varExpr);
64107                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64108                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64109                 }
64110                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
64111                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
64112                 }
64113                 else {
64114                     // run check only former check succeeded to avoid cascading errors
64115                     checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access);
64116                 }
64117             }
64118             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
64119             // in this case error about missing name is already reported - do not report extra one
64120             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
64121                 error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType));
64122             }
64123             checkSourceElement(node.statement);
64124             if (node.locals) {
64125                 registerForUnusedIdentifiersCheck(node);
64126             }
64127         }
64128         function checkForInOrForOfVariableDeclaration(iterationStatement) {
64129             var variableDeclarationList = iterationStatement.initializer;
64130             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
64131             if (variableDeclarationList.declarations.length >= 1) {
64132                 var decl = variableDeclarationList.declarations[0];
64133                 checkVariableDeclaration(decl);
64134             }
64135         }
64136         function checkRightHandSideOfForOf(statement) {
64137             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
64138             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
64139         }
64140         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
64141             if (isTypeAny(inputType)) {
64142                 return inputType;
64143             }
64144             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
64145         }
64146         /**
64147          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
64148          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
64149          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
64150          */
64151         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
64152             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
64153             if (inputType === neverType) {
64154                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
64155                 return undefined;
64156             }
64157             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
64158             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
64159             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
64160             // or higher, when inside of an async generator or for-await-if, or when
64161             // downlevelIteration is requested.
64162             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
64163                 // We only report errors for an invalid iterable type in ES2015 or higher.
64164                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
64165                 if (checkAssignability) {
64166                     if (iterationTypes) {
64167                         var diagnostic = use & 8 /* ForOfFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 :
64168                             use & 32 /* SpreadFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 :
64169                                 use & 64 /* DestructuringFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 :
64170                                     use & 16 /* YieldStarFlag */ ? ts.Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 :
64171                                         undefined;
64172                         if (diagnostic) {
64173                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
64174                         }
64175                     }
64176                 }
64177                 if (iterationTypes || uplevelIteration) {
64178                     return iterationTypes && iterationTypes.yieldType;
64179                 }
64180             }
64181             var arrayType = inputType;
64182             var reportedError = false;
64183             var hasStringConstituent = false;
64184             // If strings are permitted, remove any string-like constituents from the array type.
64185             // This allows us to find other non-string element types from an array unioned with
64186             // a string.
64187             if (use & 4 /* AllowsStringInputFlag */) {
64188                 if (arrayType.flags & 1048576 /* Union */) {
64189                     // After we remove all types that are StringLike, we will know if there was a string constituent
64190                     // based on whether the result of filter is a new array.
64191                     var arrayTypes = inputType.types;
64192                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
64193                     if (filteredTypes !== arrayTypes) {
64194                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
64195                     }
64196                 }
64197                 else if (arrayType.flags & 132 /* StringLike */) {
64198                     arrayType = neverType;
64199                 }
64200                 hasStringConstituent = arrayType !== inputType;
64201                 if (hasStringConstituent) {
64202                     if (languageVersion < 1 /* ES5 */) {
64203                         if (errorNode) {
64204                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
64205                             reportedError = true;
64206                         }
64207                     }
64208                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
64209                     // arrayOrStringType was a string.
64210                     if (arrayType.flags & 131072 /* Never */) {
64211                         return stringType;
64212                     }
64213                 }
64214             }
64215             if (!isArrayLikeType(arrayType)) {
64216                 if (errorNode && !reportedError) {
64217                     // Which error we report depends on whether we allow strings or if there was a
64218                     // string constituent. For example, if the input type is number | string, we
64219                     // want to say that number is not an array type. But if the input was just
64220                     // number and string input is allowed, we want to say that number is not an
64221                     // array type or a string type.
64222                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
64223                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
64224                         ? downlevelIteration
64225                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
64226                             : yieldType
64227                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64228                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
64229                         : downlevelIteration
64230                             ? [ts.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]
64231                             : yieldType
64232                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64233                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
64234                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
64235                 }
64236                 return hasStringConstituent ? stringType : undefined;
64237             }
64238             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
64239             if (hasStringConstituent && arrayElementType) {
64240                 // This is just an optimization for the case where arrayOrStringType is string | string[]
64241                 if (arrayElementType.flags & 132 /* StringLike */) {
64242                     return stringType;
64243                 }
64244                 return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
64245             }
64246             return arrayElementType;
64247         }
64248         /**
64249          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
64250          */
64251         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
64252             if (isTypeAny(inputType)) {
64253                 return undefined;
64254             }
64255             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
64256             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
64257         }
64258         function createIterationTypes(yieldType, returnType, nextType) {
64259             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
64260             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
64261             // as it is combined via `getIntersectionType` when merging iteration types.
64262             if (yieldType === void 0) { yieldType = neverType; }
64263             if (returnType === void 0) { returnType = neverType; }
64264             if (nextType === void 0) { nextType = unknownType; }
64265             // Use the cache only for intrinsic types to keep it small as they are likely to be
64266             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
64267             // are also cached on the type they are requested for, so we shouldn't need to maintain
64268             // the cache for less-frequently used types.
64269             if (yieldType.flags & 67359327 /* Intrinsic */ &&
64270                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
64271                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
64272                 var id = getTypeListId([yieldType, returnType, nextType]);
64273                 var iterationTypes = iterationTypesCache.get(id);
64274                 if (!iterationTypes) {
64275                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
64276                     iterationTypesCache.set(id, iterationTypes);
64277                 }
64278                 return iterationTypes;
64279             }
64280             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
64281         }
64282         /**
64283          * Combines multiple `IterationTypes` records.
64284          *
64285          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
64286          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
64287          * for the combined iteration types.
64288          */
64289         function combineIterationTypes(array) {
64290             var yieldTypes;
64291             var returnTypes;
64292             var nextTypes;
64293             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
64294                 var iterationTypes = array_10[_i];
64295                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
64296                     continue;
64297                 }
64298                 if (iterationTypes === anyIterationTypes) {
64299                     return anyIterationTypes;
64300                 }
64301                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
64302                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64303                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
64304             }
64305             if (yieldTypes || returnTypes || nextTypes) {
64306                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
64307             }
64308             return noIterationTypes;
64309         }
64310         function getCachedIterationTypes(type, cacheKey) {
64311             return type[cacheKey];
64312         }
64313         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
64314             return type[cacheKey] = cachedTypes;
64315         }
64316         /**
64317          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
64318          *
64319          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
64320          *
64321          * Another thing to note is that at any step of this process, we could run into a dead end,
64322          * meaning either the property is missing, or we run into the anyType. If either of these things
64323          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
64324          * is missing, and the previous step did not result in `any`, then we also give an error if the
64325          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
64326          * type.
64327          *
64328          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
64329          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
64330          * method.
64331          *
64332          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
64333          *
64334          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
64335          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
64336          */
64337         function getIterationTypesOfIterable(type, use, errorNode) {
64338             if (isTypeAny(type)) {
64339                 return anyIterationTypes;
64340             }
64341             if (!(type.flags & 1048576 /* Union */)) {
64342                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
64343                 if (iterationTypes_1 === noIterationTypes) {
64344                     if (errorNode) {
64345                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64346                     }
64347                     return undefined;
64348                 }
64349                 return iterationTypes_1;
64350             }
64351             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
64352             var cachedTypes = getCachedIterationTypes(type, cacheKey);
64353             if (cachedTypes)
64354                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
64355             var allIterationTypes;
64356             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
64357                 var constituent = _a[_i];
64358                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
64359                 if (iterationTypes_2 === noIterationTypes) {
64360                     if (errorNode) {
64361                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64362                         errorNode = undefined;
64363                     }
64364                 }
64365                 else {
64366                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
64367                 }
64368             }
64369             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
64370             setCachedIterationTypes(type, cacheKey, iterationTypes);
64371             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64372         }
64373         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
64374             if (iterationTypes === noIterationTypes)
64375                 return noIterationTypes;
64376             if (iterationTypes === anyIterationTypes)
64377                 return anyIterationTypes;
64378             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
64379             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
64380         }
64381         /**
64382          * Gets the *yield*, *return*, and *next* types from a non-union type.
64383          *
64384          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
64385          * returned to indicate to the caller that it should report an error. Otherwise, an
64386          * `IterationTypes` record is returned.
64387          *
64388          * NOTE: You probably don't want to call this directly and should be calling
64389          * `getIterationTypesOfIterable` instead.
64390          */
64391         function getIterationTypesOfIterableWorker(type, use, errorNode) {
64392             if (isTypeAny(type)) {
64393                 return anyIterationTypes;
64394             }
64395             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64396                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
64397                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
64398                 if (iterationTypes) {
64399                     return iterationTypes;
64400                 }
64401             }
64402             if (use & 1 /* AllowsSyncIterablesFlag */) {
64403                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
64404                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
64405                 if (iterationTypes) {
64406                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64407                         // for a sync iterable in an async context, only use the cached types if they are valid.
64408                         if (iterationTypes !== noIterationTypes) {
64409                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
64410                         }
64411                     }
64412                     else {
64413                         return iterationTypes;
64414                     }
64415                 }
64416             }
64417             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64418                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
64419                 if (iterationTypes !== noIterationTypes) {
64420                     return iterationTypes;
64421                 }
64422             }
64423             if (use & 1 /* AllowsSyncIterablesFlag */) {
64424                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
64425                 if (iterationTypes !== noIterationTypes) {
64426                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64427                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
64428                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
64429                             : noIterationTypes);
64430                     }
64431                     else {
64432                         return iterationTypes;
64433                     }
64434                 }
64435             }
64436             return noIterationTypes;
64437         }
64438         /**
64439          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
64440          * `AsyncIterable`-like type from the cache.
64441          *
64442          * NOTE: You probably don't want to call this directly and should be calling
64443          * `getIterationTypesOfIterable` instead.
64444          */
64445         function getIterationTypesOfIterableCached(type, resolver) {
64446             return getCachedIterationTypes(type, resolver.iterableCacheKey);
64447         }
64448         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
64449             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
64450                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
64451             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
64452         }
64453         /**
64454          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64455          * type from from common heuristics.
64456          *
64457          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64458          * returned. If we found iteration types, an `IterationTypes` record is returned.
64459          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64460          * exhaustive analysis.
64461          *
64462          * NOTE: You probably don't want to call this directly and should be calling
64463          * `getIterationTypesOfIterable` instead.
64464          */
64465         function getIterationTypesOfIterableFast(type, resolver) {
64466             // As an optimization, if the type is an instantiation of one of the following global types, then
64467             // just grab its related type argument:
64468             // - `Iterable<T>` or `AsyncIterable<T>`
64469             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64470             var globalType;
64471             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
64472                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
64473                 var yieldType = getTypeArguments(type)[0];
64474                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
64475                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
64476                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
64477                 // different definitions.
64478                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
64479                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64480             }
64481             // As an optimization, if the type is an instantiation of the following global type, then
64482             // just grab its related type arguments:
64483             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64484             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64485                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64486                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64487             }
64488         }
64489         /**
64490          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64491          * type from its members.
64492          *
64493          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64494          * record is returned. Otherwise, `noIterationTypes` is returned.
64495          *
64496          * NOTE: You probably don't want to call this directly and should be calling
64497          * `getIterationTypesOfIterable` instead.
64498          */
64499         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
64500             var _a;
64501             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
64502             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
64503             if (isTypeAny(methodType)) {
64504                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
64505             }
64506             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
64507             if (!ts.some(signatures)) {
64508                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
64509             }
64510             var iteratorType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
64511             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
64512             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
64513         }
64514         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
64515             var message = allowAsyncIterables
64516                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
64517                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
64518             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
64519         }
64520         /**
64521          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
64522          *
64523          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64524          * record is returned. Otherwise, `undefined` is returned.
64525          */
64526         function getIterationTypesOfIterator(type, resolver, errorNode) {
64527             if (isTypeAny(type)) {
64528                 return anyIterationTypes;
64529             }
64530             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
64531                 getIterationTypesOfIteratorFast(type, resolver) ||
64532                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
64533             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64534         }
64535         /**
64536          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64537          * cache.
64538          *
64539          * NOTE: You probably don't want to call this directly and should be calling
64540          * `getIterationTypesOfIterator` instead.
64541          */
64542         function getIterationTypesOfIteratorCached(type, resolver) {
64543             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
64544         }
64545         /**
64546          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64547          * cache or from common heuristics.
64548          *
64549          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64550          * returned. If we found iteration types, an `IterationTypes` record is returned.
64551          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64552          * exhaustive analysis.
64553          *
64554          * NOTE: You probably don't want to call this directly and should be calling
64555          * `getIterationTypesOfIterator` instead.
64556          */
64557         function getIterationTypesOfIteratorFast(type, resolver) {
64558             // As an optimization, if the type is an instantiation of one of the following global types,
64559             // then just grab its related type argument:
64560             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64561             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
64562             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64563             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
64564             if (isReferenceToType(type, globalType)) {
64565                 var yieldType = getTypeArguments(type)[0];
64566                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
64567                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
64568                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
64569                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
64570                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
64571                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
64572                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64573             }
64574             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
64575                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64576                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64577                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64578             }
64579         }
64580         function isIteratorResult(type, kind) {
64581             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
64582             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
64583             // > If the end was not reached `done` is `false` and a value is available.
64584             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
64585             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
64586             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
64587         }
64588         function isYieldIteratorResult(type) {
64589             return isIteratorResult(type, 0 /* Yield */);
64590         }
64591         function isReturnIteratorResult(type) {
64592             return isIteratorResult(type, 1 /* Return */);
64593         }
64594         /**
64595          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
64596          *
64597          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
64598          * returned to indicate to the caller that it should handle the error. Otherwise, an
64599          * `IterationTypes` record is returned.
64600          */
64601         function getIterationTypesOfIteratorResult(type) {
64602             if (isTypeAny(type)) {
64603                 return anyIterationTypes;
64604             }
64605             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
64606             if (cachedTypes) {
64607                 return cachedTypes;
64608             }
64609             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
64610             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
64611             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
64612                 var yieldType_1 = getTypeArguments(type)[0];
64613                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
64614             }
64615             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
64616                 var returnType_1 = getTypeArguments(type)[0];
64617                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
64618             }
64619             // Choose any constituents that can produce the requested iteration type.
64620             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
64621             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
64622             var returnIteratorResult = filterType(type, isReturnIteratorResult);
64623             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
64624             if (!yieldType && !returnType) {
64625                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
64626             }
64627             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
64628             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
64629             // > `value` property may be absent from the conforming object if it does not inherit an explicit
64630             // > `value` property.
64631             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
64632         }
64633         /**
64634          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
64635          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
64636          *
64637          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64638          * record is returned. Otherwise, we return `undefined`.
64639          */
64640         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
64641             var method = getPropertyOfType(type, methodName);
64642             // Ignore 'return' or 'throw' if they are missing.
64643             if (!method && methodName !== "next") {
64644                 return undefined;
64645             }
64646             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
64647                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
64648                 : undefined;
64649             if (isTypeAny(methodType)) {
64650                 // `return()` and `throw()` don't provide a *next* type.
64651                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
64652             }
64653             // Both async and non-async iterators *must* have a `next` method.
64654             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
64655             if (methodSignatures.length === 0) {
64656                 if (errorNode) {
64657                     var diagnostic = methodName === "next"
64658                         ? resolver.mustHaveANextMethodDiagnostic
64659                         : resolver.mustBeAMethodDiagnostic;
64660                     error(errorNode, diagnostic, methodName);
64661                 }
64662                 return methodName === "next" ? anyIterationTypes : undefined;
64663             }
64664             // Extract the first parameter and return type of each signature.
64665             var methodParameterTypes;
64666             var methodReturnTypes;
64667             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
64668                 var signature = methodSignatures_1[_i];
64669                 if (methodName !== "throw" && ts.some(signature.parameters)) {
64670                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
64671                 }
64672                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
64673             }
64674             // Resolve the *next* or *return* type from the first parameter of a `next()` or
64675             // `return()` method, respectively.
64676             var returnTypes;
64677             var nextType;
64678             if (methodName !== "throw") {
64679                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
64680                 if (methodName === "next") {
64681                     // The value of `next(value)` is *not* awaited by async generators
64682                     nextType = methodParameterType;
64683                 }
64684                 else if (methodName === "return") {
64685                     // The value of `return(value)` *is* awaited by async generators
64686                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
64687                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
64688                 }
64689             }
64690             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
64691             var yieldType;
64692             var methodReturnType = methodReturnTypes ? getUnionType(methodReturnTypes, 2 /* Subtype */) : neverType;
64693             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
64694             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
64695             if (iterationTypes === noIterationTypes) {
64696                 if (errorNode) {
64697                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
64698                 }
64699                 yieldType = anyType;
64700                 returnTypes = ts.append(returnTypes, anyType);
64701             }
64702             else {
64703                 yieldType = iterationTypes.yieldType;
64704                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64705             }
64706             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
64707         }
64708         /**
64709          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
64710          * type from its members.
64711          *
64712          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64713          * record is returned. Otherwise, `noIterationTypes` is returned.
64714          *
64715          * NOTE: You probably don't want to call this directly and should be calling
64716          * `getIterationTypesOfIterator` instead.
64717          */
64718         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
64719             var iterationTypes = combineIterationTypes([
64720                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
64721                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
64722                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
64723             ]);
64724             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
64725         }
64726         /**
64727          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
64728          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
64729          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
64730          */
64731         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
64732             if (isTypeAny(returnType)) {
64733                 return undefined;
64734             }
64735             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
64736             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
64737         }
64738         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
64739             if (isTypeAny(type)) {
64740                 return anyIterationTypes;
64741             }
64742             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
64743             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
64744             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
64745                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
64746         }
64747         function checkBreakOrContinueStatement(node) {
64748             // Grammar checking
64749             if (!checkGrammarStatementInAmbientContext(node))
64750                 checkGrammarBreakOrContinueStatement(node);
64751             // TODO: Check that target label is valid
64752         }
64753         function unwrapReturnType(returnType, functionFlags) {
64754             var _a, _b;
64755             var isGenerator = !!(functionFlags & 1 /* Generator */);
64756             var isAsync = !!(functionFlags & 2 /* Async */);
64757             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
64758                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
64759                     returnType;
64760         }
64761         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
64762             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
64763             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
64764         }
64765         function checkReturnStatement(node) {
64766             var _a;
64767             // Grammar checking
64768             if (checkGrammarStatementInAmbientContext(node)) {
64769                 return;
64770             }
64771             var func = ts.getContainingFunction(node);
64772             if (!func) {
64773                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
64774                 return;
64775             }
64776             var signature = getSignatureFromDeclaration(func);
64777             var returnType = getReturnTypeOfSignature(signature);
64778             var functionFlags = ts.getFunctionFlags(func);
64779             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
64780                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
64781                 if (func.kind === 164 /* SetAccessor */) {
64782                     if (node.expression) {
64783                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
64784                     }
64785                 }
64786                 else if (func.kind === 162 /* Constructor */) {
64787                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
64788                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
64789                     }
64790                 }
64791                 else if (getReturnTypeFromAnnotation(func)) {
64792                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
64793                     var unwrappedExprType = functionFlags & 2 /* Async */
64794                         ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)
64795                         : exprType;
64796                     if (unwrappedReturnType) {
64797                         // If the function has a return type, but promisedType is
64798                         // undefined, an error will be reported in checkAsyncFunctionReturnType
64799                         // so we don't need to report one here.
64800                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
64801                     }
64802                 }
64803             }
64804             else if (func.kind !== 162 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
64805                 // The function has a return type, but the return statement doesn't have an expression.
64806                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
64807             }
64808         }
64809         function checkWithStatement(node) {
64810             // Grammar checking for withStatement
64811             if (!checkGrammarStatementInAmbientContext(node)) {
64812                 if (node.flags & 32768 /* AwaitContext */) {
64813                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
64814                 }
64815             }
64816             checkExpression(node.expression);
64817             var sourceFile = ts.getSourceFileOfNode(node);
64818             if (!hasParseDiagnostics(sourceFile)) {
64819                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
64820                 var end = node.statement.pos;
64821                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
64822             }
64823         }
64824         function checkSwitchStatement(node) {
64825             // Grammar checking
64826             checkGrammarStatementInAmbientContext(node);
64827             var firstDefaultClause;
64828             var hasDuplicateDefaultClause = false;
64829             var expressionType = checkExpression(node.expression);
64830             var expressionIsLiteral = isLiteralType(expressionType);
64831             ts.forEach(node.caseBlock.clauses, function (clause) {
64832                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
64833                 if (clause.kind === 278 /* DefaultClause */ && !hasDuplicateDefaultClause) {
64834                     if (firstDefaultClause === undefined) {
64835                         firstDefaultClause = clause;
64836                     }
64837                     else {
64838                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
64839                         hasDuplicateDefaultClause = true;
64840                     }
64841                 }
64842                 if (produceDiagnostics && clause.kind === 277 /* CaseClause */) {
64843                     // TypeScript 1.0 spec (April 2014): 5.9
64844                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
64845                     // to or from the type of the 'switch' expression.
64846                     var caseType = checkExpression(clause.expression);
64847                     var caseIsLiteral = isLiteralType(caseType);
64848                     var comparedExpressionType = expressionType;
64849                     if (!caseIsLiteral || !expressionIsLiteral) {
64850                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
64851                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
64852                     }
64853                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
64854                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
64855                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
64856                     }
64857                 }
64858                 ts.forEach(clause.statements, checkSourceElement);
64859                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
64860                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
64861                 }
64862             });
64863             if (node.caseBlock.locals) {
64864                 registerForUnusedIdentifiersCheck(node.caseBlock);
64865             }
64866         }
64867         function checkLabeledStatement(node) {
64868             // Grammar checking
64869             if (!checkGrammarStatementInAmbientContext(node)) {
64870                 ts.findAncestor(node.parent, function (current) {
64871                     if (ts.isFunctionLike(current)) {
64872                         return "quit";
64873                     }
64874                     if (current.kind === 238 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
64875                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
64876                         return true;
64877                     }
64878                     return false;
64879                 });
64880             }
64881             // ensure that label is unique
64882             checkSourceElement(node.statement);
64883         }
64884         function checkThrowStatement(node) {
64885             // Grammar checking
64886             if (!checkGrammarStatementInAmbientContext(node)) {
64887                 if (node.expression === undefined) {
64888                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
64889                 }
64890             }
64891             if (node.expression) {
64892                 checkExpression(node.expression);
64893             }
64894         }
64895         function checkTryStatement(node) {
64896             // Grammar checking
64897             checkGrammarStatementInAmbientContext(node);
64898             checkBlock(node.tryBlock);
64899             var catchClause = node.catchClause;
64900             if (catchClause) {
64901                 // Grammar checking
64902                 if (catchClause.variableDeclaration) {
64903                     if (catchClause.variableDeclaration.type) {
64904                         grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
64905                     }
64906                     else if (catchClause.variableDeclaration.initializer) {
64907                         grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
64908                     }
64909                     else {
64910                         var blockLocals_1 = catchClause.block.locals;
64911                         if (blockLocals_1) {
64912                             ts.forEachKey(catchClause.locals, function (caughtName) {
64913                                 var blockLocal = blockLocals_1.get(caughtName);
64914                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
64915                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
64916                                 }
64917                             });
64918                         }
64919                     }
64920                 }
64921                 checkBlock(catchClause.block);
64922             }
64923             if (node.finallyBlock) {
64924                 checkBlock(node.finallyBlock);
64925             }
64926         }
64927         function checkIndexConstraints(type) {
64928             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
64929             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
64930             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
64931             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
64932             if (stringIndexType || numberIndexType) {
64933                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
64934                     var propType = getTypeOfSymbol(prop);
64935                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64936                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64937                 });
64938                 var classDeclaration = type.symbol.valueDeclaration;
64939                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
64940                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
64941                         var member = _a[_i];
64942                         // Only process instance properties with computed names here.
64943                         // Static properties cannot be in conflict with indexers,
64944                         // and properties with literal names were already checked.
64945                         if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
64946                             var symbol = getSymbolOfNode(member);
64947                             var propType = getTypeOfSymbol(symbol);
64948                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64949                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64950                         }
64951                     }
64952                 }
64953             }
64954             var errorNode;
64955             if (stringIndexType && numberIndexType) {
64956                 errorNode = declaredNumberIndexer || declaredStringIndexer;
64957                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
64958                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
64959                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
64960                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
64961                 }
64962             }
64963             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
64964                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
64965             }
64966             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
64967                 // ESSymbol properties apply to neither string nor numeric indexers.
64968                 if (!indexType || ts.isKnownSymbol(prop)) {
64969                     return;
64970                 }
64971                 var propDeclaration = prop.valueDeclaration;
64972                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
64973                 if (name && ts.isPrivateIdentifier(name)) {
64974                     return;
64975                 }
64976                 // index is numeric and property name is not valid numeric literal
64977                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
64978                     return;
64979                 }
64980                 // perform property check if property or indexer is declared in 'type'
64981                 // this allows us to rule out cases when both property and indexer are inherited from the base class
64982                 var errorNode;
64983                 if (propDeclaration && name &&
64984                     (propDeclaration.kind === 209 /* BinaryExpression */ ||
64985                         name.kind === 154 /* ComputedPropertyName */ ||
64986                         prop.parent === containingType.symbol)) {
64987                     errorNode = propDeclaration;
64988                 }
64989                 else if (indexDeclaration) {
64990                     errorNode = indexDeclaration;
64991                 }
64992                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
64993                     // for interfaces property and indexer might be inherited from different bases
64994                     // check if any base class already has both property and indexer.
64995                     // check should be performed only if 'type' is the first type that brings property\indexer together
64996                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
64997                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
64998                 }
64999                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
65000                     var errorMessage = indexKind === 0 /* String */
65001                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
65002                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
65003                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
65004                 }
65005             }
65006         }
65007         function checkTypeNameIsReserved(name, message) {
65008             // TS 1.0 spec (April 2014): 3.6.1
65009             // The predefined type keywords are reserved and cannot be used as names of user defined types.
65010             switch (name.escapedText) {
65011                 case "any":
65012                 case "unknown":
65013                 case "number":
65014                 case "bigint":
65015                 case "boolean":
65016                 case "string":
65017                 case "symbol":
65018                 case "void":
65019                 case "object":
65020                     error(name, message, name.escapedText);
65021             }
65022         }
65023         /**
65024          * The name cannot be used as 'Object' of user defined types with special target.
65025          */
65026         function checkClassNameCollisionWithObject(name) {
65027             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
65028                 && moduleKind < ts.ModuleKind.ES2015) {
65029                 error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494
65030             }
65031         }
65032         /**
65033          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
65034          */
65035         function checkTypeParameters(typeParameterDeclarations) {
65036             if (typeParameterDeclarations) {
65037                 var seenDefault = false;
65038                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
65039                     var node = typeParameterDeclarations[i];
65040                     checkTypeParameter(node);
65041                     if (produceDiagnostics) {
65042                         if (node.default) {
65043                             seenDefault = true;
65044                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
65045                         }
65046                         else if (seenDefault) {
65047                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
65048                         }
65049                         for (var j = 0; j < i; j++) {
65050                             if (typeParameterDeclarations[j].symbol === node.symbol) {
65051                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
65052                             }
65053                         }
65054                     }
65055                 }
65056             }
65057         }
65058         /** Check that type parameter defaults only reference previously declared type parameters */
65059         function checkTypeParametersNotReferenced(root, typeParameters, index) {
65060             visit(root);
65061             function visit(node) {
65062                 if (node.kind === 169 /* TypeReference */) {
65063                     var type = getTypeFromTypeReference(node);
65064                     if (type.flags & 262144 /* TypeParameter */) {
65065                         for (var i = index; i < typeParameters.length; i++) {
65066                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
65067                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
65068                             }
65069                         }
65070                     }
65071                 }
65072                 ts.forEachChild(node, visit);
65073             }
65074         }
65075         /** Check that type parameter lists are identical across multiple declarations */
65076         function checkTypeParameterListsIdentical(symbol) {
65077             if (symbol.declarations.length === 1) {
65078                 return;
65079             }
65080             var links = getSymbolLinks(symbol);
65081             if (!links.typeParametersChecked) {
65082                 links.typeParametersChecked = true;
65083                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
65084                 if (declarations.length <= 1) {
65085                     return;
65086                 }
65087                 var type = getDeclaredTypeOfSymbol(symbol);
65088                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
65089                     // Report an error on every conflicting declaration.
65090                     var name = symbolToString(symbol);
65091                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
65092                         var declaration = declarations_6[_i];
65093                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
65094                     }
65095                 }
65096             }
65097         }
65098         function areTypeParametersIdentical(declarations, targetParameters) {
65099             var maxTypeArgumentCount = ts.length(targetParameters);
65100             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
65101             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
65102                 var declaration = declarations_7[_i];
65103                 // If this declaration has too few or too many type parameters, we report an error
65104                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
65105                 var numTypeParameters = sourceParameters.length;
65106                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
65107                     return false;
65108                 }
65109                 for (var i = 0; i < numTypeParameters; i++) {
65110                     var source = sourceParameters[i];
65111                     var target = targetParameters[i];
65112                     // If the type parameter node does not have the same as the resolved type
65113                     // parameter at this position, we report an error.
65114                     if (source.name.escapedText !== target.symbol.escapedName) {
65115                         return false;
65116                     }
65117                     // If the type parameter node does not have an identical constraint as the resolved
65118                     // type parameter at this position, we report an error.
65119                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
65120                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
65121                     var targetConstraint = getConstraintOfTypeParameter(target);
65122                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
65123                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
65124                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
65125                         return false;
65126                     }
65127                     // If the type parameter node has a default and it is not identical to the default
65128                     // for the type parameter at this position, we report an error.
65129                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
65130                     var targetDefault = getDefaultFromTypeParameter(target);
65131                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
65132                         return false;
65133                     }
65134                 }
65135             }
65136             return true;
65137         }
65138         function checkClassExpression(node) {
65139             checkClassLikeDeclaration(node);
65140             checkNodeDeferred(node);
65141             return getTypeOfSymbol(getSymbolOfNode(node));
65142         }
65143         function checkClassExpressionDeferred(node) {
65144             ts.forEach(node.members, checkSourceElement);
65145             registerForUnusedIdentifiersCheck(node);
65146         }
65147         function checkClassDeclaration(node) {
65148             if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
65149                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
65150             }
65151             checkClassLikeDeclaration(node);
65152             ts.forEach(node.members, checkSourceElement);
65153             registerForUnusedIdentifiersCheck(node);
65154         }
65155         function checkClassLikeDeclaration(node) {
65156             checkGrammarClassLikeDeclaration(node);
65157             checkDecorators(node);
65158             if (node.name) {
65159                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
65160                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65161                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65162                 if (!(node.flags & 8388608 /* Ambient */)) {
65163                     checkClassNameCollisionWithObject(node.name);
65164                 }
65165             }
65166             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
65167             checkExportsOnMergedDeclarations(node);
65168             var symbol = getSymbolOfNode(node);
65169             var type = getDeclaredTypeOfSymbol(symbol);
65170             var typeWithThis = getTypeWithThisArgument(type);
65171             var staticType = getTypeOfSymbol(symbol);
65172             checkTypeParameterListsIdentical(symbol);
65173             checkClassForDuplicateDeclarations(node);
65174             // Only check for reserved static identifiers on non-ambient context.
65175             if (!(node.flags & 8388608 /* Ambient */)) {
65176                 checkClassForStaticPropertyNameConflicts(node);
65177             }
65178             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
65179             if (baseTypeNode) {
65180                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65181                 if (languageVersion < 2 /* ES2015 */) {
65182                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
65183                 }
65184                 // check both @extends and extends if both are specified.
65185                 var extendsNode = ts.getClassExtendsHeritageElement(node);
65186                 if (extendsNode && extendsNode !== baseTypeNode) {
65187                     checkExpression(extendsNode.expression);
65188                 }
65189                 var baseTypes = getBaseTypes(type);
65190                 if (baseTypes.length && produceDiagnostics) {
65191                     var baseType_1 = baseTypes[0];
65192                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
65193                     var staticBaseType = getApparentType(baseConstructorType);
65194                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
65195                     checkSourceElement(baseTypeNode.expression);
65196                     if (ts.some(baseTypeNode.typeArguments)) {
65197                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65198                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
65199                             var constructor = _a[_i];
65200                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
65201                                 break;
65202                             }
65203                         }
65204                     }
65205                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
65206                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65207                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
65208                     }
65209                     else {
65210                         // Report static side error only when instance type is assignable
65211                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
65212                     }
65213                     if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
65214                         error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
65215                     }
65216                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
65217                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
65218                         // that all instantiated base constructor signatures return the same type.
65219                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
65220                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
65221                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
65222                         }
65223                     }
65224                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
65225                 }
65226             }
65227             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
65228             if (implementedTypeNodes) {
65229                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
65230                     var typeRefNode = implementedTypeNodes_1[_b];
65231                     if (!ts.isEntityNameExpression(typeRefNode.expression)) {
65232                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
65233                     }
65234                     checkTypeReferenceNode(typeRefNode);
65235                     if (produceDiagnostics) {
65236                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
65237                         if (t !== errorType) {
65238                             if (isValidBaseType(t)) {
65239                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
65240                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
65241                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
65242                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
65243                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65244                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
65245                                 }
65246                             }
65247                             else {
65248                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
65249                             }
65250                         }
65251                     }
65252                 }
65253             }
65254             if (produceDiagnostics) {
65255                 checkIndexConstraints(type);
65256                 checkTypeForDuplicateIndexSignatures(node);
65257                 checkPropertyInitialization(node);
65258             }
65259         }
65260         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
65261             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
65262             var issuedMemberError = false;
65263             var _loop_19 = function (member) {
65264                 if (ts.hasStaticModifier(member)) {
65265                     return "continue";
65266                 }
65267                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
65268                 if (declaredProp) {
65269                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
65270                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
65271                     if (prop && baseProp) {
65272                         var rootChain = function () { return ts.chainDiagnosticMessages(
65273                         /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); };
65274                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
65275                             issuedMemberError = true;
65276                         }
65277                     }
65278                 }
65279             };
65280             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65281                 var member = _a[_i];
65282                 _loop_19(member);
65283             }
65284             if (!issuedMemberError) {
65285                 // check again with diagnostics to generate a less-specific error
65286                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
65287             }
65288         }
65289         function checkBaseTypeAccessibility(type, node) {
65290             var signatures = getSignaturesOfType(type, 1 /* Construct */);
65291             if (signatures.length) {
65292                 var declaration = signatures[0].declaration;
65293                 if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
65294                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65295                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
65296                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
65297                     }
65298                 }
65299             }
65300         }
65301         function getTargetSymbol(s) {
65302             // if symbol is instantiated its flags are not copied from the 'target'
65303             // so we'll need to get back original 'target' symbol to work with correct set of flags
65304             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
65305         }
65306         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
65307             return ts.filter(symbol.declarations, function (d) {
65308                 return d.kind === 245 /* ClassDeclaration */ || d.kind === 246 /* InterfaceDeclaration */;
65309             });
65310         }
65311         function checkKindsOfPropertyMemberOverrides(type, baseType) {
65312             // TypeScript 1.0 spec (April 2014): 8.2.3
65313             // A derived class inherits all members from its base class it doesn't override.
65314             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
65315             // Both public and private property members are inherited, but only public property members can be overridden.
65316             // A property member in a derived class is said to override a property member in a base class
65317             // when the derived class property member has the same name and kind(instance or static)
65318             // as the base class property member.
65319             // The type of an overriding property member must be assignable(section 3.8.4)
65320             // to the type of the overridden property member, or otherwise a compile - time error occurs.
65321             // Base class instance member functions can be overridden by derived class instance member functions,
65322             // but not by other kinds of members.
65323             // Base class instance member variables and accessors can be overridden by
65324             // derived class instance member variables and accessors, but not by other kinds of members.
65325             // NOTE: assignability is checked in checkClassDeclaration
65326             var baseProperties = getPropertiesOfType(baseType);
65327             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
65328                 var baseProperty = baseProperties_1[_i];
65329                 var base = getTargetSymbol(baseProperty);
65330                 if (base.flags & 4194304 /* Prototype */) {
65331                     continue;
65332                 }
65333                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
65334                 if (!baseSymbol) {
65335                     continue;
65336                 }
65337                 var derived = getTargetSymbol(baseSymbol);
65338                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
65339                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
65340                 // In order to resolve whether the inherited method was overridden in the base class or not,
65341                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
65342                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
65343                 if (derived === base) {
65344                     // derived class inherits base without override/redeclaration
65345                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65346                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
65347                     // If there is no declaration for the derived class (as in the case of class expressions),
65348                     // then the class cannot be declared abstract.
65349                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
65350                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
65351                         // (The class may have more than one base type via declaration merging with an interface with the
65352                         // same name.)
65353                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
65354                             var otherBaseType = _b[_a];
65355                             if (otherBaseType === baseType)
65356                                 continue;
65357                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
65358                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
65359                             if (derivedElsewhere && derivedElsewhere !== base) {
65360                                 continue basePropertyCheck;
65361                             }
65362                         }
65363                         if (derivedClassDecl.kind === 214 /* ClassExpression */) {
65364                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
65365                         }
65366                         else {
65367                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
65368                         }
65369                     }
65370                 }
65371                 else {
65372                     // derived overrides base.
65373                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
65374                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
65375                         // either base or derived property is private - not override, skip it
65376                         continue;
65377                     }
65378                     var errorMessage = void 0;
65379                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
65380                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
65381                     if (basePropertyFlags && derivedPropertyFlags) {
65382                         // property/accessor is overridden with property/accessor
65383                         if (!compilerOptions.useDefineForClassFields
65384                             || baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
65385                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 246 /* InterfaceDeclaration */
65386                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
65387                             // when the base property is abstract or from an interface, base/derived flags don't need to match
65388                             // same when the derived property is from an assignment
65389                             continue;
65390                         }
65391                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
65392                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
65393                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
65394                             var errorMessage_1 = overriddenInstanceProperty ?
65395                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
65396                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
65397                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
65398                         }
65399                         else {
65400                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 159 /* PropertyDeclaration */ && !d.initializer; });
65401                             if (uninitialized
65402                                 && !(derived.flags & 33554432 /* Transient */)
65403                                 && !(baseDeclarationFlags & 128 /* Abstract */)
65404                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
65405                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
65406                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
65407                                 var propName = uninitialized.name;
65408                                 if (uninitialized.exclamationToken
65409                                     || !constructor
65410                                     || !ts.isIdentifier(propName)
65411                                     || !strictNullChecks
65412                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65413                                     var errorMessage_2 = ts.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;
65414                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
65415                                 }
65416                             }
65417                         }
65418                         // correct case
65419                         continue;
65420                     }
65421                     else if (isPrototypeProperty(base)) {
65422                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
65423                             // method is overridden with method or property -- correct case
65424                             continue;
65425                         }
65426                         else {
65427                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
65428                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
65429                         }
65430                     }
65431                     else if (base.flags & 98304 /* Accessor */) {
65432                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
65433                     }
65434                     else {
65435                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
65436                     }
65437                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
65438                 }
65439             }
65440         }
65441         function getNonInterhitedProperties(type, baseTypes, properties) {
65442             if (!ts.length(baseTypes)) {
65443                 return properties;
65444             }
65445             var seen = ts.createUnderscoreEscapedMap();
65446             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
65447             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
65448                 var base = baseTypes_2[_i];
65449                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65450                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
65451                     var prop = properties_4[_a];
65452                     var existing = seen.get(prop.escapedName);
65453                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
65454                         seen.delete(prop.escapedName);
65455                     }
65456                 }
65457             }
65458             return ts.arrayFrom(seen.values());
65459         }
65460         function checkInheritedPropertiesAreIdentical(type, typeNode) {
65461             var baseTypes = getBaseTypes(type);
65462             if (baseTypes.length < 2) {
65463                 return true;
65464             }
65465             var seen = ts.createUnderscoreEscapedMap();
65466             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
65467             var ok = true;
65468             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
65469                 var base = baseTypes_3[_i];
65470                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65471                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
65472                     var prop = properties_6[_a];
65473                     var existing = seen.get(prop.escapedName);
65474                     if (!existing) {
65475                         seen.set(prop.escapedName, { prop: prop, containingType: base });
65476                     }
65477                     else {
65478                         var isInheritedProperty = existing.containingType !== type;
65479                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
65480                             ok = false;
65481                             var typeName1 = typeToString(existing.containingType);
65482                             var typeName2 = typeToString(base);
65483                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
65484                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
65485                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
65486                         }
65487                     }
65488                 }
65489             }
65490             return ok;
65491         }
65492         function checkPropertyInitialization(node) {
65493             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
65494                 return;
65495             }
65496             var constructor = findConstructorDeclaration(node);
65497             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65498                 var member = _a[_i];
65499                 if (ts.getModifierFlags(member) & 2 /* Ambient */) {
65500                     continue;
65501                 }
65502                 if (isInstancePropertyWithoutInitializer(member)) {
65503                     var propName = member.name;
65504                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
65505                         var type = getTypeOfSymbol(getSymbolOfNode(member));
65506                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
65507                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65508                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
65509                             }
65510                         }
65511                     }
65512                 }
65513             }
65514         }
65515         function isInstancePropertyWithoutInitializer(node) {
65516             return node.kind === 159 /* PropertyDeclaration */ &&
65517                 !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
65518                 !node.exclamationToken &&
65519                 !node.initializer;
65520         }
65521         function isPropertyInitializedInConstructor(propName, propType, constructor) {
65522             var reference = ts.createPropertyAccess(ts.createThis(), propName);
65523             reference.expression.parent = reference;
65524             reference.parent = constructor;
65525             reference.flowNode = constructor.returnFlowNode;
65526             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
65527             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
65528         }
65529         function checkInterfaceDeclaration(node) {
65530             // Grammar checking
65531             if (!checkGrammarDecoratorsAndModifiers(node))
65532                 checkGrammarInterfaceDeclaration(node);
65533             checkTypeParameters(node.typeParameters);
65534             if (produceDiagnostics) {
65535                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
65536                 checkExportsOnMergedDeclarations(node);
65537                 var symbol = getSymbolOfNode(node);
65538                 checkTypeParameterListsIdentical(symbol);
65539                 // Only check this symbol once
65540                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
65541                 if (node === firstInterfaceDecl) {
65542                     var type = getDeclaredTypeOfSymbol(symbol);
65543                     var typeWithThis = getTypeWithThisArgument(type);
65544                     // run subsequent checks only if first set succeeded
65545                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
65546                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
65547                             var baseType = _a[_i];
65548                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
65549                         }
65550                         checkIndexConstraints(type);
65551                     }
65552                 }
65553                 checkObjectTypeForDuplicateDeclarations(node);
65554             }
65555             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
65556                 if (!ts.isEntityNameExpression(heritageElement.expression)) {
65557                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
65558                 }
65559                 checkTypeReferenceNode(heritageElement);
65560             });
65561             ts.forEach(node.members, checkSourceElement);
65562             if (produceDiagnostics) {
65563                 checkTypeForDuplicateIndexSignatures(node);
65564                 registerForUnusedIdentifiersCheck(node);
65565             }
65566         }
65567         function checkTypeAliasDeclaration(node) {
65568             // Grammar checking
65569             checkGrammarDecoratorsAndModifiers(node);
65570             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
65571             checkExportsOnMergedDeclarations(node);
65572             checkTypeParameters(node.typeParameters);
65573             checkSourceElement(node.type);
65574             registerForUnusedIdentifiersCheck(node);
65575         }
65576         function computeEnumMemberValues(node) {
65577             var nodeLinks = getNodeLinks(node);
65578             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
65579                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
65580                 var autoValue = 0;
65581                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65582                     var member = _a[_i];
65583                     var value = computeMemberValue(member, autoValue);
65584                     getNodeLinks(member).enumMemberValue = value;
65585                     autoValue = typeof value === "number" ? value + 1 : undefined;
65586                 }
65587             }
65588         }
65589         function computeMemberValue(member, autoValue) {
65590             if (ts.isComputedNonLiteralName(member.name)) {
65591                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
65592             }
65593             else {
65594                 var text = ts.getTextOfPropertyName(member.name);
65595                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
65596                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
65597                 }
65598             }
65599             if (member.initializer) {
65600                 return computeConstantValue(member);
65601             }
65602             // In ambient non-const numeric enum declarations, enum members without initializers are
65603             // considered computed members (as opposed to having auto-incremented values).
65604             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
65605                 return undefined;
65606             }
65607             // If the member declaration specifies no value, the member is considered a constant enum member.
65608             // If the member is the first member in the enum declaration, it is assigned the value zero.
65609             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
65610             // occurs if the immediately preceding member is not a constant enum member.
65611             if (autoValue !== undefined) {
65612                 return autoValue;
65613             }
65614             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
65615             return undefined;
65616         }
65617         function computeConstantValue(member) {
65618             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
65619             var isConstEnum = ts.isEnumConst(member.parent);
65620             var initializer = member.initializer;
65621             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
65622             if (value !== undefined) {
65623                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
65624                     error(initializer, isNaN(value) ?
65625                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
65626                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
65627                 }
65628             }
65629             else if (enumKind === 1 /* Literal */) {
65630                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
65631                 return 0;
65632             }
65633             else if (isConstEnum) {
65634                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
65635             }
65636             else if (member.parent.flags & 8388608 /* Ambient */) {
65637                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
65638             }
65639             else {
65640                 // Only here do we need to check that the initializer is assignable to the enum type.
65641                 var source = checkExpression(initializer);
65642                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
65643                     error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source));
65644                 }
65645                 else {
65646                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
65647                 }
65648             }
65649             return value;
65650             function evaluate(expr) {
65651                 switch (expr.kind) {
65652                     case 207 /* PrefixUnaryExpression */:
65653                         var value_2 = evaluate(expr.operand);
65654                         if (typeof value_2 === "number") {
65655                             switch (expr.operator) {
65656                                 case 39 /* PlusToken */: return value_2;
65657                                 case 40 /* MinusToken */: return -value_2;
65658                                 case 54 /* TildeToken */: return ~value_2;
65659                             }
65660                         }
65661                         break;
65662                     case 209 /* BinaryExpression */:
65663                         var left = evaluate(expr.left);
65664                         var right = evaluate(expr.right);
65665                         if (typeof left === "number" && typeof right === "number") {
65666                             switch (expr.operatorToken.kind) {
65667                                 case 51 /* BarToken */: return left | right;
65668                                 case 50 /* AmpersandToken */: return left & right;
65669                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
65670                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
65671                                 case 47 /* LessThanLessThanToken */: return left << right;
65672                                 case 52 /* CaretToken */: return left ^ right;
65673                                 case 41 /* AsteriskToken */: return left * right;
65674                                 case 43 /* SlashToken */: return left / right;
65675                                 case 39 /* PlusToken */: return left + right;
65676                                 case 40 /* MinusToken */: return left - right;
65677                                 case 44 /* PercentToken */: return left % right;
65678                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
65679                             }
65680                         }
65681                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
65682                             return left + right;
65683                         }
65684                         break;
65685                     case 10 /* StringLiteral */:
65686                     case 14 /* NoSubstitutionTemplateLiteral */:
65687                         return expr.text;
65688                     case 8 /* NumericLiteral */:
65689                         checkGrammarNumericLiteral(expr);
65690                         return +expr.text;
65691                     case 200 /* ParenthesizedExpression */:
65692                         return evaluate(expr.expression);
65693                     case 75 /* Identifier */:
65694                         var identifier = expr;
65695                         if (isInfinityOrNaNString(identifier.escapedText)) {
65696                             return +(identifier.escapedText);
65697                         }
65698                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
65699                     case 195 /* ElementAccessExpression */:
65700                     case 194 /* PropertyAccessExpression */:
65701                         var ex = expr;
65702                         if (isConstantMemberAccess(ex)) {
65703                             var type = getTypeOfExpression(ex.expression);
65704                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
65705                                 var name = void 0;
65706                                 if (ex.kind === 194 /* PropertyAccessExpression */) {
65707                                     name = ex.name.escapedText;
65708                                 }
65709                                 else {
65710                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
65711                                 }
65712                                 return evaluateEnumMember(expr, type.symbol, name);
65713                             }
65714                         }
65715                         break;
65716                 }
65717                 return undefined;
65718             }
65719             function evaluateEnumMember(expr, enumSymbol, name) {
65720                 var memberSymbol = enumSymbol.exports.get(name);
65721                 if (memberSymbol) {
65722                     var declaration = memberSymbol.valueDeclaration;
65723                     if (declaration !== member) {
65724                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
65725                             return getEnumMemberValue(declaration);
65726                         }
65727                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
65728                         return 0;
65729                     }
65730                     else {
65731                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
65732                     }
65733                 }
65734                 return undefined;
65735             }
65736         }
65737         function isConstantMemberAccess(node) {
65738             return node.kind === 75 /* Identifier */ ||
65739                 node.kind === 194 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
65740                 node.kind === 195 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
65741                     ts.isStringLiteralLike(node.argumentExpression);
65742         }
65743         function checkEnumDeclaration(node) {
65744             if (!produceDiagnostics) {
65745                 return;
65746             }
65747             // Grammar checking
65748             checkGrammarDecoratorsAndModifiers(node);
65749             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
65750             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65751             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65752             checkExportsOnMergedDeclarations(node);
65753             node.members.forEach(checkEnumMember);
65754             computeEnumMemberValues(node);
65755             // Spec 2014 - Section 9.3:
65756             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
65757             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
65758             // for the first member.
65759             //
65760             // Only perform this check once per symbol
65761             var enumSymbol = getSymbolOfNode(node);
65762             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
65763             if (node === firstDeclaration) {
65764                 if (enumSymbol.declarations.length > 1) {
65765                     var enumIsConst_1 = ts.isEnumConst(node);
65766                     // check that const is placed\omitted on all enum declarations
65767                     ts.forEach(enumSymbol.declarations, function (decl) {
65768                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
65769                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
65770                         }
65771                     });
65772                 }
65773                 var seenEnumMissingInitialInitializer_1 = false;
65774                 ts.forEach(enumSymbol.declarations, function (declaration) {
65775                     // return true if we hit a violation of the rule, false otherwise
65776                     if (declaration.kind !== 248 /* EnumDeclaration */) {
65777                         return false;
65778                     }
65779                     var enumDeclaration = declaration;
65780                     if (!enumDeclaration.members.length) {
65781                         return false;
65782                     }
65783                     var firstEnumMember = enumDeclaration.members[0];
65784                     if (!firstEnumMember.initializer) {
65785                         if (seenEnumMissingInitialInitializer_1) {
65786                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
65787                         }
65788                         else {
65789                             seenEnumMissingInitialInitializer_1 = true;
65790                         }
65791                     }
65792                 });
65793             }
65794         }
65795         function checkEnumMember(node) {
65796             if (ts.isPrivateIdentifier(node.name)) {
65797                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
65798             }
65799         }
65800         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
65801             var declarations = symbol.declarations;
65802             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
65803                 var declaration = declarations_8[_i];
65804                 if ((declaration.kind === 245 /* ClassDeclaration */ ||
65805                     (declaration.kind === 244 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
65806                     !(declaration.flags & 8388608 /* Ambient */)) {
65807                     return declaration;
65808                 }
65809             }
65810             return undefined;
65811         }
65812         function inSameLexicalScope(node1, node2) {
65813             var container1 = ts.getEnclosingBlockScopeContainer(node1);
65814             var container2 = ts.getEnclosingBlockScopeContainer(node2);
65815             if (isGlobalSourceFile(container1)) {
65816                 return isGlobalSourceFile(container2);
65817             }
65818             else if (isGlobalSourceFile(container2)) {
65819                 return false;
65820             }
65821             else {
65822                 return container1 === container2;
65823             }
65824         }
65825         function checkModuleDeclaration(node) {
65826             if (produceDiagnostics) {
65827                 // Grammar checking
65828                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
65829                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
65830                 if (isGlobalAugmentation && !inAmbientContext) {
65831                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
65832                 }
65833                 var isAmbientExternalModule = ts.isAmbientModule(node);
65834                 var contextErrorMessage = isAmbientExternalModule
65835                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
65836                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
65837                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
65838                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
65839                     return;
65840                 }
65841                 if (!checkGrammarDecoratorsAndModifiers(node)) {
65842                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
65843                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
65844                     }
65845                 }
65846                 if (ts.isIdentifier(node.name)) {
65847                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65848                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65849                 }
65850                 checkExportsOnMergedDeclarations(node);
65851                 var symbol = getSymbolOfNode(node);
65852                 // The following checks only apply on a non-ambient instantiated module declaration.
65853                 if (symbol.flags & 512 /* ValueModule */
65854                     && !inAmbientContext
65855                     && symbol.declarations.length > 1
65856                     && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
65857                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
65858                     if (firstNonAmbientClassOrFunc) {
65859                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
65860                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
65861                         }
65862                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
65863                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
65864                         }
65865                     }
65866                     // if the module merges with a class declaration in the same lexical scope,
65867                     // we need to track this to ensure the correct emit.
65868                     var mergedClass = ts.getDeclarationOfKind(symbol, 245 /* ClassDeclaration */);
65869                     if (mergedClass &&
65870                         inSameLexicalScope(node, mergedClass)) {
65871                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
65872                     }
65873                 }
65874                 if (isAmbientExternalModule) {
65875                     if (ts.isExternalModuleAugmentation(node)) {
65876                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
65877                         // otherwise we'll be swamped in cascading errors.
65878                         // We can detect if augmentation was applied using following rules:
65879                         // - augmentation for a global scope is always applied
65880                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
65881                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
65882                         if (checkBody && node.body) {
65883                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
65884                                 var statement = _a[_i];
65885                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
65886                             }
65887                         }
65888                     }
65889                     else if (isGlobalSourceFile(node.parent)) {
65890                         if (isGlobalAugmentation) {
65891                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65892                         }
65893                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
65894                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
65895                         }
65896                     }
65897                     else {
65898                         if (isGlobalAugmentation) {
65899                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65900                         }
65901                         else {
65902                             // Node is not an augmentation and is not located on the script level.
65903                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
65904                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
65905                         }
65906                     }
65907                 }
65908             }
65909             if (node.body) {
65910                 checkSourceElement(node.body);
65911                 if (!ts.isGlobalScopeAugmentation(node)) {
65912                     registerForUnusedIdentifiersCheck(node);
65913                 }
65914             }
65915         }
65916         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
65917             switch (node.kind) {
65918                 case 225 /* VariableStatement */:
65919                     // error each individual name in variable statement instead of marking the entire variable statement
65920                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
65921                         var decl = _a[_i];
65922                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
65923                     }
65924                     break;
65925                 case 259 /* ExportAssignment */:
65926                 case 260 /* ExportDeclaration */:
65927                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
65928                     break;
65929                 case 253 /* ImportEqualsDeclaration */:
65930                 case 254 /* ImportDeclaration */:
65931                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
65932                     break;
65933                 case 191 /* BindingElement */:
65934                 case 242 /* VariableDeclaration */:
65935                     var name = node.name;
65936                     if (ts.isBindingPattern(name)) {
65937                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
65938                             var el = _c[_b];
65939                             // mark individual names in binding pattern
65940                             checkModuleAugmentationElement(el, isGlobalAugmentation);
65941                         }
65942                         break;
65943                     }
65944                 // falls through
65945                 case 245 /* ClassDeclaration */:
65946                 case 248 /* EnumDeclaration */:
65947                 case 244 /* FunctionDeclaration */:
65948                 case 246 /* InterfaceDeclaration */:
65949                 case 249 /* ModuleDeclaration */:
65950                 case 247 /* TypeAliasDeclaration */:
65951                     if (isGlobalAugmentation) {
65952                         return;
65953                     }
65954                     var symbol = getSymbolOfNode(node);
65955                     if (symbol) {
65956                         // module augmentations cannot introduce new names on the top level scope of the module
65957                         // this is done it two steps
65958                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
65959                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
65960                         var reportError = !(symbol.flags & 33554432 /* Transient */);
65961                         if (!reportError) {
65962                             // symbol should not originate in augmentation
65963                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
65964                         }
65965                     }
65966                     break;
65967             }
65968         }
65969         function getFirstNonModuleExportsIdentifier(node) {
65970             switch (node.kind) {
65971                 case 75 /* Identifier */:
65972                     return node;
65973                 case 153 /* QualifiedName */:
65974                     do {
65975                         node = node.left;
65976                     } while (node.kind !== 75 /* Identifier */);
65977                     return node;
65978                 case 194 /* PropertyAccessExpression */:
65979                     do {
65980                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
65981                             return node.name;
65982                         }
65983                         node = node.expression;
65984                     } while (node.kind !== 75 /* Identifier */);
65985                     return node;
65986             }
65987         }
65988         function checkExternalImportOrExportDeclaration(node) {
65989             var moduleName = ts.getExternalModuleName(node);
65990             if (!moduleName || ts.nodeIsMissing(moduleName)) {
65991                 // Should be a parse error.
65992                 return false;
65993             }
65994             if (!ts.isStringLiteral(moduleName)) {
65995                 error(moduleName, ts.Diagnostics.String_literal_expected);
65996                 return false;
65997             }
65998             var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
65999             if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule) {
66000                 error(moduleName, node.kind === 260 /* ExportDeclaration */ ?
66001                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
66002                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
66003                 return false;
66004             }
66005             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
66006                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
66007                 // no need to do this again.
66008                 if (!isTopLevelInExternalModuleAugmentation(node)) {
66009                     // TypeScript 1.0 spec (April 2013): 12.1.6
66010                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
66011                     // other external modules only through top - level external module names.
66012                     // Relative external module names are not permitted.
66013                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
66014                     return false;
66015                 }
66016             }
66017             return true;
66018         }
66019         function checkAliasSymbol(node) {
66020             var symbol = getSymbolOfNode(node);
66021             var target = resolveAlias(symbol);
66022             var shouldSkipWithJSExpandoTargets = symbol.flags & 67108864 /* Assignment */;
66023             if (!shouldSkipWithJSExpandoTargets && target !== unknownSymbol) {
66024                 // For external modules symbol represents local symbol for an alias.
66025                 // This local symbol will merge any other local declarations (excluding other aliases)
66026                 // and symbol.flags will contains combined representation for all merged declaration.
66027                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
66028                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
66029                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
66030                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
66031                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
66032                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
66033                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
66034                 if (target.flags & excludedMeanings) {
66035                     var message = node.kind === 263 /* ExportSpecifier */ ?
66036                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
66037                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
66038                     error(node, message, symbolToString(symbol));
66039                 }
66040                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
66041                 if (compilerOptions.isolatedModules
66042                     && node.kind === 263 /* ExportSpecifier */
66043                     && !node.parent.parent.isTypeOnly
66044                     && !(target.flags & 111551 /* Value */)
66045                     && !(node.flags & 8388608 /* Ambient */)) {
66046                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
66047                 }
66048             }
66049         }
66050         function checkImportBinding(node) {
66051             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
66052             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
66053             checkAliasSymbol(node);
66054         }
66055         function checkImportDeclaration(node) {
66056             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66057                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66058                 return;
66059             }
66060             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66061                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
66062             }
66063             if (checkExternalImportOrExportDeclaration(node)) {
66064                 var importClause = node.importClause;
66065                 if (importClause && !checkGrammarImportClause(importClause)) {
66066                     if (importClause.name) {
66067                         checkImportBinding(importClause);
66068                     }
66069                     if (importClause.namedBindings) {
66070                         if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
66071                             checkImportBinding(importClause.namedBindings);
66072                         }
66073                         else {
66074                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
66075                             if (moduleExisted) {
66076                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
66077                             }
66078                         }
66079                     }
66080                 }
66081             }
66082         }
66083         function checkImportEqualsDeclaration(node) {
66084             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66085                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66086                 return;
66087             }
66088             checkGrammarDecoratorsAndModifiers(node);
66089             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
66090                 checkImportBinding(node);
66091                 if (ts.hasModifier(node, 1 /* Export */)) {
66092                     markExportAsReferenced(node);
66093                 }
66094                 if (node.moduleReference.kind !== 265 /* ExternalModuleReference */) {
66095                     var target = resolveAlias(getSymbolOfNode(node));
66096                     if (target !== unknownSymbol) {
66097                         if (target.flags & 111551 /* Value */) {
66098                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
66099                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
66100                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
66101                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
66102                             }
66103                         }
66104                         if (target.flags & 788968 /* Type */) {
66105                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
66106                         }
66107                     }
66108                 }
66109                 else {
66110                     if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
66111                         // Import equals declaration is deprecated in es6 or above
66112                         grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
66113                     }
66114                 }
66115             }
66116         }
66117         function checkExportDeclaration(node) {
66118             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
66119                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
66120                 return;
66121             }
66122             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66123                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
66124             }
66125             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
66126                 checkExternalEmitHelpers(node, 1048576 /* CreateBinding */);
66127             }
66128             checkGrammarExportDeclaration(node);
66129             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
66130                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
66131                     // export { x, y }
66132                     // export { x, y } from "foo"
66133                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
66134                     var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
66135                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ &&
66136                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
66137                     if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
66138                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
66139                     }
66140                 }
66141                 else {
66142                     // export * from "foo"
66143                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
66144                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
66145                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
66146                     }
66147                     else if (node.exportClause) {
66148                         checkAliasSymbol(node.exportClause);
66149                     }
66150                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
66151                         checkExternalEmitHelpers(node, 65536 /* ExportStar */);
66152                     }
66153                 }
66154             }
66155         }
66156         function checkGrammarExportDeclaration(node) {
66157             var _a;
66158             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 261 /* NamedExports */;
66159             if (isTypeOnlyExportStar) {
66160                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
66161             }
66162             return !isTypeOnlyExportStar;
66163         }
66164         function checkGrammarModuleElementContext(node, errorMessage) {
66165             var isInAppropriateContext = node.parent.kind === 290 /* SourceFile */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 249 /* ModuleDeclaration */;
66166             if (!isInAppropriateContext) {
66167                 grammarErrorOnFirstToken(node, errorMessage);
66168             }
66169             return !isInAppropriateContext;
66170         }
66171         function importClauseContainsReferencedImport(importClause) {
66172             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66173                 return !!getSymbolOfNode(declaration).isReferenced;
66174             });
66175         }
66176         function importClauseContainsConstEnumUsedAsValue(importClause) {
66177             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66178                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
66179             });
66180         }
66181         function checkImportsForTypeOnlyConversion(sourceFile) {
66182             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
66183                 var statement = _a[_i];
66184                 if (ts.isImportDeclaration(statement) &&
66185                     statement.importClause &&
66186                     !statement.importClause.isTypeOnly &&
66187                     importClauseContainsReferencedImport(statement.importClause) &&
66188                     !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
66189                     !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
66190                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
66191                 }
66192             }
66193         }
66194         function checkExportSpecifier(node) {
66195             checkAliasSymbol(node);
66196             if (ts.getEmitDeclarations(compilerOptions)) {
66197                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
66198             }
66199             if (!node.parent.parent.moduleSpecifier) {
66200                 var exportedName = node.propertyName || node.name;
66201                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
66202                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
66203                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
66204                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
66205                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
66206                 }
66207                 else {
66208                     markExportAsReferenced(node);
66209                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
66210                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
66211                         checkExpressionCached(node.propertyName || node.name);
66212                     }
66213                 }
66214             }
66215         }
66216         function checkExportAssignment(node) {
66217             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
66218                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
66219                 return;
66220             }
66221             var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
66222             if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
66223                 if (node.isExportEquals) {
66224                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
66225                 }
66226                 else {
66227                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
66228                 }
66229                 return;
66230             }
66231             // Grammar checking
66232             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66233                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
66234             }
66235             if (node.expression.kind === 75 /* Identifier */) {
66236                 var id = node.expression;
66237                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
66238                 if (sym) {
66239                     markAliasReferenced(sym, id);
66240                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
66241                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
66242                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
66243                         // However if it is a value, we need to check it's being used correctly
66244                         checkExpressionCached(node.expression);
66245                     }
66246                 }
66247                 if (ts.getEmitDeclarations(compilerOptions)) {
66248                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
66249                 }
66250             }
66251             else {
66252                 checkExpressionCached(node.expression);
66253             }
66254             checkExternalModuleExports(container);
66255             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
66256                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
66257             }
66258             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
66259                 if (moduleKind >= ts.ModuleKind.ES2015) {
66260                     // export assignment is not supported in es6 modules
66261                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
66262                 }
66263                 else if (moduleKind === ts.ModuleKind.System) {
66264                     // system modules does not support export assignment
66265                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
66266                 }
66267             }
66268         }
66269         function hasExportedMembers(moduleSymbol) {
66270             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
66271         }
66272         function checkExternalModuleExports(node) {
66273             var moduleSymbol = getSymbolOfNode(node);
66274             var links = getSymbolLinks(moduleSymbol);
66275             if (!links.exportsChecked) {
66276                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
66277                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
66278                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
66279                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
66280                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
66281                     }
66282                 }
66283                 // Checks for export * conflicts
66284                 var exports_2 = getExportsOfModule(moduleSymbol);
66285                 if (exports_2) {
66286                     exports_2.forEach(function (_a, id) {
66287                         var declarations = _a.declarations, flags = _a.flags;
66288                         if (id === "__export") {
66289                             return;
66290                         }
66291                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
66292                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
66293                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
66294                             return;
66295                         }
66296                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
66297                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
66298                             // it is legal to merge type alias with other values
66299                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
66300                             return;
66301                         }
66302                         if (exportedDeclarationsCount > 1) {
66303                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
66304                                 var declaration = declarations_9[_i];
66305                                 if (isNotOverload(declaration)) {
66306                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
66307                                 }
66308                             }
66309                         }
66310                     });
66311                 }
66312                 links.exportsChecked = true;
66313             }
66314         }
66315         function checkSourceElement(node) {
66316             if (node) {
66317                 var saveCurrentNode = currentNode;
66318                 currentNode = node;
66319                 instantiationCount = 0;
66320                 checkSourceElementWorker(node);
66321                 currentNode = saveCurrentNode;
66322             }
66323         }
66324         function checkSourceElementWorker(node) {
66325             if (ts.isInJSFile(node)) {
66326                 ts.forEach(node.jsDoc, function (_a) {
66327                     var tags = _a.tags;
66328                     return ts.forEach(tags, checkSourceElement);
66329                 });
66330             }
66331             var kind = node.kind;
66332             if (cancellationToken) {
66333                 // Only bother checking on a few construct kinds.  We don't want to be excessively
66334                 // hitting the cancellation token on every node we check.
66335                 switch (kind) {
66336                     case 249 /* ModuleDeclaration */:
66337                     case 245 /* ClassDeclaration */:
66338                     case 246 /* InterfaceDeclaration */:
66339                     case 244 /* FunctionDeclaration */:
66340                         cancellationToken.throwIfCancellationRequested();
66341                 }
66342             }
66343             if (kind >= 225 /* FirstStatement */ && kind <= 241 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
66344                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
66345             }
66346             switch (kind) {
66347                 case 155 /* TypeParameter */:
66348                     return checkTypeParameter(node);
66349                 case 156 /* Parameter */:
66350                     return checkParameter(node);
66351                 case 159 /* PropertyDeclaration */:
66352                     return checkPropertyDeclaration(node);
66353                 case 158 /* PropertySignature */:
66354                     return checkPropertySignature(node);
66355                 case 170 /* FunctionType */:
66356                 case 171 /* ConstructorType */:
66357                 case 165 /* CallSignature */:
66358                 case 166 /* ConstructSignature */:
66359                 case 167 /* IndexSignature */:
66360                     return checkSignatureDeclaration(node);
66361                 case 161 /* MethodDeclaration */:
66362                 case 160 /* MethodSignature */:
66363                     return checkMethodDeclaration(node);
66364                 case 162 /* Constructor */:
66365                     return checkConstructorDeclaration(node);
66366                 case 163 /* GetAccessor */:
66367                 case 164 /* SetAccessor */:
66368                     return checkAccessorDeclaration(node);
66369                 case 169 /* TypeReference */:
66370                     return checkTypeReferenceNode(node);
66371                 case 168 /* TypePredicate */:
66372                     return checkTypePredicate(node);
66373                 case 172 /* TypeQuery */:
66374                     return checkTypeQuery(node);
66375                 case 173 /* TypeLiteral */:
66376                     return checkTypeLiteral(node);
66377                 case 174 /* ArrayType */:
66378                     return checkArrayType(node);
66379                 case 175 /* TupleType */:
66380                     return checkTupleType(node);
66381                 case 178 /* UnionType */:
66382                 case 179 /* IntersectionType */:
66383                     return checkUnionOrIntersectionType(node);
66384                 case 182 /* ParenthesizedType */:
66385                 case 176 /* OptionalType */:
66386                 case 177 /* RestType */:
66387                     return checkSourceElement(node.type);
66388                 case 183 /* ThisType */:
66389                     return checkThisType(node);
66390                 case 184 /* TypeOperator */:
66391                     return checkTypeOperator(node);
66392                 case 180 /* ConditionalType */:
66393                     return checkConditionalType(node);
66394                 case 181 /* InferType */:
66395                     return checkInferType(node);
66396                 case 188 /* ImportType */:
66397                     return checkImportType(node);
66398                 case 307 /* JSDocAugmentsTag */:
66399                     return checkJSDocAugmentsTag(node);
66400                 case 308 /* JSDocImplementsTag */:
66401                     return checkJSDocImplementsTag(node);
66402                 case 322 /* JSDocTypedefTag */:
66403                 case 315 /* JSDocCallbackTag */:
66404                 case 316 /* JSDocEnumTag */:
66405                     return checkJSDocTypeAliasTag(node);
66406                 case 321 /* JSDocTemplateTag */:
66407                     return checkJSDocTemplateTag(node);
66408                 case 320 /* JSDocTypeTag */:
66409                     return checkJSDocTypeTag(node);
66410                 case 317 /* JSDocParameterTag */:
66411                     return checkJSDocParameterTag(node);
66412                 case 323 /* JSDocPropertyTag */:
66413                     return checkJSDocPropertyTag(node);
66414                 case 300 /* JSDocFunctionType */:
66415                     checkJSDocFunctionType(node);
66416                 // falls through
66417                 case 298 /* JSDocNonNullableType */:
66418                 case 297 /* JSDocNullableType */:
66419                 case 295 /* JSDocAllType */:
66420                 case 296 /* JSDocUnknownType */:
66421                 case 304 /* JSDocTypeLiteral */:
66422                     checkJSDocTypeIsInJsFile(node);
66423                     ts.forEachChild(node, checkSourceElement);
66424                     return;
66425                 case 301 /* JSDocVariadicType */:
66426                     checkJSDocVariadicType(node);
66427                     return;
66428                 case 294 /* JSDocTypeExpression */:
66429                     return checkSourceElement(node.type);
66430                 case 185 /* IndexedAccessType */:
66431                     return checkIndexedAccessType(node);
66432                 case 186 /* MappedType */:
66433                     return checkMappedType(node);
66434                 case 244 /* FunctionDeclaration */:
66435                     return checkFunctionDeclaration(node);
66436                 case 223 /* Block */:
66437                 case 250 /* ModuleBlock */:
66438                     return checkBlock(node);
66439                 case 225 /* VariableStatement */:
66440                     return checkVariableStatement(node);
66441                 case 226 /* ExpressionStatement */:
66442                     return checkExpressionStatement(node);
66443                 case 227 /* IfStatement */:
66444                     return checkIfStatement(node);
66445                 case 228 /* DoStatement */:
66446                     return checkDoStatement(node);
66447                 case 229 /* WhileStatement */:
66448                     return checkWhileStatement(node);
66449                 case 230 /* ForStatement */:
66450                     return checkForStatement(node);
66451                 case 231 /* ForInStatement */:
66452                     return checkForInStatement(node);
66453                 case 232 /* ForOfStatement */:
66454                     return checkForOfStatement(node);
66455                 case 233 /* ContinueStatement */:
66456                 case 234 /* BreakStatement */:
66457                     return checkBreakOrContinueStatement(node);
66458                 case 235 /* ReturnStatement */:
66459                     return checkReturnStatement(node);
66460                 case 236 /* WithStatement */:
66461                     return checkWithStatement(node);
66462                 case 237 /* SwitchStatement */:
66463                     return checkSwitchStatement(node);
66464                 case 238 /* LabeledStatement */:
66465                     return checkLabeledStatement(node);
66466                 case 239 /* ThrowStatement */:
66467                     return checkThrowStatement(node);
66468                 case 240 /* TryStatement */:
66469                     return checkTryStatement(node);
66470                 case 242 /* VariableDeclaration */:
66471                     return checkVariableDeclaration(node);
66472                 case 191 /* BindingElement */:
66473                     return checkBindingElement(node);
66474                 case 245 /* ClassDeclaration */:
66475                     return checkClassDeclaration(node);
66476                 case 246 /* InterfaceDeclaration */:
66477                     return checkInterfaceDeclaration(node);
66478                 case 247 /* TypeAliasDeclaration */:
66479                     return checkTypeAliasDeclaration(node);
66480                 case 248 /* EnumDeclaration */:
66481                     return checkEnumDeclaration(node);
66482                 case 249 /* ModuleDeclaration */:
66483                     return checkModuleDeclaration(node);
66484                 case 254 /* ImportDeclaration */:
66485                     return checkImportDeclaration(node);
66486                 case 253 /* ImportEqualsDeclaration */:
66487                     return checkImportEqualsDeclaration(node);
66488                 case 260 /* ExportDeclaration */:
66489                     return checkExportDeclaration(node);
66490                 case 259 /* ExportAssignment */:
66491                     return checkExportAssignment(node);
66492                 case 224 /* EmptyStatement */:
66493                 case 241 /* DebuggerStatement */:
66494                     checkGrammarStatementInAmbientContext(node);
66495                     return;
66496                 case 264 /* MissingDeclaration */:
66497                     return checkMissingDeclaration(node);
66498             }
66499         }
66500         function checkJSDocTypeIsInJsFile(node) {
66501             if (!ts.isInJSFile(node)) {
66502                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
66503             }
66504         }
66505         function checkJSDocVariadicType(node) {
66506             checkJSDocTypeIsInJsFile(node);
66507             checkSourceElement(node.type);
66508             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
66509             var parent = node.parent;
66510             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66511                 if (ts.last(parent.parent.parameters) !== parent) {
66512                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66513                 }
66514                 return;
66515             }
66516             if (!ts.isJSDocTypeExpression(parent)) {
66517                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66518             }
66519             var paramTag = node.parent.parent;
66520             if (!ts.isJSDocParameterTag(paramTag)) {
66521                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66522                 return;
66523             }
66524             var param = ts.getParameterSymbolFromJSDoc(paramTag);
66525             if (!param) {
66526                 // We will error in `checkJSDocParameterTag`.
66527                 return;
66528             }
66529             var host = ts.getHostSignatureFromJSDoc(paramTag);
66530             if (!host || ts.last(host.parameters).symbol !== param) {
66531                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66532             }
66533         }
66534         function getTypeFromJSDocVariadicType(node) {
66535             var type = getTypeFromTypeNode(node.type);
66536             var parent = node.parent;
66537             var paramTag = node.parent.parent;
66538             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
66539                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
66540                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
66541                 if (host_1) {
66542                     /*
66543                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
66544                     So in the following situation we will not create an array type:
66545                         /** @param {...number} a * /
66546                         function f(a) {}
66547                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
66548                     */
66549                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
66550                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
66551                     if (!lastParamDeclaration ||
66552                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
66553                         return createArrayType(type);
66554                     }
66555                 }
66556             }
66557             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66558                 return createArrayType(type);
66559             }
66560             return addOptionality(type);
66561         }
66562         // Function and class expression bodies are checked after all statements in the enclosing body. This is
66563         // to ensure constructs like the following are permitted:
66564         //     const foo = function () {
66565         //        const s = foo();
66566         //        return "hello";
66567         //     }
66568         // Here, performing a full type check of the body of the function expression whilst in the process of
66569         // determining the type of foo would cause foo to be given type any because of the recursive reference.
66570         // Delaying the type check of the body ensures foo has been assigned a type.
66571         function checkNodeDeferred(node) {
66572             var enclosingFile = ts.getSourceFileOfNode(node);
66573             var links = getNodeLinks(enclosingFile);
66574             if (!(links.flags & 1 /* TypeChecked */)) {
66575                 links.deferredNodes = links.deferredNodes || ts.createMap();
66576                 var id = "" + getNodeId(node);
66577                 links.deferredNodes.set(id, node);
66578             }
66579         }
66580         function checkDeferredNodes(context) {
66581             var links = getNodeLinks(context);
66582             if (links.deferredNodes) {
66583                 links.deferredNodes.forEach(checkDeferredNode);
66584             }
66585         }
66586         function checkDeferredNode(node) {
66587             var saveCurrentNode = currentNode;
66588             currentNode = node;
66589             instantiationCount = 0;
66590             switch (node.kind) {
66591                 case 196 /* CallExpression */:
66592                 case 197 /* NewExpression */:
66593                 case 198 /* TaggedTemplateExpression */:
66594                 case 157 /* Decorator */:
66595                 case 268 /* JsxOpeningElement */:
66596                     // These node kinds are deferred checked when overload resolution fails
66597                     // To save on work, we ensure the arguments are checked just once, in
66598                     // a deferred way
66599                     resolveUntypedCall(node);
66600                     break;
66601                 case 201 /* FunctionExpression */:
66602                 case 202 /* ArrowFunction */:
66603                 case 161 /* MethodDeclaration */:
66604                 case 160 /* MethodSignature */:
66605                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
66606                     break;
66607                 case 163 /* GetAccessor */:
66608                 case 164 /* SetAccessor */:
66609                     checkAccessorDeclaration(node);
66610                     break;
66611                 case 214 /* ClassExpression */:
66612                     checkClassExpressionDeferred(node);
66613                     break;
66614                 case 267 /* JsxSelfClosingElement */:
66615                     checkJsxSelfClosingElementDeferred(node);
66616                     break;
66617                 case 266 /* JsxElement */:
66618                     checkJsxElementDeferred(node);
66619                     break;
66620             }
66621             currentNode = saveCurrentNode;
66622         }
66623         function checkSourceFile(node) {
66624             ts.performance.mark("beforeCheck");
66625             checkSourceFileWorker(node);
66626             ts.performance.mark("afterCheck");
66627             ts.performance.measure("Check", "beforeCheck", "afterCheck");
66628         }
66629         function unusedIsError(kind, isAmbient) {
66630             if (isAmbient) {
66631                 return false;
66632             }
66633             switch (kind) {
66634                 case 0 /* Local */:
66635                     return !!compilerOptions.noUnusedLocals;
66636                 case 1 /* Parameter */:
66637                     return !!compilerOptions.noUnusedParameters;
66638                 default:
66639                     return ts.Debug.assertNever(kind);
66640             }
66641         }
66642         function getPotentiallyUnusedIdentifiers(sourceFile) {
66643             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
66644         }
66645         // Fully type check a source file and collect the relevant diagnostics.
66646         function checkSourceFileWorker(node) {
66647             var links = getNodeLinks(node);
66648             if (!(links.flags & 1 /* TypeChecked */)) {
66649                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
66650                     return;
66651                 }
66652                 // Grammar checking
66653                 checkGrammarSourceFile(node);
66654                 ts.clear(potentialThisCollisions);
66655                 ts.clear(potentialNewTargetCollisions);
66656                 ts.clear(potentialWeakMapCollisions);
66657                 ts.forEach(node.statements, checkSourceElement);
66658                 checkSourceElement(node.endOfFileToken);
66659                 checkDeferredNodes(node);
66660                 if (ts.isExternalOrCommonJsModule(node)) {
66661                     registerForUnusedIdentifiersCheck(node);
66662                 }
66663                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
66664                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
66665                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
66666                             diagnostics.add(diag);
66667                         }
66668                     });
66669                 }
66670                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
66671                     !node.isDeclarationFile &&
66672                     ts.isExternalModule(node)) {
66673                     checkImportsForTypeOnlyConversion(node);
66674                 }
66675                 if (ts.isExternalOrCommonJsModule(node)) {
66676                     checkExternalModuleExports(node);
66677                 }
66678                 if (potentialThisCollisions.length) {
66679                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
66680                     ts.clear(potentialThisCollisions);
66681                 }
66682                 if (potentialNewTargetCollisions.length) {
66683                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
66684                     ts.clear(potentialNewTargetCollisions);
66685                 }
66686                 if (potentialWeakMapCollisions.length) {
66687                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
66688                     ts.clear(potentialWeakMapCollisions);
66689                 }
66690                 links.flags |= 1 /* TypeChecked */;
66691             }
66692         }
66693         function getDiagnostics(sourceFile, ct) {
66694             try {
66695                 // Record the cancellation token so it can be checked later on during checkSourceElement.
66696                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
66697                 // this call is done.
66698                 cancellationToken = ct;
66699                 return getDiagnosticsWorker(sourceFile);
66700             }
66701             finally {
66702                 cancellationToken = undefined;
66703             }
66704         }
66705         function getDiagnosticsWorker(sourceFile) {
66706             throwIfNonDiagnosticsProducing();
66707             if (sourceFile) {
66708                 // Some global diagnostics are deferred until they are needed and
66709                 // may not be reported in the first call to getGlobalDiagnostics.
66710                 // We should catch these changes and report them.
66711                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66712                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
66713                 checkSourceFile(sourceFile);
66714                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
66715                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66716                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
66717                     // If the arrays are not the same reference, new diagnostics were added.
66718                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
66719                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
66720                 }
66721                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
66722                     // If the arrays are the same reference, but the length has changed, a single
66723                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
66724                     // same array.
66725                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
66726                 }
66727                 return semanticDiagnostics;
66728             }
66729             // Global diagnostics are always added when a file is not provided to
66730             // getDiagnostics
66731             ts.forEach(host.getSourceFiles(), checkSourceFile);
66732             return diagnostics.getDiagnostics();
66733         }
66734         function getGlobalDiagnostics() {
66735             throwIfNonDiagnosticsProducing();
66736             return diagnostics.getGlobalDiagnostics();
66737         }
66738         function throwIfNonDiagnosticsProducing() {
66739             if (!produceDiagnostics) {
66740                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
66741             }
66742         }
66743         // Language service support
66744         function getSymbolsInScope(location, meaning) {
66745             if (location.flags & 16777216 /* InWithStatement */) {
66746                 // We cannot answer semantic questions within a with block, do not proceed any further
66747                 return [];
66748             }
66749             var symbols = ts.createSymbolTable();
66750             var isStatic = false;
66751             populateSymbols();
66752             symbols.delete("this" /* This */); // Not a symbol, a keyword
66753             return symbolsToArray(symbols);
66754             function populateSymbols() {
66755                 while (location) {
66756                     if (location.locals && !isGlobalSourceFile(location)) {
66757                         copySymbols(location.locals, meaning);
66758                     }
66759                     switch (location.kind) {
66760                         case 290 /* SourceFile */:
66761                             if (!ts.isExternalOrCommonJsModule(location))
66762                                 break;
66763                         // falls through
66764                         case 249 /* ModuleDeclaration */:
66765                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
66766                             break;
66767                         case 248 /* EnumDeclaration */:
66768                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
66769                             break;
66770                         case 214 /* ClassExpression */:
66771                             var className = location.name;
66772                             if (className) {
66773                                 copySymbol(location.symbol, meaning);
66774                             }
66775                         // this fall-through is necessary because we would like to handle
66776                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
66777                         // falls through
66778                         case 245 /* ClassDeclaration */:
66779                         case 246 /* InterfaceDeclaration */:
66780                             // If we didn't come from static member of class or interface,
66781                             // add the type parameters into the symbol table
66782                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
66783                             // Note: that the memberFlags come from previous iteration.
66784                             if (!isStatic) {
66785                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
66786                             }
66787                             break;
66788                         case 201 /* FunctionExpression */:
66789                             var funcName = location.name;
66790                             if (funcName) {
66791                                 copySymbol(location.symbol, meaning);
66792                             }
66793                             break;
66794                     }
66795                     if (ts.introducesArgumentsExoticObject(location)) {
66796                         copySymbol(argumentsSymbol, meaning);
66797                     }
66798                     isStatic = ts.hasModifier(location, 32 /* Static */);
66799                     location = location.parent;
66800                 }
66801                 copySymbols(globals, meaning);
66802             }
66803             /**
66804              * Copy the given symbol into symbol tables if the symbol has the given meaning
66805              * and it doesn't already existed in the symbol table
66806              * @param key a key for storing in symbol table; if undefined, use symbol.name
66807              * @param symbol the symbol to be added into symbol table
66808              * @param meaning meaning of symbol to filter by before adding to symbol table
66809              */
66810             function copySymbol(symbol, meaning) {
66811                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
66812                     var id = symbol.escapedName;
66813                     // We will copy all symbol regardless of its reserved name because
66814                     // symbolsToArray will check whether the key is a reserved name and
66815                     // it will not copy symbol with reserved name to the array
66816                     if (!symbols.has(id)) {
66817                         symbols.set(id, symbol);
66818                     }
66819                 }
66820             }
66821             function copySymbols(source, meaning) {
66822                 if (meaning) {
66823                     source.forEach(function (symbol) {
66824                         copySymbol(symbol, meaning);
66825                     });
66826                 }
66827             }
66828         }
66829         function isTypeDeclarationName(name) {
66830             return name.kind === 75 /* Identifier */ &&
66831                 isTypeDeclaration(name.parent) &&
66832                 name.parent.name === name;
66833         }
66834         function isTypeDeclaration(node) {
66835             switch (node.kind) {
66836                 case 155 /* TypeParameter */:
66837                 case 245 /* ClassDeclaration */:
66838                 case 246 /* InterfaceDeclaration */:
66839                 case 247 /* TypeAliasDeclaration */:
66840                 case 248 /* EnumDeclaration */:
66841                     return true;
66842                 case 255 /* ImportClause */:
66843                     return node.isTypeOnly;
66844                 case 258 /* ImportSpecifier */:
66845                 case 263 /* ExportSpecifier */:
66846                     return node.parent.parent.isTypeOnly;
66847                 default:
66848                     return false;
66849             }
66850         }
66851         // True if the given identifier is part of a type reference
66852         function isTypeReferenceIdentifier(node) {
66853             while (node.parent.kind === 153 /* QualifiedName */) {
66854                 node = node.parent;
66855             }
66856             return node.parent.kind === 169 /* TypeReference */;
66857         }
66858         function isHeritageClauseElementIdentifier(node) {
66859             while (node.parent.kind === 194 /* PropertyAccessExpression */) {
66860                 node = node.parent;
66861             }
66862             return node.parent.kind === 216 /* ExpressionWithTypeArguments */;
66863         }
66864         function forEachEnclosingClass(node, callback) {
66865             var result;
66866             while (true) {
66867                 node = ts.getContainingClass(node);
66868                 if (!node)
66869                     break;
66870                 if (result = callback(node))
66871                     break;
66872             }
66873             return result;
66874         }
66875         function isNodeUsedDuringClassInitialization(node) {
66876             return !!ts.findAncestor(node, function (element) {
66877                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
66878                     return true;
66879                 }
66880                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
66881                     return "quit";
66882                 }
66883                 return false;
66884             });
66885         }
66886         function isNodeWithinClass(node, classDeclaration) {
66887             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
66888         }
66889         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
66890             while (nodeOnRightSide.parent.kind === 153 /* QualifiedName */) {
66891                 nodeOnRightSide = nodeOnRightSide.parent;
66892             }
66893             if (nodeOnRightSide.parent.kind === 253 /* ImportEqualsDeclaration */) {
66894                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66895             }
66896             if (nodeOnRightSide.parent.kind === 259 /* ExportAssignment */) {
66897                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66898             }
66899             return undefined;
66900         }
66901         function isInRightSideOfImportOrExportAssignment(node) {
66902             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
66903         }
66904         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
66905             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
66906             switch (specialPropertyAssignmentKind) {
66907                 case 1 /* ExportsProperty */:
66908                 case 3 /* PrototypeProperty */:
66909                     return getSymbolOfNode(entityName.parent);
66910                 case 4 /* ThisProperty */:
66911                 case 2 /* ModuleExports */:
66912                 case 5 /* Property */:
66913                     return getSymbolOfNode(entityName.parent.parent);
66914             }
66915         }
66916         function isImportTypeQualifierPart(node) {
66917             var parent = node.parent;
66918             while (ts.isQualifiedName(parent)) {
66919                 node = parent;
66920                 parent = parent.parent;
66921             }
66922             if (parent && parent.kind === 188 /* ImportType */ && parent.qualifier === node) {
66923                 return parent;
66924             }
66925             return undefined;
66926         }
66927         function getSymbolOfNameOrPropertyAccessExpression(name) {
66928             if (ts.isDeclarationName(name)) {
66929                 return getSymbolOfNode(name.parent);
66930             }
66931             if (ts.isInJSFile(name) &&
66932                 name.parent.kind === 194 /* PropertyAccessExpression */ &&
66933                 name.parent === name.parent.parent.left) {
66934                 // Check if this is a special property assignment
66935                 if (!ts.isPrivateIdentifier(name)) {
66936                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
66937                     if (specialPropertyAssignmentSymbol) {
66938                         return specialPropertyAssignmentSymbol;
66939                     }
66940                 }
66941             }
66942             if (name.parent.kind === 259 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
66943                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
66944                 var success = resolveEntityName(name, 
66945                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
66946                 if (success && success !== unknownSymbol) {
66947                     return success;
66948                 }
66949             }
66950             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
66951                 // Since we already checked for ExportAssignment, this really could only be an Import
66952                 var importEqualsDeclaration = ts.getAncestor(name, 253 /* ImportEqualsDeclaration */);
66953                 ts.Debug.assert(importEqualsDeclaration !== undefined);
66954                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
66955             }
66956             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
66957                 var possibleImportNode = isImportTypeQualifierPart(name);
66958                 if (possibleImportNode) {
66959                     getTypeFromTypeNode(possibleImportNode);
66960                     var sym = getNodeLinks(name).resolvedSymbol;
66961                     return sym === unknownSymbol ? undefined : sym;
66962                 }
66963             }
66964             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
66965                 name = name.parent;
66966             }
66967             if (isHeritageClauseElementIdentifier(name)) {
66968                 var meaning = 0 /* None */;
66969                 // In an interface or class, we're definitely interested in a type.
66970                 if (name.parent.kind === 216 /* ExpressionWithTypeArguments */) {
66971                     meaning = 788968 /* Type */;
66972                     // In a class 'extends' clause we are also looking for a value.
66973                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
66974                         meaning |= 111551 /* Value */;
66975                     }
66976                 }
66977                 else {
66978                     meaning = 1920 /* Namespace */;
66979                 }
66980                 meaning |= 2097152 /* Alias */;
66981                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
66982                 if (entityNameSymbol) {
66983                     return entityNameSymbol;
66984                 }
66985             }
66986             if (name.parent.kind === 317 /* JSDocParameterTag */) {
66987                 return ts.getParameterSymbolFromJSDoc(name.parent);
66988             }
66989             if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 321 /* JSDocTemplateTag */) {
66990                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
66991                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
66992                 return typeParameter && typeParameter.symbol;
66993             }
66994             if (ts.isExpressionNode(name)) {
66995                 if (ts.nodeIsMissing(name)) {
66996                     // Missing entity name.
66997                     return undefined;
66998                 }
66999                 if (name.kind === 75 /* Identifier */) {
67000                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
67001                         var symbol = getIntrinsicTagSymbol(name.parent);
67002                         return symbol === unknownSymbol ? undefined : symbol;
67003                     }
67004                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
67005                 }
67006                 else if (name.kind === 194 /* PropertyAccessExpression */ || name.kind === 153 /* QualifiedName */) {
67007                     var links = getNodeLinks(name);
67008                     if (links.resolvedSymbol) {
67009                         return links.resolvedSymbol;
67010                     }
67011                     if (name.kind === 194 /* PropertyAccessExpression */) {
67012                         checkPropertyAccessExpression(name);
67013                     }
67014                     else {
67015                         checkQualifiedName(name);
67016                     }
67017                     return links.resolvedSymbol;
67018                 }
67019             }
67020             else if (isTypeReferenceIdentifier(name)) {
67021                 var meaning = name.parent.kind === 169 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
67022                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
67023             }
67024             if (name.parent.kind === 168 /* TypePredicate */) {
67025                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
67026             }
67027             // Do we want to return undefined here?
67028             return undefined;
67029         }
67030         function getSymbolAtLocation(node, ignoreErrors) {
67031             if (node.kind === 290 /* SourceFile */) {
67032                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
67033             }
67034             var parent = node.parent;
67035             var grandParent = parent.parent;
67036             if (node.flags & 16777216 /* InWithStatement */) {
67037                 // We cannot answer semantic questions within a with block, do not proceed any further
67038                 return undefined;
67039             }
67040             if (isDeclarationNameOrImportPropertyName(node)) {
67041                 // This is a declaration, call getSymbolOfNode
67042                 var parentSymbol = getSymbolOfNode(parent);
67043                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
67044                     ? getImmediateAliasedSymbol(parentSymbol)
67045                     : parentSymbol;
67046             }
67047             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
67048                 return getSymbolOfNode(parent.parent);
67049             }
67050             if (node.kind === 75 /* Identifier */) {
67051                 if (isInRightSideOfImportOrExportAssignment(node)) {
67052                     return getSymbolOfNameOrPropertyAccessExpression(node);
67053                 }
67054                 else if (parent.kind === 191 /* BindingElement */ &&
67055                     grandParent.kind === 189 /* ObjectBindingPattern */ &&
67056                     node === parent.propertyName) {
67057                     var typeOfPattern = getTypeOfNode(grandParent);
67058                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
67059                     if (propertyDeclaration) {
67060                         return propertyDeclaration;
67061                     }
67062                 }
67063             }
67064             switch (node.kind) {
67065                 case 75 /* Identifier */:
67066                 case 76 /* PrivateIdentifier */:
67067                 case 194 /* PropertyAccessExpression */:
67068                 case 153 /* QualifiedName */:
67069                     return getSymbolOfNameOrPropertyAccessExpression(node);
67070                 case 104 /* ThisKeyword */:
67071                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
67072                     if (ts.isFunctionLike(container)) {
67073                         var sig = getSignatureFromDeclaration(container);
67074                         if (sig.thisParameter) {
67075                             return sig.thisParameter;
67076                         }
67077                     }
67078                     if (ts.isInExpressionContext(node)) {
67079                         return checkExpression(node).symbol;
67080                     }
67081                 // falls through
67082                 case 183 /* ThisType */:
67083                     return getTypeFromThisTypeNode(node).symbol;
67084                 case 102 /* SuperKeyword */:
67085                     return checkExpression(node).symbol;
67086                 case 129 /* ConstructorKeyword */:
67087                     // constructor keyword for an overload, should take us to the definition if it exist
67088                     var constructorDeclaration = node.parent;
67089                     if (constructorDeclaration && constructorDeclaration.kind === 162 /* Constructor */) {
67090                         return constructorDeclaration.parent.symbol;
67091                     }
67092                     return undefined;
67093                 case 10 /* StringLiteral */:
67094                 case 14 /* NoSubstitutionTemplateLiteral */:
67095                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
67096                     // 2). External module name in an import declaration
67097                     // 3). Dynamic import call or require in javascript
67098                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
67099                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
67100                         ((node.parent.kind === 254 /* ImportDeclaration */ || node.parent.kind === 260 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
67101                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
67102                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
67103                         return resolveExternalModuleName(node, node, ignoreErrors);
67104                     }
67105                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
67106                         return getSymbolOfNode(parent);
67107                     }
67108                 // falls through
67109                 case 8 /* NumericLiteral */:
67110                     // index access
67111                     var objectType = ts.isElementAccessExpression(parent)
67112                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
67113                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
67114                             ? getTypeFromTypeNode(grandParent.objectType)
67115                             : undefined;
67116                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
67117                 case 84 /* DefaultKeyword */:
67118                 case 94 /* FunctionKeyword */:
67119                 case 38 /* EqualsGreaterThanToken */:
67120                 case 80 /* ClassKeyword */:
67121                     return getSymbolOfNode(node.parent);
67122                 case 188 /* ImportType */:
67123                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
67124                 case 89 /* ExportKeyword */:
67125                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
67126                 default:
67127                     return undefined;
67128             }
67129         }
67130         function getShorthandAssignmentValueSymbol(location) {
67131             if (location && location.kind === 282 /* ShorthandPropertyAssignment */) {
67132                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
67133             }
67134             return undefined;
67135         }
67136         /** Returns the target of an export specifier without following aliases */
67137         function getExportSpecifierLocalTargetSymbol(node) {
67138             return node.parent.parent.moduleSpecifier ?
67139                 getExternalModuleMember(node.parent.parent, node) :
67140                 resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
67141         }
67142         function getTypeOfNode(node) {
67143             if (node.flags & 16777216 /* InWithStatement */) {
67144                 // We cannot answer semantic questions within a with block, do not proceed any further
67145                 return errorType;
67146             }
67147             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
67148             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
67149             if (ts.isPartOfTypeNode(node)) {
67150                 var typeFromTypeNode = getTypeFromTypeNode(node);
67151                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
67152             }
67153             if (ts.isExpressionNode(node)) {
67154                 return getRegularTypeOfExpression(node);
67155             }
67156             if (classType && !classDecl.isImplements) {
67157                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
67158                 // extends clause of a class. We handle that case here.
67159                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
67160                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
67161             }
67162             if (isTypeDeclaration(node)) {
67163                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67164                 var symbol = getSymbolOfNode(node);
67165                 return getDeclaredTypeOfSymbol(symbol);
67166             }
67167             if (isTypeDeclarationName(node)) {
67168                 var symbol = getSymbolAtLocation(node);
67169                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
67170             }
67171             if (ts.isDeclaration(node)) {
67172                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67173                 var symbol = getSymbolOfNode(node);
67174                 return getTypeOfSymbol(symbol);
67175             }
67176             if (isDeclarationNameOrImportPropertyName(node)) {
67177                 var symbol = getSymbolAtLocation(node);
67178                 if (symbol) {
67179                     return getTypeOfSymbol(symbol);
67180                 }
67181                 return errorType;
67182             }
67183             if (ts.isBindingPattern(node)) {
67184                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
67185             }
67186             if (isInRightSideOfImportOrExportAssignment(node)) {
67187                 var symbol = getSymbolAtLocation(node);
67188                 if (symbol) {
67189                     var declaredType = getDeclaredTypeOfSymbol(symbol);
67190                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
67191                 }
67192             }
67193             return errorType;
67194         }
67195         // Gets the type of object literal or array literal of destructuring assignment.
67196         // { a } from
67197         //     for ( { a } of elems) {
67198         //     }
67199         // [ a ] from
67200         //     [a] = [ some array ...]
67201         function getTypeOfAssignmentPattern(expr) {
67202             ts.Debug.assert(expr.kind === 193 /* ObjectLiteralExpression */ || expr.kind === 192 /* ArrayLiteralExpression */);
67203             // If this is from "for of"
67204             //     for ( { a } of elems) {
67205             //     }
67206             if (expr.parent.kind === 232 /* ForOfStatement */) {
67207                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
67208                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67209             }
67210             // If this is from "for" initializer
67211             //     for ({a } = elems[0];.....) { }
67212             if (expr.parent.kind === 209 /* BinaryExpression */) {
67213                 var iteratedType = getTypeOfExpression(expr.parent.right);
67214                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67215             }
67216             // If this is from nested object binding pattern
67217             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
67218             if (expr.parent.kind === 281 /* PropertyAssignment */) {
67219                 var node_4 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
67220                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_4) || errorType;
67221                 var propertyIndex = ts.indexOfNode(node_4.properties, expr.parent);
67222                 return checkObjectLiteralDestructuringPropertyAssignment(node_4, typeOfParentObjectLiteral, propertyIndex);
67223             }
67224             // Array literal assignment - array destructuring pattern
67225             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
67226             //    [{ property1: p1, property2 }] = elems;
67227             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
67228             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
67229             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
67230         }
67231         // Gets the property symbol corresponding to the property in destructuring assignment
67232         // 'property1' from
67233         //     for ( { property1: a } of elems) {
67234         //     }
67235         // 'property1' at location 'a' from:
67236         //     [a] = [ property1, property2 ]
67237         function getPropertySymbolOfDestructuringAssignment(location) {
67238             // Get the type of the object or array literal and then look for property of given name in the type
67239             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
67240             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
67241         }
67242         function getRegularTypeOfExpression(expr) {
67243             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
67244                 expr = expr.parent;
67245             }
67246             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
67247         }
67248         /**
67249          * Gets either the static or instance type of a class element, based on
67250          * whether the element is declared as "static".
67251          */
67252         function getParentTypeOfClassElement(node) {
67253             var classSymbol = getSymbolOfNode(node.parent);
67254             return ts.hasModifier(node, 32 /* Static */)
67255                 ? getTypeOfSymbol(classSymbol)
67256                 : getDeclaredTypeOfSymbol(classSymbol);
67257         }
67258         function getClassElementPropertyKeyType(element) {
67259             var name = element.name;
67260             switch (name.kind) {
67261                 case 75 /* Identifier */:
67262                     return getLiteralType(ts.idText(name));
67263                 case 8 /* NumericLiteral */:
67264                 case 10 /* StringLiteral */:
67265                     return getLiteralType(name.text);
67266                 case 154 /* ComputedPropertyName */:
67267                     var nameType = checkComputedPropertyName(name);
67268                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
67269                 default:
67270                     return ts.Debug.fail("Unsupported property name.");
67271             }
67272         }
67273         // Return the list of properties of the given type, augmented with properties from Function
67274         // if the type has call or construct signatures
67275         function getAugmentedPropertiesOfType(type) {
67276             type = getApparentType(type);
67277             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
67278             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
67279                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
67280                     undefined;
67281             if (functionType) {
67282                 ts.forEach(getPropertiesOfType(functionType), function (p) {
67283                     if (!propsByName.has(p.escapedName)) {
67284                         propsByName.set(p.escapedName, p);
67285                     }
67286                 });
67287             }
67288             return getNamedMembers(propsByName);
67289         }
67290         function typeHasCallOrConstructSignatures(type) {
67291             return ts.typeHasCallOrConstructSignatures(type, checker);
67292         }
67293         function getRootSymbols(symbol) {
67294             var roots = getImmediateRootSymbols(symbol);
67295             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
67296         }
67297         function getImmediateRootSymbols(symbol) {
67298             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
67299                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
67300             }
67301             else if (symbol.flags & 33554432 /* Transient */) {
67302                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
67303                 return leftSpread ? [leftSpread, rightSpread]
67304                     : syntheticOrigin ? [syntheticOrigin]
67305                         : ts.singleElementArray(tryGetAliasTarget(symbol));
67306             }
67307             return undefined;
67308         }
67309         function tryGetAliasTarget(symbol) {
67310             var target;
67311             var next = symbol;
67312             while (next = getSymbolLinks(next).target) {
67313                 target = next;
67314             }
67315             return target;
67316         }
67317         // Emitter support
67318         function isArgumentsLocalBinding(nodeIn) {
67319             if (!ts.isGeneratedIdentifier(nodeIn)) {
67320                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67321                 if (node) {
67322                     var isPropertyName_1 = node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node;
67323                     return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
67324                 }
67325             }
67326             return false;
67327         }
67328         function moduleExportsSomeValue(moduleReferenceExpression) {
67329             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
67330             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
67331                 // If the module is not found or is shorthand, assume that it may export a value.
67332                 return true;
67333             }
67334             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
67335             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
67336             // otherwise it will return moduleSymbol itself
67337             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
67338             var symbolLinks = getSymbolLinks(moduleSymbol);
67339             if (symbolLinks.exportsSomeValue === undefined) {
67340                 // for export assignments - check if resolved symbol for RHS is itself a value
67341                 // otherwise - check if at least one export is value
67342                 symbolLinks.exportsSomeValue = hasExportAssignment
67343                     ? !!(moduleSymbol.flags & 111551 /* Value */)
67344                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
67345             }
67346             return symbolLinks.exportsSomeValue;
67347             function isValue(s) {
67348                 s = resolveSymbol(s);
67349                 return s && !!(s.flags & 111551 /* Value */);
67350             }
67351         }
67352         function isNameOfModuleOrEnumDeclaration(node) {
67353             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
67354         }
67355         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
67356         // node of the exported entity's container. Otherwise, return undefined.
67357         function getReferencedExportContainer(nodeIn, prefixLocals) {
67358             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67359             if (node) {
67360                 // When resolving the export container for the name of a module or enum
67361                 // declaration, we need to start resolution at the declaration's container.
67362                 // Otherwise, we could incorrectly resolve the export container as the
67363                 // declaration if it contains an exported member with the same name.
67364                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
67365                 if (symbol) {
67366                     if (symbol.flags & 1048576 /* ExportValue */) {
67367                         // If we reference an exported entity within the same module declaration, then whether
67368                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
67369                         // kinds that we do NOT prefix.
67370                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
67371                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
67372                             return undefined;
67373                         }
67374                         symbol = exportSymbol;
67375                     }
67376                     var parentSymbol_1 = getParentOfSymbol(symbol);
67377                     if (parentSymbol_1) {
67378                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 290 /* SourceFile */) {
67379                             var symbolFile = parentSymbol_1.valueDeclaration;
67380                             var referenceFile = ts.getSourceFileOfNode(node);
67381                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
67382                             var symbolIsUmdExport = symbolFile !== referenceFile;
67383                             return symbolIsUmdExport ? undefined : symbolFile;
67384                         }
67385                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
67386                     }
67387                 }
67388             }
67389         }
67390         // When resolved as an expression identifier, if the given node references an import, return the declaration of
67391         // that import. Otherwise, return undefined.
67392         function getReferencedImportDeclaration(nodeIn) {
67393             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67394             if (node) {
67395                 var symbol = getReferencedValueSymbol(node);
67396                 // We should only get the declaration of an alias if there isn't a local value
67397                 // declaration for the symbol
67398                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
67399                     return getDeclarationOfAliasSymbol(symbol);
67400                 }
67401             }
67402             return undefined;
67403         }
67404         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
67405             return ts.isBindingElement(symbol.valueDeclaration)
67406                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 280 /* CatchClause */;
67407         }
67408         function isSymbolOfDeclarationWithCollidingName(symbol) {
67409             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
67410                 var links = getSymbolLinks(symbol);
67411                 if (links.isDeclarationWithCollidingName === undefined) {
67412                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
67413                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
67414                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
67415                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
67416                             // redeclaration - always should be renamed
67417                             links.isDeclarationWithCollidingName = true;
67418                         }
67419                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
67420                             // binding is captured in the function
67421                             // should be renamed if:
67422                             // - binding is not top level - top level bindings never collide with anything
67423                             // AND
67424                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
67425                             //     let a, b
67426                             //     { let x = 1; a = () => x; }
67427                             //     { let x = 100; b = () => x; }
67428                             //     console.log(a()); // should print '1'
67429                             //     console.log(b()); // should print '100'
67430                             //     OR
67431                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
67432                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
67433                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
67434                             //       they will not collide with anything
67435                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
67436                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
67437                             var inLoopBodyBlock = container.kind === 223 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
67438                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
67439                         }
67440                         else {
67441                             links.isDeclarationWithCollidingName = false;
67442                         }
67443                     }
67444                 }
67445                 return links.isDeclarationWithCollidingName;
67446             }
67447             return false;
67448         }
67449         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
67450         // a name that either hides an existing name or might hide it when compiled downlevel,
67451         // return the declaration of that entity. Otherwise, return undefined.
67452         function getReferencedDeclarationWithCollidingName(nodeIn) {
67453             if (!ts.isGeneratedIdentifier(nodeIn)) {
67454                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67455                 if (node) {
67456                     var symbol = getReferencedValueSymbol(node);
67457                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
67458                         return symbol.valueDeclaration;
67459                     }
67460                 }
67461             }
67462             return undefined;
67463         }
67464         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
67465         // existing name or might hide a name when compiled downlevel
67466         function isDeclarationWithCollidingName(nodeIn) {
67467             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67468             if (node) {
67469                 var symbol = getSymbolOfNode(node);
67470                 if (symbol) {
67471                     return isSymbolOfDeclarationWithCollidingName(symbol);
67472                 }
67473             }
67474             return false;
67475         }
67476         function isValueAliasDeclaration(node) {
67477             switch (node.kind) {
67478                 case 253 /* ImportEqualsDeclaration */:
67479                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
67480                 case 255 /* ImportClause */:
67481                 case 256 /* NamespaceImport */:
67482                 case 258 /* ImportSpecifier */:
67483                 case 263 /* ExportSpecifier */:
67484                     var symbol = getSymbolOfNode(node) || unknownSymbol;
67485                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
67486                 case 260 /* ExportDeclaration */:
67487                     var exportClause = node.exportClause;
67488                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
67489                         ts.some(exportClause.elements, isValueAliasDeclaration));
67490                 case 259 /* ExportAssignment */:
67491                     return node.expression && node.expression.kind === 75 /* Identifier */ ?
67492                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
67493                         true;
67494             }
67495             return false;
67496         }
67497         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
67498             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
67499             if (node === undefined || node.parent.kind !== 290 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
67500                 // parent is not source file or it is not reference to internal module
67501                 return false;
67502             }
67503             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
67504             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
67505         }
67506         function isAliasResolvedToValue(symbol) {
67507             var target = resolveAlias(symbol);
67508             if (target === unknownSymbol) {
67509                 return true;
67510             }
67511             // const enums and modules that contain only const enums are not considered values from the emit perspective
67512             // unless 'preserveConstEnums' option is set to true
67513             return !!(target.flags & 111551 /* Value */) &&
67514                 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
67515         }
67516         function isConstEnumOrConstEnumOnlyModule(s) {
67517             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
67518         }
67519         function isReferencedAliasDeclaration(node, checkChildren) {
67520             if (isAliasSymbolDeclaration(node)) {
67521                 var symbol = getSymbolOfNode(node);
67522                 if (symbol && getSymbolLinks(symbol).referenced) {
67523                     return true;
67524                 }
67525                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
67526                 if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
67527                     target.flags & 111551 /* Value */ &&
67528                     (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
67529                     // An `export import ... =` of a value symbol is always considered referenced
67530                     return true;
67531                 }
67532             }
67533             if (checkChildren) {
67534                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
67535             }
67536             return false;
67537         }
67538         function isImplementationOfOverload(node) {
67539             if (ts.nodeIsPresent(node.body)) {
67540                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
67541                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
67542                 var symbol = getSymbolOfNode(node);
67543                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
67544                 // If this function body corresponds to function with multiple signature, it is implementation of overload
67545                 // e.g.: function foo(a: string): string;
67546                 //       function foo(a: number): number;
67547                 //       function foo(a: any) { // This is implementation of the overloads
67548                 //           return a;
67549                 //       }
67550                 return signaturesOfSymbol.length > 1 ||
67551                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
67552                     // e.g.: function foo(a: string): string;
67553                     //       function foo(a: any) { // This is implementation of the overloads
67554                     //           return a;
67555                     //       }
67556                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
67557             }
67558             return false;
67559         }
67560         function isRequiredInitializedParameter(parameter) {
67561             return !!strictNullChecks &&
67562                 !isOptionalParameter(parameter) &&
67563                 !ts.isJSDocParameterTag(parameter) &&
67564                 !!parameter.initializer &&
67565                 !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67566         }
67567         function isOptionalUninitializedParameterProperty(parameter) {
67568             return strictNullChecks &&
67569                 isOptionalParameter(parameter) &&
67570                 !parameter.initializer &&
67571                 ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67572         }
67573         function isExpandoFunctionDeclaration(node) {
67574             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67575             if (!declaration) {
67576                 return false;
67577             }
67578             var symbol = getSymbolOfNode(declaration);
67579             if (!symbol || !(symbol.flags & 16 /* Function */)) {
67580                 return false;
67581             }
67582             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
67583         }
67584         function getPropertiesOfContainerFunction(node) {
67585             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67586             if (!declaration) {
67587                 return ts.emptyArray;
67588             }
67589             var symbol = getSymbolOfNode(declaration);
67590             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
67591         }
67592         function getNodeCheckFlags(node) {
67593             return getNodeLinks(node).flags || 0;
67594         }
67595         function getEnumMemberValue(node) {
67596             computeEnumMemberValues(node.parent);
67597             return getNodeLinks(node).enumMemberValue;
67598         }
67599         function canHaveConstantValue(node) {
67600             switch (node.kind) {
67601                 case 284 /* EnumMember */:
67602                 case 194 /* PropertyAccessExpression */:
67603                 case 195 /* ElementAccessExpression */:
67604                     return true;
67605             }
67606             return false;
67607         }
67608         function getConstantValue(node) {
67609             if (node.kind === 284 /* EnumMember */) {
67610                 return getEnumMemberValue(node);
67611             }
67612             var symbol = getNodeLinks(node).resolvedSymbol;
67613             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
67614                 // inline property\index accesses only for const enums
67615                 var member = symbol.valueDeclaration;
67616                 if (ts.isEnumConst(member.parent)) {
67617                     return getEnumMemberValue(member);
67618                 }
67619             }
67620             return undefined;
67621         }
67622         function isFunctionType(type) {
67623             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
67624         }
67625         function getTypeReferenceSerializationKind(typeNameIn, location) {
67626             // ensure both `typeName` and `location` are parse tree nodes.
67627             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
67628             if (!typeName)
67629                 return ts.TypeReferenceSerializationKind.Unknown;
67630             if (location) {
67631                 location = ts.getParseTreeNode(location);
67632                 if (!location)
67633                     return ts.TypeReferenceSerializationKind.Unknown;
67634             }
67635             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
67636             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67637             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
67638             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67639             if (valueSymbol && valueSymbol === typeSymbol) {
67640                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
67641                 if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
67642                     return ts.TypeReferenceSerializationKind.Promise;
67643                 }
67644                 var constructorType = getTypeOfSymbol(valueSymbol);
67645                 if (constructorType && isConstructorType(constructorType)) {
67646                     return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
67647                 }
67648             }
67649             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
67650             if (!typeSymbol) {
67651                 return ts.TypeReferenceSerializationKind.Unknown;
67652             }
67653             var type = getDeclaredTypeOfSymbol(typeSymbol);
67654             if (type === errorType) {
67655                 return ts.TypeReferenceSerializationKind.Unknown;
67656             }
67657             else if (type.flags & 3 /* AnyOrUnknown */) {
67658                 return ts.TypeReferenceSerializationKind.ObjectType;
67659             }
67660             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
67661                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
67662             }
67663             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
67664                 return ts.TypeReferenceSerializationKind.BooleanType;
67665             }
67666             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
67667                 return ts.TypeReferenceSerializationKind.NumberLikeType;
67668             }
67669             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
67670                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
67671             }
67672             else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
67673                 return ts.TypeReferenceSerializationKind.StringLikeType;
67674             }
67675             else if (isTupleType(type)) {
67676                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67677             }
67678             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
67679                 return ts.TypeReferenceSerializationKind.ESSymbolType;
67680             }
67681             else if (isFunctionType(type)) {
67682                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
67683             }
67684             else if (isArrayType(type)) {
67685                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67686             }
67687             else {
67688                 return ts.TypeReferenceSerializationKind.ObjectType;
67689             }
67690         }
67691         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
67692             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
67693             if (!declaration) {
67694                 return ts.createToken(125 /* AnyKeyword */);
67695             }
67696             // Get type of the symbol if this is the valid symbol otherwise get type at location
67697             var symbol = getSymbolOfNode(declaration);
67698             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
67699                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
67700                 : errorType;
67701             if (type.flags & 8192 /* UniqueESSymbol */ &&
67702                 type.symbol === symbol) {
67703                 flags |= 1048576 /* AllowUniqueESSymbolType */;
67704             }
67705             if (addUndefined) {
67706                 type = getOptionalType(type);
67707             }
67708             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67709         }
67710         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
67711             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
67712             if (!signatureDeclaration) {
67713                 return ts.createToken(125 /* AnyKeyword */);
67714             }
67715             var signature = getSignatureFromDeclaration(signatureDeclaration);
67716             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67717         }
67718         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
67719             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
67720             if (!expr) {
67721                 return ts.createToken(125 /* AnyKeyword */);
67722             }
67723             var type = getWidenedType(getRegularTypeOfExpression(expr));
67724             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67725         }
67726         function hasGlobalName(name) {
67727             return globals.has(ts.escapeLeadingUnderscores(name));
67728         }
67729         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
67730             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
67731             if (resolvedSymbol) {
67732                 return resolvedSymbol;
67733             }
67734             var location = reference;
67735             if (startInDeclarationContainer) {
67736                 // When resolving the name of a declaration as a value, we need to start resolution
67737                 // at a point outside of the declaration.
67738                 var parent = reference.parent;
67739                 if (ts.isDeclaration(parent) && reference === parent.name) {
67740                     location = getDeclarationContainer(parent);
67741                 }
67742             }
67743             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
67744         }
67745         function getReferencedValueDeclaration(referenceIn) {
67746             if (!ts.isGeneratedIdentifier(referenceIn)) {
67747                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
67748                 if (reference) {
67749                     var symbol = getReferencedValueSymbol(reference);
67750                     if (symbol) {
67751                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
67752                     }
67753                 }
67754             }
67755             return undefined;
67756         }
67757         function isLiteralConstDeclaration(node) {
67758             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
67759                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
67760             }
67761             return false;
67762         }
67763         function literalTypeToNode(type, enclosing, tracker) {
67764             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
67765                 : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
67766             return enumResult || ts.createLiteral(type.value);
67767         }
67768         function createLiteralConstValue(node, tracker) {
67769             var type = getTypeOfSymbol(getSymbolOfNode(node));
67770             return literalTypeToNode(type, node, tracker);
67771         }
67772         function getJsxFactoryEntity(location) {
67773             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
67774         }
67775         function createResolver() {
67776             // this variable and functions that use it are deliberately moved here from the outer scope
67777             // to avoid scope pollution
67778             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
67779             var fileToDirective;
67780             if (resolvedTypeReferenceDirectives) {
67781                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
67782                 fileToDirective = ts.createMap();
67783                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
67784                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
67785                         return;
67786                     }
67787                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
67788                     if (file) {
67789                         // Add the transitive closure of path references loaded by this file (as long as they are not)
67790                         // part of an existing type reference.
67791                         addReferencedFilesToTypeDirective(file, key);
67792                     }
67793                 });
67794             }
67795             return {
67796                 getReferencedExportContainer: getReferencedExportContainer,
67797                 getReferencedImportDeclaration: getReferencedImportDeclaration,
67798                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
67799                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
67800                 isValueAliasDeclaration: function (node) {
67801                     node = ts.getParseTreeNode(node);
67802                     // Synthesized nodes are always treated like values.
67803                     return node ? isValueAliasDeclaration(node) : true;
67804                 },
67805                 hasGlobalName: hasGlobalName,
67806                 isReferencedAliasDeclaration: function (node, checkChildren) {
67807                     node = ts.getParseTreeNode(node);
67808                     // Synthesized nodes are always treated as referenced.
67809                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
67810                 },
67811                 getNodeCheckFlags: function (node) {
67812                     node = ts.getParseTreeNode(node);
67813                     return node ? getNodeCheckFlags(node) : 0;
67814                 },
67815                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
67816                 isDeclarationVisible: isDeclarationVisible,
67817                 isImplementationOfOverload: isImplementationOfOverload,
67818                 isRequiredInitializedParameter: isRequiredInitializedParameter,
67819                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
67820                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
67821                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
67822                 createTypeOfDeclaration: createTypeOfDeclaration,
67823                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
67824                 createTypeOfExpression: createTypeOfExpression,
67825                 createLiteralConstValue: createLiteralConstValue,
67826                 isSymbolAccessible: isSymbolAccessible,
67827                 isEntityNameVisible: isEntityNameVisible,
67828                 getConstantValue: function (nodeIn) {
67829                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
67830                     return node ? getConstantValue(node) : undefined;
67831                 },
67832                 collectLinkedAliases: collectLinkedAliases,
67833                 getReferencedValueDeclaration: getReferencedValueDeclaration,
67834                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
67835                 isOptionalParameter: isOptionalParameter,
67836                 moduleExportsSomeValue: moduleExportsSomeValue,
67837                 isArgumentsLocalBinding: isArgumentsLocalBinding,
67838                 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
67839                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
67840                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
67841                 isLiteralConstDeclaration: isLiteralConstDeclaration,
67842                 isLateBound: function (nodeIn) {
67843                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67844                     var symbol = node && getSymbolOfNode(node);
67845                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
67846                 },
67847                 getJsxFactoryEntity: getJsxFactoryEntity,
67848                 getAllAccessorDeclarations: function (accessor) {
67849                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
67850                     var otherKind = accessor.kind === 164 /* SetAccessor */ ? 163 /* GetAccessor */ : 164 /* SetAccessor */;
67851                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
67852                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
67853                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
67854                     var setAccessor = accessor.kind === 164 /* SetAccessor */ ? accessor : otherAccessor;
67855                     var getAccessor = accessor.kind === 163 /* GetAccessor */ ? accessor : otherAccessor;
67856                     return {
67857                         firstAccessor: firstAccessor,
67858                         secondAccessor: secondAccessor,
67859                         setAccessor: setAccessor,
67860                         getAccessor: getAccessor
67861                     };
67862                 },
67863                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
67864                 isBindingCapturedByNode: function (node, decl) {
67865                     var parseNode = ts.getParseTreeNode(node);
67866                     var parseDecl = ts.getParseTreeNode(decl);
67867                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
67868                 },
67869                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
67870                     var n = ts.getParseTreeNode(node);
67871                     ts.Debug.assert(n && n.kind === 290 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
67872                     var sym = getSymbolOfNode(node);
67873                     if (!sym) {
67874                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
67875                     }
67876                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
67877                 },
67878                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
67879             };
67880             function isImportRequiredByAugmentation(node) {
67881                 var file = ts.getSourceFileOfNode(node);
67882                 if (!file.symbol)
67883                     return false;
67884                 var importTarget = getExternalModuleFileFromDeclaration(node);
67885                 if (!importTarget)
67886                     return false;
67887                 if (importTarget === file)
67888                     return false;
67889                 var exports = getExportsOfModule(file.symbol);
67890                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
67891                     var s = _a[_i];
67892                     if (s.mergeId) {
67893                         var merged = getMergedSymbol(s);
67894                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
67895                             var d = _c[_b];
67896                             var declFile = ts.getSourceFileOfNode(d);
67897                             if (declFile === importTarget) {
67898                                 return true;
67899                             }
67900                         }
67901                     }
67902                 }
67903                 return false;
67904             }
67905             function isInHeritageClause(node) {
67906                 return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */;
67907             }
67908             // defined here to avoid outer scope pollution
67909             function getTypeReferenceDirectivesForEntityName(node) {
67910                 // program does not have any files with type reference directives - bail out
67911                 if (!fileToDirective) {
67912                     return undefined;
67913                 }
67914                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
67915                 // qualified names can only be used as types\namespaces
67916                 // identifiers are treated as values only if they appear in type queries
67917                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
67918                 if ((node.kind === 75 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 194 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
67919                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
67920                 }
67921                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
67922                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
67923             }
67924             // defined here to avoid outer scope pollution
67925             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
67926                 // program does not have any files with type reference directives - bail out
67927                 if (!fileToDirective) {
67928                     return undefined;
67929                 }
67930                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
67931                     return undefined;
67932                 }
67933                 // check what declarations in the symbol can contribute to the target meaning
67934                 var typeReferenceDirectives;
67935                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67936                     var decl = _a[_i];
67937                     // check meaning of the local symbol to see if declaration needs to be analyzed further
67938                     if (decl.symbol && decl.symbol.flags & meaning) {
67939                         var file = ts.getSourceFileOfNode(decl);
67940                         var typeReferenceDirective = fileToDirective.get(file.path);
67941                         if (typeReferenceDirective) {
67942                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
67943                         }
67944                         else {
67945                             // found at least one entry that does not originate from type reference directive
67946                             return undefined;
67947                         }
67948                     }
67949                 }
67950                 return typeReferenceDirectives;
67951             }
67952             function isSymbolFromTypeDeclarationFile(symbol) {
67953                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
67954                 if (!symbol.declarations) {
67955                     return false;
67956                 }
67957                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
67958                 // external modules cannot define or contribute to type declaration files
67959                 var current = symbol;
67960                 while (true) {
67961                     var parent = getParentOfSymbol(current);
67962                     if (parent) {
67963                         current = parent;
67964                     }
67965                     else {
67966                         break;
67967                     }
67968                 }
67969                 if (current.valueDeclaration && current.valueDeclaration.kind === 290 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
67970                     return false;
67971                 }
67972                 // check that at least one declaration of top level symbol originates from type declaration file
67973                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67974                     var decl = _a[_i];
67975                     var file = ts.getSourceFileOfNode(decl);
67976                     if (fileToDirective.has(file.path)) {
67977                         return true;
67978                     }
67979                 }
67980                 return false;
67981             }
67982             function addReferencedFilesToTypeDirective(file, key) {
67983                 if (fileToDirective.has(file.path))
67984                     return;
67985                 fileToDirective.set(file.path, key);
67986                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
67987                     var fileName = _a[_i].fileName;
67988                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.originalFileName);
67989                     var referencedFile = host.getSourceFile(resolvedFile);
67990                     if (referencedFile) {
67991                         addReferencedFilesToTypeDirective(referencedFile, key);
67992                     }
67993                 }
67994             }
67995         }
67996         function getExternalModuleFileFromDeclaration(declaration) {
67997             var specifier = declaration.kind === 249 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
67998             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
67999             if (!moduleSymbol) {
68000                 return undefined;
68001             }
68002             return ts.getDeclarationOfKind(moduleSymbol, 290 /* SourceFile */);
68003         }
68004         function initializeTypeChecker() {
68005             // Bind all source files and propagate errors
68006             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
68007                 var file = _a[_i];
68008                 ts.bindSourceFile(file, compilerOptions);
68009             }
68010             amalgamatedDuplicates = ts.createMap();
68011             // Initialize global symbol table
68012             var augmentations;
68013             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
68014                 var file = _c[_b];
68015                 if (file.redirectInfo) {
68016                     continue;
68017                 }
68018                 if (!ts.isExternalOrCommonJsModule(file)) {
68019                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
68020                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
68021                     var fileGlobalThisSymbol = file.locals.get("globalThis");
68022                     if (fileGlobalThisSymbol) {
68023                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
68024                             var declaration = _e[_d];
68025                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
68026                         }
68027                     }
68028                     mergeSymbolTable(globals, file.locals);
68029                 }
68030                 if (file.jsGlobalAugmentations) {
68031                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
68032                 }
68033                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
68034                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
68035                 }
68036                 if (file.moduleAugmentations.length) {
68037                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
68038                 }
68039                 if (file.symbol && file.symbol.globalExports) {
68040                     // Merge in UMD exports with first-in-wins semantics (see #9771)
68041                     var source = file.symbol.globalExports;
68042                     source.forEach(function (sourceSymbol, id) {
68043                         if (!globals.has(id)) {
68044                             globals.set(id, sourceSymbol);
68045                         }
68046                     });
68047                 }
68048             }
68049             // We do global augmentations separately from module augmentations (and before creating global types) because they
68050             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
68051             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
68052             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
68053             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
68054             //       did module augmentations prior to finalizing the global types.
68055             if (augmentations) {
68056                 // merge _global_ module augmentations.
68057                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68058                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
68059                     var list = augmentations_1[_f];
68060                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
68061                         var augmentation = list_1[_g];
68062                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
68063                             continue;
68064                         mergeModuleAugmentation(augmentation);
68065                     }
68066                 }
68067             }
68068             // Setup global builtins
68069             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
68070             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
68071             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
68072             getSymbolLinks(unknownSymbol).type = errorType;
68073             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
68074             // Initialize special types
68075             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
68076             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
68077             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
68078             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68079             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68080             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
68081             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
68082             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
68083             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
68084             anyArrayType = createArrayType(anyType);
68085             autoArrayType = createArrayType(autoType);
68086             if (autoArrayType === emptyObjectType) {
68087                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
68088                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
68089             }
68090             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
68091             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
68092             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
68093             if (augmentations) {
68094                 // merge _nonglobal_ module augmentations.
68095                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68096                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
68097                     var list = augmentations_2[_h];
68098                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
68099                         var augmentation = list_2[_j];
68100                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
68101                             continue;
68102                         mergeModuleAugmentation(augmentation);
68103                     }
68104                 }
68105             }
68106             amalgamatedDuplicates.forEach(function (_a) {
68107                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
68108                 // If not many things conflict, issue individual errors
68109                 if (conflictingSymbols.size < 8) {
68110                     conflictingSymbols.forEach(function (_a, symbolName) {
68111                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
68112                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
68113                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
68114                             var node = firstFileLocations_1[_i];
68115                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
68116                         }
68117                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
68118                             var node = secondFileLocations_1[_b];
68119                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
68120                         }
68121                     });
68122                 }
68123                 else {
68124                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
68125                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
68126                     diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file)));
68127                     diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file)));
68128                 }
68129             });
68130             amalgamatedDuplicates = undefined;
68131         }
68132         function checkExternalEmitHelpers(location, helpers) {
68133             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
68134                 var sourceFile = ts.getSourceFileOfNode(location);
68135                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
68136                     var helpersModule = resolveHelpersModule(sourceFile, location);
68137                     if (helpersModule !== unknownSymbol) {
68138                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
68139                         for (var helper = 1 /* FirstEmitHelper */; helper <= 1048576 /* LastEmitHelper */; helper <<= 1) {
68140                             if (uncheckedHelpers & helper) {
68141                                 var name = getHelperName(helper);
68142                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
68143                                 if (!symbol) {
68144                                     error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name);
68145                                 }
68146                             }
68147                         }
68148                     }
68149                     requestedExternalEmitHelpers |= helpers;
68150                 }
68151             }
68152         }
68153         function getHelperName(helper) {
68154             switch (helper) {
68155                 case 1 /* Extends */: return "__extends";
68156                 case 2 /* Assign */: return "__assign";
68157                 case 4 /* Rest */: return "__rest";
68158                 case 8 /* Decorate */: return "__decorate";
68159                 case 16 /* Metadata */: return "__metadata";
68160                 case 32 /* Param */: return "__param";
68161                 case 64 /* Awaiter */: return "__awaiter";
68162                 case 128 /* Generator */: return "__generator";
68163                 case 256 /* Values */: return "__values";
68164                 case 512 /* Read */: return "__read";
68165                 case 1024 /* Spread */: return "__spread";
68166                 case 2048 /* SpreadArrays */: return "__spreadArrays";
68167                 case 4096 /* Await */: return "__await";
68168                 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
68169                 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
68170                 case 32768 /* AsyncValues */: return "__asyncValues";
68171                 case 65536 /* ExportStar */: return "__exportStar";
68172                 case 131072 /* MakeTemplateObject */: return "__makeTemplateObject";
68173                 case 262144 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
68174                 case 524288 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
68175                 case 1048576 /* CreateBinding */: return "__createBinding";
68176                 default: return ts.Debug.fail("Unrecognized helper");
68177             }
68178         }
68179         function resolveHelpersModule(node, errorNode) {
68180             if (!externalHelpersModule) {
68181                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
68182             }
68183             return externalHelpersModule;
68184         }
68185         // GRAMMAR CHECKING
68186         function checkGrammarDecoratorsAndModifiers(node) {
68187             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
68188         }
68189         function checkGrammarDecorators(node) {
68190             if (!node.decorators) {
68191                 return false;
68192             }
68193             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
68194                 if (node.kind === 161 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
68195                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
68196                 }
68197                 else {
68198                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
68199                 }
68200             }
68201             else if (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */) {
68202                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
68203                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
68204                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
68205                 }
68206             }
68207             return false;
68208         }
68209         function checkGrammarModifiers(node) {
68210             var quickResult = reportObviousModifierErrors(node);
68211             if (quickResult !== undefined) {
68212                 return quickResult;
68213             }
68214             var lastStatic, lastDeclare, lastAsync, lastReadonly;
68215             var flags = 0 /* None */;
68216             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
68217                 var modifier = _a[_i];
68218                 if (modifier.kind !== 138 /* ReadonlyKeyword */) {
68219                     if (node.kind === 158 /* PropertySignature */ || node.kind === 160 /* MethodSignature */) {
68220                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
68221                     }
68222                     if (node.kind === 167 /* IndexSignature */) {
68223                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
68224                     }
68225                 }
68226                 switch (modifier.kind) {
68227                     case 81 /* ConstKeyword */:
68228                         if (node.kind !== 248 /* EnumDeclaration */) {
68229                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(81 /* ConstKeyword */));
68230                         }
68231                         break;
68232                     case 119 /* PublicKeyword */:
68233                     case 118 /* ProtectedKeyword */:
68234                     case 117 /* PrivateKeyword */:
68235                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
68236                         if (flags & 28 /* AccessibilityModifier */) {
68237                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
68238                         }
68239                         else if (flags & 32 /* Static */) {
68240                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
68241                         }
68242                         else if (flags & 64 /* Readonly */) {
68243                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
68244                         }
68245                         else if (flags & 256 /* Async */) {
68246                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
68247                         }
68248                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68249                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
68250                         }
68251                         else if (flags & 128 /* Abstract */) {
68252                             if (modifier.kind === 117 /* PrivateKeyword */) {
68253                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
68254                             }
68255                             else {
68256                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
68257                             }
68258                         }
68259                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68260                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
68261                         }
68262                         flags |= ts.modifierToFlag(modifier.kind);
68263                         break;
68264                     case 120 /* StaticKeyword */:
68265                         if (flags & 32 /* Static */) {
68266                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
68267                         }
68268                         else if (flags & 64 /* Readonly */) {
68269                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
68270                         }
68271                         else if (flags & 256 /* Async */) {
68272                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
68273                         }
68274                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68275                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
68276                         }
68277                         else if (node.kind === 156 /* Parameter */) {
68278                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
68279                         }
68280                         else if (flags & 128 /* Abstract */) {
68281                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68282                         }
68283                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68284                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
68285                         }
68286                         flags |= 32 /* Static */;
68287                         lastStatic = modifier;
68288                         break;
68289                     case 138 /* ReadonlyKeyword */:
68290                         if (flags & 64 /* Readonly */) {
68291                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
68292                         }
68293                         else if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */ && node.kind !== 167 /* IndexSignature */ && node.kind !== 156 /* Parameter */) {
68294                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
68295                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
68296                         }
68297                         flags |= 64 /* Readonly */;
68298                         lastReadonly = modifier;
68299                         break;
68300                     case 89 /* ExportKeyword */:
68301                         if (flags & 1 /* Export */) {
68302                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
68303                         }
68304                         else if (flags & 2 /* Ambient */) {
68305                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
68306                         }
68307                         else if (flags & 128 /* Abstract */) {
68308                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
68309                         }
68310                         else if (flags & 256 /* Async */) {
68311                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
68312                         }
68313                         else if (ts.isClassLike(node.parent)) {
68314                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
68315                         }
68316                         else if (node.kind === 156 /* Parameter */) {
68317                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
68318                         }
68319                         flags |= 1 /* Export */;
68320                         break;
68321                     case 84 /* DefaultKeyword */:
68322                         var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
68323                         if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
68324                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
68325                         }
68326                         flags |= 512 /* Default */;
68327                         break;
68328                     case 130 /* DeclareKeyword */:
68329                         if (flags & 2 /* Ambient */) {
68330                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
68331                         }
68332                         else if (flags & 256 /* Async */) {
68333                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68334                         }
68335                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
68336                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
68337                         }
68338                         else if (node.kind === 156 /* Parameter */) {
68339                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
68340                         }
68341                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 250 /* ModuleBlock */) {
68342                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
68343                         }
68344                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68345                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
68346                         }
68347                         flags |= 2 /* Ambient */;
68348                         lastDeclare = modifier;
68349                         break;
68350                     case 122 /* AbstractKeyword */:
68351                         if (flags & 128 /* Abstract */) {
68352                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
68353                         }
68354                         if (node.kind !== 245 /* ClassDeclaration */) {
68355                             if (node.kind !== 161 /* MethodDeclaration */ &&
68356                                 node.kind !== 159 /* PropertyDeclaration */ &&
68357                                 node.kind !== 163 /* GetAccessor */ &&
68358                                 node.kind !== 164 /* SetAccessor */) {
68359                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
68360                             }
68361                             if (!(node.parent.kind === 245 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
68362                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
68363                             }
68364                             if (flags & 32 /* Static */) {
68365                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68366                             }
68367                             if (flags & 8 /* Private */) {
68368                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
68369                             }
68370                         }
68371                         if (ts.isNamedDeclaration(node) && node.name.kind === 76 /* PrivateIdentifier */) {
68372                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
68373                         }
68374                         flags |= 128 /* Abstract */;
68375                         break;
68376                     case 126 /* AsyncKeyword */:
68377                         if (flags & 256 /* Async */) {
68378                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
68379                         }
68380                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
68381                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68382                         }
68383                         else if (node.kind === 156 /* Parameter */) {
68384                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
68385                         }
68386                         flags |= 256 /* Async */;
68387                         lastAsync = modifier;
68388                         break;
68389                 }
68390             }
68391             if (node.kind === 162 /* Constructor */) {
68392                 if (flags & 32 /* Static */) {
68393                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
68394                 }
68395                 if (flags & 128 /* Abstract */) {
68396                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
68397                 }
68398                 else if (flags & 256 /* Async */) {
68399                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
68400                 }
68401                 else if (flags & 64 /* Readonly */) {
68402                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
68403                 }
68404                 return false;
68405             }
68406             else if ((node.kind === 254 /* ImportDeclaration */ || node.kind === 253 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
68407                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
68408             }
68409             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
68410                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
68411             }
68412             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
68413                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
68414             }
68415             if (flags & 256 /* Async */) {
68416                 return checkGrammarAsyncModifier(node, lastAsync);
68417             }
68418             return false;
68419         }
68420         /**
68421          * true | false: Early return this value from checkGrammarModifiers.
68422          * undefined: Need to do full checking on the modifiers.
68423          */
68424         function reportObviousModifierErrors(node) {
68425             return !node.modifiers
68426                 ? false
68427                 : shouldReportBadModifier(node)
68428                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
68429                     : undefined;
68430         }
68431         function shouldReportBadModifier(node) {
68432             switch (node.kind) {
68433                 case 163 /* GetAccessor */:
68434                 case 164 /* SetAccessor */:
68435                 case 162 /* Constructor */:
68436                 case 159 /* PropertyDeclaration */:
68437                 case 158 /* PropertySignature */:
68438                 case 161 /* MethodDeclaration */:
68439                 case 160 /* MethodSignature */:
68440                 case 167 /* IndexSignature */:
68441                 case 249 /* ModuleDeclaration */:
68442                 case 254 /* ImportDeclaration */:
68443                 case 253 /* ImportEqualsDeclaration */:
68444                 case 260 /* ExportDeclaration */:
68445                 case 259 /* ExportAssignment */:
68446                 case 201 /* FunctionExpression */:
68447                 case 202 /* ArrowFunction */:
68448                 case 156 /* Parameter */:
68449                     return false;
68450                 default:
68451                     if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68452                         return false;
68453                     }
68454                     switch (node.kind) {
68455                         case 244 /* FunctionDeclaration */:
68456                             return nodeHasAnyModifiersExcept(node, 126 /* AsyncKeyword */);
68457                         case 245 /* ClassDeclaration */:
68458                             return nodeHasAnyModifiersExcept(node, 122 /* AbstractKeyword */);
68459                         case 246 /* InterfaceDeclaration */:
68460                         case 225 /* VariableStatement */:
68461                         case 247 /* TypeAliasDeclaration */:
68462                             return true;
68463                         case 248 /* EnumDeclaration */:
68464                             return nodeHasAnyModifiersExcept(node, 81 /* ConstKeyword */);
68465                         default:
68466                             ts.Debug.fail();
68467                             return false;
68468                     }
68469             }
68470         }
68471         function nodeHasAnyModifiersExcept(node, allowedModifier) {
68472             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
68473         }
68474         function checkGrammarAsyncModifier(node, asyncModifier) {
68475             switch (node.kind) {
68476                 case 161 /* MethodDeclaration */:
68477                 case 244 /* FunctionDeclaration */:
68478                 case 201 /* FunctionExpression */:
68479                 case 202 /* ArrowFunction */:
68480                     return false;
68481             }
68482             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
68483         }
68484         function checkGrammarForDisallowedTrailingComma(list, diag) {
68485             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
68486             if (list && list.hasTrailingComma) {
68487                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
68488             }
68489             return false;
68490         }
68491         function checkGrammarTypeParameterList(typeParameters, file) {
68492             if (typeParameters && typeParameters.length === 0) {
68493                 var start = typeParameters.pos - "<".length;
68494                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
68495                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
68496             }
68497             return false;
68498         }
68499         function checkGrammarParameterList(parameters) {
68500             var seenOptionalParameter = false;
68501             var parameterCount = parameters.length;
68502             for (var i = 0; i < parameterCount; i++) {
68503                 var parameter = parameters[i];
68504                 if (parameter.dotDotDotToken) {
68505                     if (i !== (parameterCount - 1)) {
68506                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
68507                     }
68508                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
68509                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
68510                     }
68511                     if (parameter.questionToken) {
68512                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
68513                     }
68514                     if (parameter.initializer) {
68515                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
68516                     }
68517                 }
68518                 else if (parameter.questionToken) {
68519                     seenOptionalParameter = true;
68520                     if (parameter.initializer) {
68521                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
68522                     }
68523                 }
68524                 else if (seenOptionalParameter && !parameter.initializer) {
68525                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
68526                 }
68527             }
68528         }
68529         function getNonSimpleParameters(parameters) {
68530             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
68531         }
68532         function checkGrammarForUseStrictSimpleParameterList(node) {
68533             if (languageVersion >= 3 /* ES2016 */) {
68534                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
68535                 if (useStrictDirective_1) {
68536                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
68537                     if (ts.length(nonSimpleParameters)) {
68538                         ts.forEach(nonSimpleParameters, function (parameter) {
68539                             ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
68540                         });
68541                         var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
68542                         ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_1));
68543                         return true;
68544                     }
68545                 }
68546             }
68547             return false;
68548         }
68549         function checkGrammarFunctionLikeDeclaration(node) {
68550             // Prevent cascading error by short-circuit
68551             var file = ts.getSourceFileOfNode(node);
68552             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
68553                 checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
68554                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
68555         }
68556         function checkGrammarClassLikeDeclaration(node) {
68557             var file = ts.getSourceFileOfNode(node);
68558             return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
68559         }
68560         function checkGrammarArrowFunction(node, file) {
68561             if (!ts.isArrowFunction(node)) {
68562                 return false;
68563             }
68564             var equalsGreaterThanToken = node.equalsGreaterThanToken;
68565             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
68566             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
68567             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
68568         }
68569         function checkGrammarIndexSignatureParameters(node) {
68570             var parameter = node.parameters[0];
68571             if (node.parameters.length !== 1) {
68572                 if (parameter) {
68573                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68574                 }
68575                 else {
68576                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68577                 }
68578             }
68579             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
68580             if (parameter.dotDotDotToken) {
68581                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
68582             }
68583             if (ts.hasModifiers(parameter)) {
68584                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
68585             }
68586             if (parameter.questionToken) {
68587                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
68588             }
68589             if (parameter.initializer) {
68590                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
68591             }
68592             if (!parameter.type) {
68593                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
68594             }
68595             if (parameter.type.kind !== 143 /* StringKeyword */ && parameter.type.kind !== 140 /* NumberKeyword */) {
68596                 var type = getTypeFromTypeNode(parameter.type);
68597                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
68598                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType));
68599                 }
68600                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
68601                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
68602                 }
68603                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
68604             }
68605             if (!node.type) {
68606                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
68607             }
68608             return false;
68609         }
68610         function checkGrammarIndexSignature(node) {
68611             // Prevent cascading error by short-circuit
68612             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
68613         }
68614         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
68615             if (typeArguments && typeArguments.length === 0) {
68616                 var sourceFile = ts.getSourceFileOfNode(node);
68617                 var start = typeArguments.pos - "<".length;
68618                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
68619                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
68620             }
68621             return false;
68622         }
68623         function checkGrammarTypeArguments(node, typeArguments) {
68624             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
68625                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
68626         }
68627         function checkGrammarTaggedTemplateChain(node) {
68628             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
68629                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
68630             }
68631             return false;
68632         }
68633         function checkGrammarForOmittedArgument(args) {
68634             if (args) {
68635                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
68636                     var arg = args_4[_i];
68637                     if (arg.kind === 215 /* OmittedExpression */) {
68638                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
68639                     }
68640                 }
68641             }
68642             return false;
68643         }
68644         function checkGrammarArguments(args) {
68645             return checkGrammarForOmittedArgument(args);
68646         }
68647         function checkGrammarHeritageClause(node) {
68648             var types = node.types;
68649             if (checkGrammarForDisallowedTrailingComma(types)) {
68650                 return true;
68651             }
68652             if (types && types.length === 0) {
68653                 var listType = ts.tokenToString(node.token);
68654                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
68655             }
68656             return ts.some(types, checkGrammarExpressionWithTypeArguments);
68657         }
68658         function checkGrammarExpressionWithTypeArguments(node) {
68659             return checkGrammarTypeArguments(node, node.typeArguments);
68660         }
68661         function checkGrammarClassDeclarationHeritageClauses(node) {
68662             var seenExtendsClause = false;
68663             var seenImplementsClause = false;
68664             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
68665                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68666                     var heritageClause = _a[_i];
68667                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68668                         if (seenExtendsClause) {
68669                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68670                         }
68671                         if (seenImplementsClause) {
68672                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
68673                         }
68674                         if (heritageClause.types.length > 1) {
68675                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
68676                         }
68677                         seenExtendsClause = true;
68678                     }
68679                     else {
68680                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68681                         if (seenImplementsClause) {
68682                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
68683                         }
68684                         seenImplementsClause = true;
68685                     }
68686                     // Grammar checking heritageClause inside class declaration
68687                     checkGrammarHeritageClause(heritageClause);
68688                 }
68689             }
68690         }
68691         function checkGrammarInterfaceDeclaration(node) {
68692             var seenExtendsClause = false;
68693             if (node.heritageClauses) {
68694                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68695                     var heritageClause = _a[_i];
68696                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68697                         if (seenExtendsClause) {
68698                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68699                         }
68700                         seenExtendsClause = true;
68701                     }
68702                     else {
68703                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68704                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
68705                     }
68706                     // Grammar checking heritageClause inside class declaration
68707                     checkGrammarHeritageClause(heritageClause);
68708                 }
68709             }
68710             return false;
68711         }
68712         function checkGrammarComputedPropertyName(node) {
68713             // If node is not a computedPropertyName, just skip the grammar checking
68714             if (node.kind !== 154 /* ComputedPropertyName */) {
68715                 return false;
68716             }
68717             var computedPropertyName = node;
68718             if (computedPropertyName.expression.kind === 209 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
68719                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
68720             }
68721             return false;
68722         }
68723         function checkGrammarForGenerator(node) {
68724             if (node.asteriskToken) {
68725                 ts.Debug.assert(node.kind === 244 /* FunctionDeclaration */ ||
68726                     node.kind === 201 /* FunctionExpression */ ||
68727                     node.kind === 161 /* MethodDeclaration */);
68728                 if (node.flags & 8388608 /* Ambient */) {
68729                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
68730                 }
68731                 if (!node.body) {
68732                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
68733                 }
68734             }
68735         }
68736         function checkGrammarForInvalidQuestionMark(questionToken, message) {
68737             return !!questionToken && grammarErrorOnNode(questionToken, message);
68738         }
68739         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
68740             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
68741         }
68742         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
68743             var seen = ts.createUnderscoreEscapedMap();
68744             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
68745                 var prop = _a[_i];
68746                 if (prop.kind === 283 /* SpreadAssignment */) {
68747                     if (inDestructuring) {
68748                         // a rest property cannot be destructured any further
68749                         var expression = ts.skipParentheses(prop.expression);
68750                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
68751                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
68752                         }
68753                     }
68754                     continue;
68755                 }
68756                 var name = prop.name;
68757                 if (name.kind === 154 /* ComputedPropertyName */) {
68758                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
68759                     checkGrammarComputedPropertyName(name);
68760                 }
68761                 if (prop.kind === 282 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
68762                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
68763                     // outside of destructuring it is a syntax error
68764                     return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
68765                 }
68766                 if (name.kind === 76 /* PrivateIdentifier */) {
68767                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
68768                 }
68769                 // Modifiers are never allowed on properties except for 'async' on a method declaration
68770                 if (prop.modifiers) {
68771                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
68772                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
68773                         var mod = _c[_b];
68774                         if (mod.kind !== 126 /* AsyncKeyword */ || prop.kind !== 161 /* MethodDeclaration */) {
68775                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
68776                         }
68777                     }
68778                 }
68779                 // ECMA-262 11.1.5 Object Initializer
68780                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
68781                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
68782                 // IsDataDescriptor(propId.descriptor) is true.
68783                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
68784                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
68785                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
68786                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
68787                 var currentKind = void 0;
68788                 switch (prop.kind) {
68789                     case 282 /* ShorthandPropertyAssignment */:
68790                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
68791                     // falls through
68792                     case 281 /* PropertyAssignment */:
68793                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
68794                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
68795                         if (name.kind === 8 /* NumericLiteral */) {
68796                             checkGrammarNumericLiteral(name);
68797                         }
68798                         currentKind = 4 /* PropertyAssignment */;
68799                         break;
68800                     case 161 /* MethodDeclaration */:
68801                         currentKind = 8 /* Method */;
68802                         break;
68803                     case 163 /* GetAccessor */:
68804                         currentKind = 1 /* GetAccessor */;
68805                         break;
68806                     case 164 /* SetAccessor */:
68807                         currentKind = 2 /* SetAccessor */;
68808                         break;
68809                     default:
68810                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
68811                 }
68812                 if (!inDestructuring) {
68813                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
68814                     if (effectiveName === undefined) {
68815                         continue;
68816                     }
68817                     var existingKind = seen.get(effectiveName);
68818                     if (!existingKind) {
68819                         seen.set(effectiveName, currentKind);
68820                     }
68821                     else {
68822                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
68823                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
68824                         }
68825                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
68826                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
68827                                 seen.set(effectiveName, currentKind | existingKind);
68828                             }
68829                             else {
68830                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
68831                             }
68832                         }
68833                         else {
68834                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
68835                         }
68836                     }
68837                 }
68838             }
68839         }
68840         function checkGrammarJsxElement(node) {
68841             checkGrammarTypeArguments(node, node.typeArguments);
68842             var seen = ts.createUnderscoreEscapedMap();
68843             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
68844                 var attr = _a[_i];
68845                 if (attr.kind === 275 /* JsxSpreadAttribute */) {
68846                     continue;
68847                 }
68848                 var name = attr.name, initializer = attr.initializer;
68849                 if (!seen.get(name.escapedText)) {
68850                     seen.set(name.escapedText, true);
68851                 }
68852                 else {
68853                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
68854                 }
68855                 if (initializer && initializer.kind === 276 /* JsxExpression */ && !initializer.expression) {
68856                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
68857                 }
68858             }
68859         }
68860         function checkGrammarJsxExpression(node) {
68861             if (node.expression && ts.isCommaSequence(node.expression)) {
68862                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
68863             }
68864         }
68865         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
68866             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
68867                 return true;
68868             }
68869             if (forInOrOfStatement.kind === 232 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
68870                 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
68871                     // use of 'for-await-of' in non-async function
68872                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
68873                     if (!hasParseDiagnostics(sourceFile)) {
68874                         var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
68875                         var func = ts.getContainingFunction(forInOrOfStatement);
68876                         if (func && func.kind !== 162 /* Constructor */) {
68877                             ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
68878                             var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
68879                             ts.addRelatedInfo(diagnostic, relatedInfo);
68880                         }
68881                         diagnostics.add(diagnostic);
68882                         return true;
68883                     }
68884                     return false;
68885                 }
68886             }
68887             if (forInOrOfStatement.initializer.kind === 243 /* VariableDeclarationList */) {
68888                 var variableList = forInOrOfStatement.initializer;
68889                 if (!checkGrammarVariableDeclarationList(variableList)) {
68890                     var declarations = variableList.declarations;
68891                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
68892                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
68893                     // For example:
68894                     //      var let = 10;
68895                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
68896                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
68897                     // We will then want to skip on grammar checking on variableList declaration
68898                     if (!declarations.length) {
68899                         return false;
68900                     }
68901                     if (declarations.length > 1) {
68902                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68903                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
68904                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
68905                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
68906                     }
68907                     var firstDeclaration = declarations[0];
68908                     if (firstDeclaration.initializer) {
68909                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68910                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
68911                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
68912                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
68913                     }
68914                     if (firstDeclaration.type) {
68915                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68916                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
68917                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
68918                         return grammarErrorOnNode(firstDeclaration, diagnostic);
68919                     }
68920                 }
68921             }
68922             return false;
68923         }
68924         function checkGrammarAccessor(accessor) {
68925             if (!(accessor.flags & 8388608 /* Ambient */)) {
68926                 if (languageVersion < 1 /* ES5 */) {
68927                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
68928                 }
68929                 if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
68930                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
68931                 }
68932             }
68933             if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
68934                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
68935             }
68936             if (accessor.typeParameters) {
68937                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
68938             }
68939             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
68940                 return grammarErrorOnNode(accessor.name, accessor.kind === 163 /* GetAccessor */ ?
68941                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
68942                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
68943             }
68944             if (accessor.kind === 164 /* SetAccessor */) {
68945                 if (accessor.type) {
68946                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
68947                 }
68948                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
68949                 if (parameter.dotDotDotToken) {
68950                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
68951                 }
68952                 if (parameter.questionToken) {
68953                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
68954                 }
68955                 if (parameter.initializer) {
68956                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
68957                 }
68958             }
68959             return false;
68960         }
68961         /** Does the accessor have the right number of parameters?
68962          * A get accessor has no parameters or a single `this` parameter.
68963          * A set accessor has one parameter or a `this` parameter and one more parameter.
68964          */
68965         function doesAccessorHaveCorrectParameterCount(accessor) {
68966             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 0 : 1);
68967         }
68968         function getAccessorThisParameter(accessor) {
68969             if (accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 1 : 2)) {
68970                 return ts.getThisParameter(accessor);
68971             }
68972         }
68973         function checkGrammarTypeOperatorNode(node) {
68974             if (node.operator === 147 /* UniqueKeyword */) {
68975                 if (node.type.kind !== 144 /* SymbolKeyword */) {
68976                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(144 /* SymbolKeyword */));
68977                 }
68978                 var parent = ts.walkUpParenthesizedTypes(node.parent);
68979                 switch (parent.kind) {
68980                     case 242 /* VariableDeclaration */:
68981                         var decl = parent;
68982                         if (decl.name.kind !== 75 /* Identifier */) {
68983                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
68984                         }
68985                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
68986                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
68987                         }
68988                         if (!(decl.parent.flags & 2 /* Const */)) {
68989                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
68990                         }
68991                         break;
68992                     case 159 /* PropertyDeclaration */:
68993                         if (!ts.hasModifier(parent, 32 /* Static */) ||
68994                             !ts.hasModifier(parent, 64 /* Readonly */)) {
68995                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
68996                         }
68997                         break;
68998                     case 158 /* PropertySignature */:
68999                         if (!ts.hasModifier(parent, 64 /* Readonly */)) {
69000                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
69001                         }
69002                         break;
69003                     default:
69004                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
69005                 }
69006             }
69007             else if (node.operator === 138 /* ReadonlyKeyword */) {
69008                 if (node.type.kind !== 174 /* ArrayType */ && node.type.kind !== 175 /* TupleType */) {
69009                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(144 /* SymbolKeyword */));
69010                 }
69011             }
69012         }
69013         function checkGrammarForInvalidDynamicName(node, message) {
69014             if (isNonBindableDynamicName(node)) {
69015                 return grammarErrorOnNode(node, message);
69016             }
69017         }
69018         function checkGrammarMethod(node) {
69019             if (checkGrammarFunctionLikeDeclaration(node)) {
69020                 return true;
69021             }
69022             if (node.kind === 161 /* MethodDeclaration */) {
69023                 if (node.parent.kind === 193 /* ObjectLiteralExpression */) {
69024                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
69025                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 126 /* AsyncKeyword */)) {
69026                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
69027                     }
69028                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
69029                         return true;
69030                     }
69031                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
69032                         return true;
69033                     }
69034                     else if (node.body === undefined) {
69035                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
69036                     }
69037                 }
69038                 if (checkGrammarForGenerator(node)) {
69039                     return true;
69040                 }
69041             }
69042             if (ts.isClassLike(node.parent)) {
69043                 // Technically, computed properties in ambient contexts is disallowed
69044                 // for property declarations and accessors too, not just methods.
69045                 // However, property declarations disallow computed names in general,
69046                 // and accessors are not allowed in ambient contexts in general,
69047                 // so this error only really matters for methods.
69048                 if (node.flags & 8388608 /* Ambient */) {
69049                     return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
69050                 }
69051                 else if (node.kind === 161 /* MethodDeclaration */ && !node.body) {
69052                     return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
69053                 }
69054             }
69055             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69056                 return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
69057             }
69058             else if (node.parent.kind === 173 /* TypeLiteral */) {
69059                 return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
69060             }
69061         }
69062         function checkGrammarBreakOrContinueStatement(node) {
69063             var current = node;
69064             while (current) {
69065                 if (ts.isFunctionLike(current)) {
69066                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
69067                 }
69068                 switch (current.kind) {
69069                     case 238 /* LabeledStatement */:
69070                         if (node.label && current.label.escapedText === node.label.escapedText) {
69071                             // found matching label - verify that label usage is correct
69072                             // continue can only target labels that are on iteration statements
69073                             var isMisplacedContinueLabel = node.kind === 233 /* ContinueStatement */
69074                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
69075                             if (isMisplacedContinueLabel) {
69076                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
69077                             }
69078                             return false;
69079                         }
69080                         break;
69081                     case 237 /* SwitchStatement */:
69082                         if (node.kind === 234 /* BreakStatement */ && !node.label) {
69083                             // unlabeled break within switch statement - ok
69084                             return false;
69085                         }
69086                         break;
69087                     default:
69088                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
69089                             // unlabeled break or continue within iteration statement - ok
69090                             return false;
69091                         }
69092                         break;
69093                 }
69094                 current = current.parent;
69095             }
69096             if (node.label) {
69097                 var message = node.kind === 234 /* BreakStatement */
69098                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
69099                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
69100                 return grammarErrorOnNode(node, message);
69101             }
69102             else {
69103                 var message = node.kind === 234 /* BreakStatement */
69104                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
69105                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
69106                 return grammarErrorOnNode(node, message);
69107             }
69108         }
69109         function checkGrammarBindingElement(node) {
69110             if (node.dotDotDotToken) {
69111                 var elements = node.parent.elements;
69112                 if (node !== ts.last(elements)) {
69113                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
69114                 }
69115                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
69116                 if (node.propertyName) {
69117                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
69118                 }
69119                 if (node.initializer) {
69120                     // Error on equals token which immediately precedes the initializer
69121                     return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
69122                 }
69123             }
69124         }
69125         function isStringOrNumberLiteralExpression(expr) {
69126             return ts.isStringOrNumericLiteralLike(expr) ||
69127                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69128                     expr.operand.kind === 8 /* NumericLiteral */;
69129         }
69130         function isBigIntLiteralExpression(expr) {
69131             return expr.kind === 9 /* BigIntLiteral */ ||
69132                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69133                     expr.operand.kind === 9 /* BigIntLiteral */;
69134         }
69135         function isSimpleLiteralEnumReference(expr) {
69136             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
69137                 ts.isEntityNameExpression(expr.expression)) {
69138                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
69139             }
69140         }
69141         function checkAmbientInitializer(node) {
69142             var initializer = node.initializer;
69143             if (initializer) {
69144                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
69145                     isSimpleLiteralEnumReference(initializer) ||
69146                     initializer.kind === 106 /* TrueKeyword */ || initializer.kind === 91 /* FalseKeyword */ ||
69147                     isBigIntLiteralExpression(initializer));
69148                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
69149                 if (isConstOrReadonly && !node.type) {
69150                     if (isInvalidInitializer) {
69151                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
69152                     }
69153                 }
69154                 else {
69155                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69156                 }
69157                 if (!isConstOrReadonly || isInvalidInitializer) {
69158                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69159                 }
69160             }
69161         }
69162         function checkGrammarVariableDeclaration(node) {
69163             if (node.parent.parent.kind !== 231 /* ForInStatement */ && node.parent.parent.kind !== 232 /* ForOfStatement */) {
69164                 if (node.flags & 8388608 /* Ambient */) {
69165                     checkAmbientInitializer(node);
69166                 }
69167                 else if (!node.initializer) {
69168                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
69169                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
69170                     }
69171                     if (ts.isVarConst(node)) {
69172                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
69173                     }
69174                 }
69175             }
69176             if (node.exclamationToken && (node.parent.parent.kind !== 225 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
69177                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation);
69178             }
69179             var moduleKind = ts.getEmitModuleKind(compilerOptions);
69180             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System && !compilerOptions.noEmit &&
69181                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
69182                 checkESModuleMarker(node.name);
69183             }
69184             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
69185             // 1. LexicalDeclaration : LetOrConst BindingList ;
69186             // It is a Syntax Error if the BoundNames of BindingList contains "let".
69187             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
69188             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
69189             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
69190             // and its Identifier is eval or arguments
69191             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
69192         }
69193         function checkESModuleMarker(name) {
69194             if (name.kind === 75 /* Identifier */) {
69195                 if (ts.idText(name) === "__esModule") {
69196                     return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
69197                 }
69198             }
69199             else {
69200                 var elements = name.elements;
69201                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
69202                     var element = elements_1[_i];
69203                     if (!ts.isOmittedExpression(element)) {
69204                         return checkESModuleMarker(element.name);
69205                     }
69206                 }
69207             }
69208             return false;
69209         }
69210         function checkGrammarNameInLetOrConstDeclarations(name) {
69211             if (name.kind === 75 /* Identifier */) {
69212                 if (name.originalKeywordKind === 115 /* LetKeyword */) {
69213                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
69214                 }
69215             }
69216             else {
69217                 var elements = name.elements;
69218                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
69219                     var element = elements_2[_i];
69220                     if (!ts.isOmittedExpression(element)) {
69221                         checkGrammarNameInLetOrConstDeclarations(element.name);
69222                     }
69223                 }
69224             }
69225             return false;
69226         }
69227         function checkGrammarVariableDeclarationList(declarationList) {
69228             var declarations = declarationList.declarations;
69229             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
69230                 return true;
69231             }
69232             if (!declarationList.declarations.length) {
69233                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
69234             }
69235             return false;
69236         }
69237         function allowLetAndConstDeclarations(parent) {
69238             switch (parent.kind) {
69239                 case 227 /* IfStatement */:
69240                 case 228 /* DoStatement */:
69241                 case 229 /* WhileStatement */:
69242                 case 236 /* WithStatement */:
69243                 case 230 /* ForStatement */:
69244                 case 231 /* ForInStatement */:
69245                 case 232 /* ForOfStatement */:
69246                     return false;
69247                 case 238 /* LabeledStatement */:
69248                     return allowLetAndConstDeclarations(parent.parent);
69249             }
69250             return true;
69251         }
69252         function checkGrammarForDisallowedLetOrConstStatement(node) {
69253             if (!allowLetAndConstDeclarations(node.parent)) {
69254                 if (ts.isLet(node.declarationList)) {
69255                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
69256                 }
69257                 else if (ts.isVarConst(node.declarationList)) {
69258                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
69259                 }
69260             }
69261         }
69262         function checkGrammarMetaProperty(node) {
69263             var escapedText = node.name.escapedText;
69264             switch (node.keywordToken) {
69265                 case 99 /* NewKeyword */:
69266                     if (escapedText !== "target") {
69267                         return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target");
69268                     }
69269                     break;
69270                 case 96 /* ImportKeyword */:
69271                     if (escapedText !== "meta") {
69272                         return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta");
69273                     }
69274                     break;
69275             }
69276         }
69277         function hasParseDiagnostics(sourceFile) {
69278             return sourceFile.parseDiagnostics.length > 0;
69279         }
69280         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
69281             var sourceFile = ts.getSourceFileOfNode(node);
69282             if (!hasParseDiagnostics(sourceFile)) {
69283                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69284                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
69285                 return true;
69286             }
69287             return false;
69288         }
69289         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
69290             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
69291             if (!hasParseDiagnostics(sourceFile)) {
69292                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
69293                 return true;
69294             }
69295             return false;
69296         }
69297         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
69298             var sourceFile = ts.getSourceFileOfNode(node);
69299             if (!hasParseDiagnostics(sourceFile)) {
69300                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
69301                 return true;
69302             }
69303             return false;
69304         }
69305         function checkGrammarConstructorTypeParameters(node) {
69306             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
69307             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
69308             if (range) {
69309                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
69310                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
69311             }
69312         }
69313         function checkGrammarConstructorTypeAnnotation(node) {
69314             var type = ts.getEffectiveReturnTypeNode(node);
69315             if (type) {
69316                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
69317             }
69318         }
69319         function checkGrammarProperty(node) {
69320             if (ts.isClassLike(node.parent)) {
69321                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
69322                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
69323                 }
69324                 if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
69325                     return true;
69326                 }
69327                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
69328                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
69329                 }
69330             }
69331             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69332                 if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
69333                     return true;
69334                 }
69335                 if (node.initializer) {
69336                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
69337                 }
69338             }
69339             else if (node.parent.kind === 173 /* TypeLiteral */) {
69340                 if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
69341                     return true;
69342                 }
69343                 if (node.initializer) {
69344                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
69345                 }
69346             }
69347             if (node.flags & 8388608 /* Ambient */) {
69348                 checkAmbientInitializer(node);
69349             }
69350             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
69351                 node.flags & 8388608 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
69352                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
69353             }
69354         }
69355         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
69356             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
69357             // interfaces and imports categories:
69358             //
69359             //  DeclarationElement:
69360             //     ExportAssignment
69361             //     export_opt   InterfaceDeclaration
69362             //     export_opt   TypeAliasDeclaration
69363             //     export_opt   ImportDeclaration
69364             //     export_opt   ExternalImportDeclaration
69365             //     export_opt   AmbientDeclaration
69366             //
69367             // TODO: The spec needs to be amended to reflect this grammar.
69368             if (node.kind === 246 /* InterfaceDeclaration */ ||
69369                 node.kind === 247 /* TypeAliasDeclaration */ ||
69370                 node.kind === 254 /* ImportDeclaration */ ||
69371                 node.kind === 253 /* ImportEqualsDeclaration */ ||
69372                 node.kind === 260 /* ExportDeclaration */ ||
69373                 node.kind === 259 /* ExportAssignment */ ||
69374                 node.kind === 252 /* NamespaceExportDeclaration */ ||
69375                 ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
69376                 return false;
69377             }
69378             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
69379         }
69380         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
69381             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
69382                 var decl = _a[_i];
69383                 if (ts.isDeclaration(decl) || decl.kind === 225 /* VariableStatement */) {
69384                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
69385                         return true;
69386                     }
69387                 }
69388             }
69389             return false;
69390         }
69391         function checkGrammarSourceFile(node) {
69392             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
69393         }
69394         function checkGrammarStatementInAmbientContext(node) {
69395             if (node.flags & 8388608 /* Ambient */) {
69396                 // Find containing block which is either Block, ModuleBlock, SourceFile
69397                 var links = getNodeLinks(node);
69398                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
69399                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
69400                 }
69401                 // We are either parented by another statement, or some sort of block.
69402                 // If we're in a block, we only want to really report an error once
69403                 // to prevent noisiness.  So use a bit on the block to indicate if
69404                 // this has already been reported, and don't report if it has.
69405                 //
69406                 if (node.parent.kind === 223 /* Block */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
69407                     var links_2 = getNodeLinks(node.parent);
69408                     // Check if the containing block ever report this error
69409                     if (!links_2.hasReportedStatementInAmbientContext) {
69410                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
69411                     }
69412                 }
69413                 else {
69414                     // We must be parented by a statement.  If so, there's no need
69415                     // to report the error as our parent will have already done it.
69416                     // Debug.assert(isStatement(node.parent));
69417                 }
69418             }
69419             return false;
69420         }
69421         function checkGrammarNumericLiteral(node) {
69422             // Grammar checking
69423             if (node.numericLiteralFlags & 32 /* Octal */) {
69424                 var diagnosticMessage = void 0;
69425                 if (languageVersion >= 1 /* ES5 */) {
69426                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
69427                 }
69428                 else if (ts.isChildOfNodeWithKind(node, 187 /* LiteralType */)) {
69429                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
69430                 }
69431                 else if (ts.isChildOfNodeWithKind(node, 284 /* EnumMember */)) {
69432                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
69433                 }
69434                 if (diagnosticMessage) {
69435                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
69436                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
69437                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
69438                 }
69439             }
69440             // Realism (size) checking
69441             checkNumericLiteralValueSize(node);
69442             return false;
69443         }
69444         function checkNumericLiteralValueSize(node) {
69445             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
69446             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
69447             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
69448             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
69449                 return;
69450             }
69451             // We can't rely on the runtime to accurately store and compare extremely large numeric values
69452             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
69453             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
69454             // it's likely addition operations on it will fail too
69455             var apparentValue = +ts.getTextOfNode(node);
69456             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
69457                 return;
69458             }
69459             addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers));
69460         }
69461         function checkGrammarBigIntLiteral(node) {
69462             var literalType = ts.isLiteralTypeNode(node.parent) ||
69463                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
69464             if (!literalType) {
69465                 if (languageVersion < 7 /* ES2020 */) {
69466                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
69467                         return true;
69468                     }
69469                 }
69470             }
69471             return false;
69472         }
69473         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
69474             var sourceFile = ts.getSourceFileOfNode(node);
69475             if (!hasParseDiagnostics(sourceFile)) {
69476                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69477                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
69478                 return true;
69479             }
69480             return false;
69481         }
69482         function getAmbientModules() {
69483             if (!ambientModulesCache) {
69484                 ambientModulesCache = [];
69485                 globals.forEach(function (global, sym) {
69486                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
69487                     if (ambientModuleSymbolRegex.test(sym)) {
69488                         ambientModulesCache.push(global);
69489                     }
69490                 });
69491             }
69492             return ambientModulesCache;
69493         }
69494         function checkGrammarImportClause(node) {
69495             if (node.isTypeOnly && node.name && node.namedBindings) {
69496                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
69497             }
69498             return false;
69499         }
69500         function checkGrammarImportCallExpression(node) {
69501             if (moduleKind === ts.ModuleKind.ES2015) {
69502                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
69503             }
69504             if (node.typeArguments) {
69505                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
69506             }
69507             var nodeArguments = node.arguments;
69508             if (nodeArguments.length !== 1) {
69509                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
69510             }
69511             checkGrammarForDisallowedTrailingComma(nodeArguments);
69512             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
69513             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
69514             if (ts.isSpreadElement(nodeArguments[0])) {
69515                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
69516             }
69517             return false;
69518         }
69519         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
69520             var sourceObjectFlags = ts.getObjectFlags(source);
69521             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
69522                 return ts.find(unionTarget.types, function (target) {
69523                     if (target.flags & 524288 /* Object */) {
69524                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
69525                         if (overlapObjFlags & 4 /* Reference */) {
69526                             return source.target === target.target;
69527                         }
69528                         if (overlapObjFlags & 16 /* Anonymous */) {
69529                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
69530                         }
69531                     }
69532                     return false;
69533                 });
69534             }
69535         }
69536         function findBestTypeForObjectLiteral(source, unionTarget) {
69537             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
69538                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
69539             }
69540         }
69541         function findBestTypeForInvokable(source, unionTarget) {
69542             var signatureKind = 0 /* Call */;
69543             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
69544                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
69545             if (hasSignatures) {
69546                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
69547             }
69548         }
69549         function findMostOverlappyType(source, unionTarget) {
69550             var bestMatch;
69551             var matchingCount = 0;
69552             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
69553                 var target = _a[_i];
69554                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
69555                 if (overlap.flags & 4194304 /* Index */) {
69556                     // perfect overlap of keys
69557                     bestMatch = target;
69558                     matchingCount = Infinity;
69559                 }
69560                 else if (overlap.flags & 1048576 /* Union */) {
69561                     // We only want to account for literal types otherwise.
69562                     // If we have a union of index types, it seems likely that we
69563                     // needed to elaborate between two generic mapped types anyway.
69564                     var len = ts.length(ts.filter(overlap.types, isUnitType));
69565                     if (len >= matchingCount) {
69566                         bestMatch = target;
69567                         matchingCount = len;
69568                     }
69569                 }
69570                 else if (isUnitType(overlap) && 1 >= matchingCount) {
69571                     bestMatch = target;
69572                     matchingCount = 1;
69573                 }
69574             }
69575             return bestMatch;
69576         }
69577         function filterPrimitivesIfContainsNonPrimitive(type) {
69578             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
69579                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
69580                 if (!(result.flags & 131072 /* Never */)) {
69581                     return result;
69582                 }
69583             }
69584             return type;
69585         }
69586         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
69587         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
69588             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
69589                 var sourceProperties = getPropertiesOfType(source);
69590                 if (sourceProperties) {
69591                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
69592                     if (sourcePropertiesFiltered) {
69593                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
69594                     }
69595                 }
69596             }
69597             return undefined;
69598         }
69599     }
69600     ts.createTypeChecker = createTypeChecker;
69601     function isNotAccessor(declaration) {
69602         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
69603         return !ts.isAccessor(declaration);
69604     }
69605     function isNotOverload(declaration) {
69606         return (declaration.kind !== 244 /* FunctionDeclaration */ && declaration.kind !== 161 /* MethodDeclaration */) ||
69607             !!declaration.body;
69608     }
69609     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
69610     function isDeclarationNameOrImportPropertyName(name) {
69611         switch (name.parent.kind) {
69612             case 258 /* ImportSpecifier */:
69613             case 263 /* ExportSpecifier */:
69614                 return ts.isIdentifier(name);
69615             default:
69616                 return ts.isDeclarationName(name);
69617         }
69618     }
69619     function isSomeImportDeclaration(decl) {
69620         switch (decl.kind) {
69621             case 255 /* ImportClause */: // For default import
69622             case 253 /* ImportEqualsDeclaration */:
69623             case 256 /* NamespaceImport */:
69624             case 258 /* ImportSpecifier */: // For rename import `x as y`
69625                 return true;
69626             case 75 /* Identifier */:
69627                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
69628                 return decl.parent.kind === 258 /* ImportSpecifier */;
69629             default:
69630                 return false;
69631         }
69632     }
69633     var JsxNames;
69634     (function (JsxNames) {
69635         JsxNames.JSX = "JSX";
69636         JsxNames.IntrinsicElements = "IntrinsicElements";
69637         JsxNames.ElementClass = "ElementClass";
69638         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
69639         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
69640         JsxNames.Element = "Element";
69641         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
69642         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
69643         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
69644     })(JsxNames || (JsxNames = {}));
69645     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
69646         switch (typeKind) {
69647             case 0 /* Yield */: return "yieldType";
69648             case 1 /* Return */: return "returnType";
69649             case 2 /* Next */: return "nextType";
69650         }
69651     }
69652     function signatureHasRestParameter(s) {
69653         return !!(s.flags & 1 /* HasRestParameter */);
69654     }
69655     ts.signatureHasRestParameter = signatureHasRestParameter;
69656     function signatureHasLiteralTypes(s) {
69657         return !!(s.flags & 2 /* HasLiteralTypes */);
69658     }
69659     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
69660 })(ts || (ts = {}));
69661 var ts;
69662 (function (ts) {
69663     function createSynthesizedNode(kind) {
69664         var node = ts.createNode(kind, -1, -1);
69665         node.flags |= 8 /* Synthesized */;
69666         return node;
69667     }
69668     /* @internal */
69669     function updateNode(updated, original) {
69670         if (updated !== original) {
69671             setOriginalNode(updated, original);
69672             setTextRange(updated, original);
69673             ts.aggregateTransformFlags(updated);
69674         }
69675         return updated;
69676     }
69677     ts.updateNode = updateNode;
69678     /**
69679      * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
69680      */
69681     function createNodeArray(elements, hasTrailingComma) {
69682         if (!elements || elements === ts.emptyArray) {
69683             elements = [];
69684         }
69685         else if (ts.isNodeArray(elements)) {
69686             return elements;
69687         }
69688         var array = elements;
69689         array.pos = -1;
69690         array.end = -1;
69691         array.hasTrailingComma = hasTrailingComma;
69692         return array;
69693     }
69694     ts.createNodeArray = createNodeArray;
69695     /**
69696      * Creates a shallow, memberwise clone of a node with no source map location.
69697      */
69698     /* @internal */
69699     function getSynthesizedClone(node) {
69700         // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
69701         // the original node. We also need to exclude specific properties and only include own-
69702         // properties (to skip members already defined on the shared prototype).
69703         if (node === undefined) {
69704             return node;
69705         }
69706         var clone = createSynthesizedNode(node.kind);
69707         clone.flags |= node.flags;
69708         setOriginalNode(clone, node);
69709         for (var key in node) {
69710             if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
69711                 continue;
69712             }
69713             clone[key] = node[key];
69714         }
69715         return clone;
69716     }
69717     ts.getSynthesizedClone = getSynthesizedClone;
69718     function createLiteral(value, isSingleQuote) {
69719         if (typeof value === "number") {
69720             return createNumericLiteral(value + "");
69721         }
69722         // eslint-disable-next-line no-in-operator
69723         if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt
69724             return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n");
69725         }
69726         if (typeof value === "boolean") {
69727             return value ? createTrue() : createFalse();
69728         }
69729         if (ts.isString(value)) {
69730             var res = createStringLiteral(value);
69731             if (isSingleQuote)
69732                 res.singleQuote = true;
69733             return res;
69734         }
69735         return createLiteralFromNode(value);
69736     }
69737     ts.createLiteral = createLiteral;
69738     function createNumericLiteral(value, numericLiteralFlags) {
69739         if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
69740         var node = createSynthesizedNode(8 /* NumericLiteral */);
69741         node.text = value;
69742         node.numericLiteralFlags = numericLiteralFlags;
69743         return node;
69744     }
69745     ts.createNumericLiteral = createNumericLiteral;
69746     function createBigIntLiteral(value) {
69747         var node = createSynthesizedNode(9 /* BigIntLiteral */);
69748         node.text = value;
69749         return node;
69750     }
69751     ts.createBigIntLiteral = createBigIntLiteral;
69752     function createStringLiteral(text) {
69753         var node = createSynthesizedNode(10 /* StringLiteral */);
69754         node.text = text;
69755         return node;
69756     }
69757     ts.createStringLiteral = createStringLiteral;
69758     function createRegularExpressionLiteral(text) {
69759         var node = createSynthesizedNode(13 /* RegularExpressionLiteral */);
69760         node.text = text;
69761         return node;
69762     }
69763     ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
69764     function createLiteralFromNode(sourceNode) {
69765         var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
69766         node.textSourceNode = sourceNode;
69767         return node;
69768     }
69769     function createIdentifier(text, typeArguments) {
69770         var node = createSynthesizedNode(75 /* Identifier */);
69771         node.escapedText = ts.escapeLeadingUnderscores(text);
69772         node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
69773         node.autoGenerateFlags = 0 /* None */;
69774         node.autoGenerateId = 0;
69775         if (typeArguments) {
69776             node.typeArguments = createNodeArray(typeArguments);
69777         }
69778         return node;
69779     }
69780     ts.createIdentifier = createIdentifier;
69781     function updateIdentifier(node, typeArguments) {
69782         return node.typeArguments !== typeArguments
69783             ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
69784             : node;
69785     }
69786     ts.updateIdentifier = updateIdentifier;
69787     var nextAutoGenerateId = 0;
69788     function createTempVariable(recordTempVariable, reservedInNestedScopes) {
69789         var name = createIdentifier("");
69790         name.autoGenerateFlags = 1 /* Auto */;
69791         name.autoGenerateId = nextAutoGenerateId;
69792         nextAutoGenerateId++;
69793         if (recordTempVariable) {
69794             recordTempVariable(name);
69795         }
69796         if (reservedInNestedScopes) {
69797             name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
69798         }
69799         return name;
69800     }
69801     ts.createTempVariable = createTempVariable;
69802     /** Create a unique temporary variable for use in a loop. */
69803     function createLoopVariable() {
69804         var name = createIdentifier("");
69805         name.autoGenerateFlags = 2 /* Loop */;
69806         name.autoGenerateId = nextAutoGenerateId;
69807         nextAutoGenerateId++;
69808         return name;
69809     }
69810     ts.createLoopVariable = createLoopVariable;
69811     /** Create a unique name based on the supplied text. */
69812     function createUniqueName(text) {
69813         var name = createIdentifier(text);
69814         name.autoGenerateFlags = 3 /* Unique */;
69815         name.autoGenerateId = nextAutoGenerateId;
69816         nextAutoGenerateId++;
69817         return name;
69818     }
69819     ts.createUniqueName = createUniqueName;
69820     function createOptimisticUniqueName(text) {
69821         var name = createIdentifier(text);
69822         name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
69823         name.autoGenerateId = nextAutoGenerateId;
69824         nextAutoGenerateId++;
69825         return name;
69826     }
69827     ts.createOptimisticUniqueName = createOptimisticUniqueName;
69828     /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
69829     function createFileLevelUniqueName(text) {
69830         var name = createOptimisticUniqueName(text);
69831         name.autoGenerateFlags |= 32 /* FileLevel */;
69832         return name;
69833     }
69834     ts.createFileLevelUniqueName = createFileLevelUniqueName;
69835     function getGeneratedNameForNode(node, flags) {
69836         var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
69837         name.autoGenerateFlags = 4 /* Node */ | flags;
69838         name.autoGenerateId = nextAutoGenerateId;
69839         name.original = node;
69840         nextAutoGenerateId++;
69841         return name;
69842     }
69843     ts.getGeneratedNameForNode = getGeneratedNameForNode;
69844     // Private Identifiers
69845     function createPrivateIdentifier(text) {
69846         if (text[0] !== "#") {
69847             ts.Debug.fail("First character of private identifier must be #: " + text);
69848         }
69849         var node = createSynthesizedNode(76 /* PrivateIdentifier */);
69850         node.escapedText = ts.escapeLeadingUnderscores(text);
69851         return node;
69852     }
69853     ts.createPrivateIdentifier = createPrivateIdentifier;
69854     // Punctuation
69855     function createToken(token) {
69856         return createSynthesizedNode(token);
69857     }
69858     ts.createToken = createToken;
69859     // Reserved words
69860     function createSuper() {
69861         return createSynthesizedNode(102 /* SuperKeyword */);
69862     }
69863     ts.createSuper = createSuper;
69864     function createThis() {
69865         return createSynthesizedNode(104 /* ThisKeyword */);
69866     }
69867     ts.createThis = createThis;
69868     function createNull() {
69869         return createSynthesizedNode(100 /* NullKeyword */);
69870     }
69871     ts.createNull = createNull;
69872     function createTrue() {
69873         return createSynthesizedNode(106 /* TrueKeyword */);
69874     }
69875     ts.createTrue = createTrue;
69876     function createFalse() {
69877         return createSynthesizedNode(91 /* FalseKeyword */);
69878     }
69879     ts.createFalse = createFalse;
69880     // Modifiers
69881     function createModifier(kind) {
69882         return createToken(kind);
69883     }
69884     ts.createModifier = createModifier;
69885     function createModifiersFromModifierFlags(flags) {
69886         var result = [];
69887         if (flags & 1 /* Export */) {
69888             result.push(createModifier(89 /* ExportKeyword */));
69889         }
69890         if (flags & 2 /* Ambient */) {
69891             result.push(createModifier(130 /* DeclareKeyword */));
69892         }
69893         if (flags & 512 /* Default */) {
69894             result.push(createModifier(84 /* DefaultKeyword */));
69895         }
69896         if (flags & 2048 /* Const */) {
69897             result.push(createModifier(81 /* ConstKeyword */));
69898         }
69899         if (flags & 4 /* Public */) {
69900             result.push(createModifier(119 /* PublicKeyword */));
69901         }
69902         if (flags & 8 /* Private */) {
69903             result.push(createModifier(117 /* PrivateKeyword */));
69904         }
69905         if (flags & 16 /* Protected */) {
69906             result.push(createModifier(118 /* ProtectedKeyword */));
69907         }
69908         if (flags & 128 /* Abstract */) {
69909             result.push(createModifier(122 /* AbstractKeyword */));
69910         }
69911         if (flags & 32 /* Static */) {
69912             result.push(createModifier(120 /* StaticKeyword */));
69913         }
69914         if (flags & 64 /* Readonly */) {
69915             result.push(createModifier(138 /* ReadonlyKeyword */));
69916         }
69917         if (flags & 256 /* Async */) {
69918             result.push(createModifier(126 /* AsyncKeyword */));
69919         }
69920         return result;
69921     }
69922     ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
69923     // Names
69924     function createQualifiedName(left, right) {
69925         var node = createSynthesizedNode(153 /* QualifiedName */);
69926         node.left = left;
69927         node.right = asName(right);
69928         return node;
69929     }
69930     ts.createQualifiedName = createQualifiedName;
69931     function updateQualifiedName(node, left, right) {
69932         return node.left !== left
69933             || node.right !== right
69934             ? updateNode(createQualifiedName(left, right), node)
69935             : node;
69936     }
69937     ts.updateQualifiedName = updateQualifiedName;
69938     function parenthesizeForComputedName(expression) {
69939         return ts.isCommaSequence(expression)
69940             ? createParen(expression)
69941             : expression;
69942     }
69943     function createComputedPropertyName(expression) {
69944         var node = createSynthesizedNode(154 /* ComputedPropertyName */);
69945         node.expression = parenthesizeForComputedName(expression);
69946         return node;
69947     }
69948     ts.createComputedPropertyName = createComputedPropertyName;
69949     function updateComputedPropertyName(node, expression) {
69950         return node.expression !== expression
69951             ? updateNode(createComputedPropertyName(expression), node)
69952             : node;
69953     }
69954     ts.updateComputedPropertyName = updateComputedPropertyName;
69955     // Signature elements
69956     function createTypeParameterDeclaration(name, constraint, defaultType) {
69957         var node = createSynthesizedNode(155 /* TypeParameter */);
69958         node.name = asName(name);
69959         node.constraint = constraint;
69960         node.default = defaultType;
69961         return node;
69962     }
69963     ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
69964     function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
69965         return node.name !== name
69966             || node.constraint !== constraint
69967             || node.default !== defaultType
69968             ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
69969             : node;
69970     }
69971     ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
69972     function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69973         var node = createSynthesizedNode(156 /* Parameter */);
69974         node.decorators = asNodeArray(decorators);
69975         node.modifiers = asNodeArray(modifiers);
69976         node.dotDotDotToken = dotDotDotToken;
69977         node.name = asName(name);
69978         node.questionToken = questionToken;
69979         node.type = type;
69980         node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
69981         return node;
69982     }
69983     ts.createParameter = createParameter;
69984     function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69985         return node.decorators !== decorators
69986             || node.modifiers !== modifiers
69987             || node.dotDotDotToken !== dotDotDotToken
69988             || node.name !== name
69989             || node.questionToken !== questionToken
69990             || node.type !== type
69991             || node.initializer !== initializer
69992             ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
69993             : node;
69994     }
69995     ts.updateParameter = updateParameter;
69996     function createDecorator(expression) {
69997         var node = createSynthesizedNode(157 /* Decorator */);
69998         node.expression = ts.parenthesizeForAccess(expression);
69999         return node;
70000     }
70001     ts.createDecorator = createDecorator;
70002     function updateDecorator(node, expression) {
70003         return node.expression !== expression
70004             ? updateNode(createDecorator(expression), node)
70005             : node;
70006     }
70007     ts.updateDecorator = updateDecorator;
70008     // Type Elements
70009     function createPropertySignature(modifiers, name, questionToken, type, initializer) {
70010         var node = createSynthesizedNode(158 /* PropertySignature */);
70011         node.modifiers = asNodeArray(modifiers);
70012         node.name = asName(name);
70013         node.questionToken = questionToken;
70014         node.type = type;
70015         node.initializer = initializer;
70016         return node;
70017     }
70018     ts.createPropertySignature = createPropertySignature;
70019     function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
70020         return node.modifiers !== modifiers
70021             || node.name !== name
70022             || node.questionToken !== questionToken
70023             || node.type !== type
70024             || node.initializer !== initializer
70025             ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
70026             : node;
70027     }
70028     ts.updatePropertySignature = updatePropertySignature;
70029     function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70030         var node = createSynthesizedNode(159 /* PropertyDeclaration */);
70031         node.decorators = asNodeArray(decorators);
70032         node.modifiers = asNodeArray(modifiers);
70033         node.name = asName(name);
70034         node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined;
70035         node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
70036         node.type = type;
70037         node.initializer = initializer;
70038         return node;
70039     }
70040     ts.createProperty = createProperty;
70041     function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70042         return node.decorators !== decorators
70043             || node.modifiers !== modifiers
70044             || node.name !== name
70045             || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined)
70046             || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
70047             || node.type !== type
70048             || node.initializer !== initializer
70049             ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
70050             : node;
70051     }
70052     ts.updateProperty = updateProperty;
70053     function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
70054         var node = createSignatureDeclaration(160 /* MethodSignature */, typeParameters, parameters, type);
70055         node.name = asName(name);
70056         node.questionToken = questionToken;
70057         return node;
70058     }
70059     ts.createMethodSignature = createMethodSignature;
70060     function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
70061         return node.typeParameters !== typeParameters
70062             || node.parameters !== parameters
70063             || node.type !== type
70064             || node.name !== name
70065             || node.questionToken !== questionToken
70066             ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
70067             : node;
70068     }
70069     ts.updateMethodSignature = updateMethodSignature;
70070     function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70071         var node = createSynthesizedNode(161 /* MethodDeclaration */);
70072         node.decorators = asNodeArray(decorators);
70073         node.modifiers = asNodeArray(modifiers);
70074         node.asteriskToken = asteriskToken;
70075         node.name = asName(name);
70076         node.questionToken = questionToken;
70077         node.typeParameters = asNodeArray(typeParameters);
70078         node.parameters = createNodeArray(parameters);
70079         node.type = type;
70080         node.body = body;
70081         return node;
70082     }
70083     ts.createMethod = createMethod;
70084     function createMethodCall(object, methodName, argumentsList) {
70085         return createCall(createPropertyAccess(object, asName(methodName)), 
70086         /*typeArguments*/ undefined, argumentsList);
70087     }
70088     function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
70089         return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
70090     }
70091     /* @internal */
70092     function createObjectDefinePropertyCall(target, propertyName, attributes) {
70093         return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
70094     }
70095     ts.createObjectDefinePropertyCall = createObjectDefinePropertyCall;
70096     function tryAddPropertyAssignment(properties, propertyName, expression) {
70097         if (expression) {
70098             properties.push(createPropertyAssignment(propertyName, expression));
70099             return true;
70100         }
70101         return false;
70102     }
70103     /* @internal */
70104     function createPropertyDescriptor(attributes, singleLine) {
70105         var properties = [];
70106         tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
70107         tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
70108         var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
70109         isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
70110         var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
70111         isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
70112         ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
70113         return createObjectLiteral(properties, !singleLine);
70114     }
70115     ts.createPropertyDescriptor = createPropertyDescriptor;
70116     function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70117         return node.decorators !== decorators
70118             || node.modifiers !== modifiers
70119             || node.asteriskToken !== asteriskToken
70120             || node.name !== name
70121             || node.questionToken !== questionToken
70122             || node.typeParameters !== typeParameters
70123             || node.parameters !== parameters
70124             || node.type !== type
70125             || node.body !== body
70126             ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
70127             : node;
70128     }
70129     ts.updateMethod = updateMethod;
70130     function createConstructor(decorators, modifiers, parameters, body) {
70131         var node = createSynthesizedNode(162 /* Constructor */);
70132         node.decorators = asNodeArray(decorators);
70133         node.modifiers = asNodeArray(modifiers);
70134         node.typeParameters = undefined;
70135         node.parameters = createNodeArray(parameters);
70136         node.type = undefined;
70137         node.body = body;
70138         return node;
70139     }
70140     ts.createConstructor = createConstructor;
70141     function updateConstructor(node, decorators, modifiers, parameters, body) {
70142         return node.decorators !== decorators
70143             || node.modifiers !== modifiers
70144             || node.parameters !== parameters
70145             || node.body !== body
70146             ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
70147             : node;
70148     }
70149     ts.updateConstructor = updateConstructor;
70150     function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
70151         var node = createSynthesizedNode(163 /* GetAccessor */);
70152         node.decorators = asNodeArray(decorators);
70153         node.modifiers = asNodeArray(modifiers);
70154         node.name = asName(name);
70155         node.typeParameters = undefined;
70156         node.parameters = createNodeArray(parameters);
70157         node.type = type;
70158         node.body = body;
70159         return node;
70160     }
70161     ts.createGetAccessor = createGetAccessor;
70162     function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
70163         return node.decorators !== decorators
70164             || node.modifiers !== modifiers
70165             || node.name !== name
70166             || node.parameters !== parameters
70167             || node.type !== type
70168             || node.body !== body
70169             ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
70170             : node;
70171     }
70172     ts.updateGetAccessor = updateGetAccessor;
70173     function createSetAccessor(decorators, modifiers, name, parameters, body) {
70174         var node = createSynthesizedNode(164 /* SetAccessor */);
70175         node.decorators = asNodeArray(decorators);
70176         node.modifiers = asNodeArray(modifiers);
70177         node.name = asName(name);
70178         node.typeParameters = undefined;
70179         node.parameters = createNodeArray(parameters);
70180         node.body = body;
70181         return node;
70182     }
70183     ts.createSetAccessor = createSetAccessor;
70184     function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
70185         return node.decorators !== decorators
70186             || node.modifiers !== modifiers
70187             || node.name !== name
70188             || node.parameters !== parameters
70189             || node.body !== body
70190             ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
70191             : node;
70192     }
70193     ts.updateSetAccessor = updateSetAccessor;
70194     function createCallSignature(typeParameters, parameters, type) {
70195         return createSignatureDeclaration(165 /* CallSignature */, typeParameters, parameters, type);
70196     }
70197     ts.createCallSignature = createCallSignature;
70198     function updateCallSignature(node, typeParameters, parameters, type) {
70199         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70200     }
70201     ts.updateCallSignature = updateCallSignature;
70202     function createConstructSignature(typeParameters, parameters, type) {
70203         return createSignatureDeclaration(166 /* ConstructSignature */, typeParameters, parameters, type);
70204     }
70205     ts.createConstructSignature = createConstructSignature;
70206     function updateConstructSignature(node, typeParameters, parameters, type) {
70207         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70208     }
70209     ts.updateConstructSignature = updateConstructSignature;
70210     function createIndexSignature(decorators, modifiers, parameters, type) {
70211         var node = createSynthesizedNode(167 /* IndexSignature */);
70212         node.decorators = asNodeArray(decorators);
70213         node.modifiers = asNodeArray(modifiers);
70214         node.parameters = createNodeArray(parameters);
70215         node.type = type;
70216         return node;
70217     }
70218     ts.createIndexSignature = createIndexSignature;
70219     function updateIndexSignature(node, decorators, modifiers, parameters, type) {
70220         return node.parameters !== parameters
70221             || node.type !== type
70222             || node.decorators !== decorators
70223             || node.modifiers !== modifiers
70224             ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
70225             : node;
70226     }
70227     ts.updateIndexSignature = updateIndexSignature;
70228     /* @internal */
70229     function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
70230         var node = createSynthesizedNode(kind);
70231         node.typeParameters = asNodeArray(typeParameters);
70232         node.parameters = asNodeArray(parameters);
70233         node.type = type;
70234         node.typeArguments = asNodeArray(typeArguments);
70235         return node;
70236     }
70237     ts.createSignatureDeclaration = createSignatureDeclaration;
70238     function updateSignatureDeclaration(node, typeParameters, parameters, type) {
70239         return node.typeParameters !== typeParameters
70240             || node.parameters !== parameters
70241             || node.type !== type
70242             ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
70243             : node;
70244     }
70245     // Types
70246     function createKeywordTypeNode(kind) {
70247         return createSynthesizedNode(kind);
70248     }
70249     ts.createKeywordTypeNode = createKeywordTypeNode;
70250     function createTypePredicateNode(parameterName, type) {
70251         return createTypePredicateNodeWithModifier(/*assertsModifier*/ undefined, parameterName, type);
70252     }
70253     ts.createTypePredicateNode = createTypePredicateNode;
70254     function createTypePredicateNodeWithModifier(assertsModifier, parameterName, type) {
70255         var node = createSynthesizedNode(168 /* TypePredicate */);
70256         node.assertsModifier = assertsModifier;
70257         node.parameterName = asName(parameterName);
70258         node.type = type;
70259         return node;
70260     }
70261     ts.createTypePredicateNodeWithModifier = createTypePredicateNodeWithModifier;
70262     function updateTypePredicateNode(node, parameterName, type) {
70263         return updateTypePredicateNodeWithModifier(node, node.assertsModifier, parameterName, type);
70264     }
70265     ts.updateTypePredicateNode = updateTypePredicateNode;
70266     function updateTypePredicateNodeWithModifier(node, assertsModifier, parameterName, type) {
70267         return node.assertsModifier !== assertsModifier
70268             || node.parameterName !== parameterName
70269             || node.type !== type
70270             ? updateNode(createTypePredicateNodeWithModifier(assertsModifier, parameterName, type), node)
70271             : node;
70272     }
70273     ts.updateTypePredicateNodeWithModifier = updateTypePredicateNodeWithModifier;
70274     function createTypeReferenceNode(typeName, typeArguments) {
70275         var node = createSynthesizedNode(169 /* TypeReference */);
70276         node.typeName = asName(typeName);
70277         node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
70278         return node;
70279     }
70280     ts.createTypeReferenceNode = createTypeReferenceNode;
70281     function updateTypeReferenceNode(node, typeName, typeArguments) {
70282         return node.typeName !== typeName
70283             || node.typeArguments !== typeArguments
70284             ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
70285             : node;
70286     }
70287     ts.updateTypeReferenceNode = updateTypeReferenceNode;
70288     function createFunctionTypeNode(typeParameters, parameters, type) {
70289         return createSignatureDeclaration(170 /* FunctionType */, typeParameters, parameters, type);
70290     }
70291     ts.createFunctionTypeNode = createFunctionTypeNode;
70292     function updateFunctionTypeNode(node, typeParameters, parameters, type) {
70293         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70294     }
70295     ts.updateFunctionTypeNode = updateFunctionTypeNode;
70296     function createConstructorTypeNode(typeParameters, parameters, type) {
70297         return createSignatureDeclaration(171 /* ConstructorType */, typeParameters, parameters, type);
70298     }
70299     ts.createConstructorTypeNode = createConstructorTypeNode;
70300     function updateConstructorTypeNode(node, typeParameters, parameters, type) {
70301         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70302     }
70303     ts.updateConstructorTypeNode = updateConstructorTypeNode;
70304     function createTypeQueryNode(exprName) {
70305         var node = createSynthesizedNode(172 /* TypeQuery */);
70306         node.exprName = exprName;
70307         return node;
70308     }
70309     ts.createTypeQueryNode = createTypeQueryNode;
70310     function updateTypeQueryNode(node, exprName) {
70311         return node.exprName !== exprName
70312             ? updateNode(createTypeQueryNode(exprName), node)
70313             : node;
70314     }
70315     ts.updateTypeQueryNode = updateTypeQueryNode;
70316     function createTypeLiteralNode(members) {
70317         var node = createSynthesizedNode(173 /* TypeLiteral */);
70318         node.members = createNodeArray(members);
70319         return node;
70320     }
70321     ts.createTypeLiteralNode = createTypeLiteralNode;
70322     function updateTypeLiteralNode(node, members) {
70323         return node.members !== members
70324             ? updateNode(createTypeLiteralNode(members), node)
70325             : node;
70326     }
70327     ts.updateTypeLiteralNode = updateTypeLiteralNode;
70328     function createArrayTypeNode(elementType) {
70329         var node = createSynthesizedNode(174 /* ArrayType */);
70330         node.elementType = ts.parenthesizeArrayTypeMember(elementType);
70331         return node;
70332     }
70333     ts.createArrayTypeNode = createArrayTypeNode;
70334     function updateArrayTypeNode(node, elementType) {
70335         return node.elementType !== elementType
70336             ? updateNode(createArrayTypeNode(elementType), node)
70337             : node;
70338     }
70339     ts.updateArrayTypeNode = updateArrayTypeNode;
70340     function createTupleTypeNode(elementTypes) {
70341         var node = createSynthesizedNode(175 /* TupleType */);
70342         node.elementTypes = createNodeArray(elementTypes);
70343         return node;
70344     }
70345     ts.createTupleTypeNode = createTupleTypeNode;
70346     function updateTupleTypeNode(node, elementTypes) {
70347         return node.elementTypes !== elementTypes
70348             ? updateNode(createTupleTypeNode(elementTypes), node)
70349             : node;
70350     }
70351     ts.updateTupleTypeNode = updateTupleTypeNode;
70352     function createOptionalTypeNode(type) {
70353         var node = createSynthesizedNode(176 /* OptionalType */);
70354         node.type = ts.parenthesizeArrayTypeMember(type);
70355         return node;
70356     }
70357     ts.createOptionalTypeNode = createOptionalTypeNode;
70358     function updateOptionalTypeNode(node, type) {
70359         return node.type !== type
70360             ? updateNode(createOptionalTypeNode(type), node)
70361             : node;
70362     }
70363     ts.updateOptionalTypeNode = updateOptionalTypeNode;
70364     function createRestTypeNode(type) {
70365         var node = createSynthesizedNode(177 /* RestType */);
70366         node.type = type;
70367         return node;
70368     }
70369     ts.createRestTypeNode = createRestTypeNode;
70370     function updateRestTypeNode(node, type) {
70371         return node.type !== type
70372             ? updateNode(createRestTypeNode(type), node)
70373             : node;
70374     }
70375     ts.updateRestTypeNode = updateRestTypeNode;
70376     function createUnionTypeNode(types) {
70377         return createUnionOrIntersectionTypeNode(178 /* UnionType */, types);
70378     }
70379     ts.createUnionTypeNode = createUnionTypeNode;
70380     function updateUnionTypeNode(node, types) {
70381         return updateUnionOrIntersectionTypeNode(node, types);
70382     }
70383     ts.updateUnionTypeNode = updateUnionTypeNode;
70384     function createIntersectionTypeNode(types) {
70385         return createUnionOrIntersectionTypeNode(179 /* IntersectionType */, types);
70386     }
70387     ts.createIntersectionTypeNode = createIntersectionTypeNode;
70388     function updateIntersectionTypeNode(node, types) {
70389         return updateUnionOrIntersectionTypeNode(node, types);
70390     }
70391     ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
70392     function createUnionOrIntersectionTypeNode(kind, types) {
70393         var node = createSynthesizedNode(kind);
70394         node.types = ts.parenthesizeElementTypeMembers(types);
70395         return node;
70396     }
70397     ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
70398     function updateUnionOrIntersectionTypeNode(node, types) {
70399         return node.types !== types
70400             ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
70401             : node;
70402     }
70403     function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
70404         var node = createSynthesizedNode(180 /* ConditionalType */);
70405         node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
70406         node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
70407         node.trueType = trueType;
70408         node.falseType = falseType;
70409         return node;
70410     }
70411     ts.createConditionalTypeNode = createConditionalTypeNode;
70412     function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
70413         return node.checkType !== checkType
70414             || node.extendsType !== extendsType
70415             || node.trueType !== trueType
70416             || node.falseType !== falseType
70417             ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
70418             : node;
70419     }
70420     ts.updateConditionalTypeNode = updateConditionalTypeNode;
70421     function createInferTypeNode(typeParameter) {
70422         var node = createSynthesizedNode(181 /* InferType */);
70423         node.typeParameter = typeParameter;
70424         return node;
70425     }
70426     ts.createInferTypeNode = createInferTypeNode;
70427     function updateInferTypeNode(node, typeParameter) {
70428         return node.typeParameter !== typeParameter
70429             ? updateNode(createInferTypeNode(typeParameter), node)
70430             : node;
70431     }
70432     ts.updateInferTypeNode = updateInferTypeNode;
70433     function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
70434         var node = createSynthesizedNode(188 /* ImportType */);
70435         node.argument = argument;
70436         node.qualifier = qualifier;
70437         node.typeArguments = ts.parenthesizeTypeParameters(typeArguments);
70438         node.isTypeOf = isTypeOf;
70439         return node;
70440     }
70441     ts.createImportTypeNode = createImportTypeNode;
70442     function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
70443         return node.argument !== argument
70444             || node.qualifier !== qualifier
70445             || node.typeArguments !== typeArguments
70446             || node.isTypeOf !== isTypeOf
70447             ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
70448             : node;
70449     }
70450     ts.updateImportTypeNode = updateImportTypeNode;
70451     function createParenthesizedType(type) {
70452         var node = createSynthesizedNode(182 /* ParenthesizedType */);
70453         node.type = type;
70454         return node;
70455     }
70456     ts.createParenthesizedType = createParenthesizedType;
70457     function updateParenthesizedType(node, type) {
70458         return node.type !== type
70459             ? updateNode(createParenthesizedType(type), node)
70460             : node;
70461     }
70462     ts.updateParenthesizedType = updateParenthesizedType;
70463     function createThisTypeNode() {
70464         return createSynthesizedNode(183 /* ThisType */);
70465     }
70466     ts.createThisTypeNode = createThisTypeNode;
70467     function createTypeOperatorNode(operatorOrType, type) {
70468         var node = createSynthesizedNode(184 /* TypeOperator */);
70469         node.operator = typeof operatorOrType === "number" ? operatorOrType : 134 /* KeyOfKeyword */;
70470         node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
70471         return node;
70472     }
70473     ts.createTypeOperatorNode = createTypeOperatorNode;
70474     function updateTypeOperatorNode(node, type) {
70475         return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
70476     }
70477     ts.updateTypeOperatorNode = updateTypeOperatorNode;
70478     function createIndexedAccessTypeNode(objectType, indexType) {
70479         var node = createSynthesizedNode(185 /* IndexedAccessType */);
70480         node.objectType = ts.parenthesizeElementTypeMember(objectType);
70481         node.indexType = indexType;
70482         return node;
70483     }
70484     ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
70485     function updateIndexedAccessTypeNode(node, objectType, indexType) {
70486         return node.objectType !== objectType
70487             || node.indexType !== indexType
70488             ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
70489             : node;
70490     }
70491     ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
70492     function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
70493         var node = createSynthesizedNode(186 /* MappedType */);
70494         node.readonlyToken = readonlyToken;
70495         node.typeParameter = typeParameter;
70496         node.questionToken = questionToken;
70497         node.type = type;
70498         return node;
70499     }
70500     ts.createMappedTypeNode = createMappedTypeNode;
70501     function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
70502         return node.readonlyToken !== readonlyToken
70503             || node.typeParameter !== typeParameter
70504             || node.questionToken !== questionToken
70505             || node.type !== type
70506             ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
70507             : node;
70508     }
70509     ts.updateMappedTypeNode = updateMappedTypeNode;
70510     function createLiteralTypeNode(literal) {
70511         var node = createSynthesizedNode(187 /* LiteralType */);
70512         node.literal = literal;
70513         return node;
70514     }
70515     ts.createLiteralTypeNode = createLiteralTypeNode;
70516     function updateLiteralTypeNode(node, literal) {
70517         return node.literal !== literal
70518             ? updateNode(createLiteralTypeNode(literal), node)
70519             : node;
70520     }
70521     ts.updateLiteralTypeNode = updateLiteralTypeNode;
70522     // Binding Patterns
70523     function createObjectBindingPattern(elements) {
70524         var node = createSynthesizedNode(189 /* ObjectBindingPattern */);
70525         node.elements = createNodeArray(elements);
70526         return node;
70527     }
70528     ts.createObjectBindingPattern = createObjectBindingPattern;
70529     function updateObjectBindingPattern(node, elements) {
70530         return node.elements !== elements
70531             ? updateNode(createObjectBindingPattern(elements), node)
70532             : node;
70533     }
70534     ts.updateObjectBindingPattern = updateObjectBindingPattern;
70535     function createArrayBindingPattern(elements) {
70536         var node = createSynthesizedNode(190 /* ArrayBindingPattern */);
70537         node.elements = createNodeArray(elements);
70538         return node;
70539     }
70540     ts.createArrayBindingPattern = createArrayBindingPattern;
70541     function updateArrayBindingPattern(node, elements) {
70542         return node.elements !== elements
70543             ? updateNode(createArrayBindingPattern(elements), node)
70544             : node;
70545     }
70546     ts.updateArrayBindingPattern = updateArrayBindingPattern;
70547     function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
70548         var node = createSynthesizedNode(191 /* BindingElement */);
70549         node.dotDotDotToken = dotDotDotToken;
70550         node.propertyName = asName(propertyName);
70551         node.name = asName(name);
70552         node.initializer = initializer;
70553         return node;
70554     }
70555     ts.createBindingElement = createBindingElement;
70556     function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
70557         return node.propertyName !== propertyName
70558             || node.dotDotDotToken !== dotDotDotToken
70559             || node.name !== name
70560             || node.initializer !== initializer
70561             ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
70562             : node;
70563     }
70564     ts.updateBindingElement = updateBindingElement;
70565     // Expression
70566     function createArrayLiteral(elements, multiLine) {
70567         var node = createSynthesizedNode(192 /* ArrayLiteralExpression */);
70568         node.elements = ts.parenthesizeListElements(createNodeArray(elements));
70569         if (multiLine)
70570             node.multiLine = true;
70571         return node;
70572     }
70573     ts.createArrayLiteral = createArrayLiteral;
70574     function updateArrayLiteral(node, elements) {
70575         return node.elements !== elements
70576             ? updateNode(createArrayLiteral(elements, node.multiLine), node)
70577             : node;
70578     }
70579     ts.updateArrayLiteral = updateArrayLiteral;
70580     function createObjectLiteral(properties, multiLine) {
70581         var node = createSynthesizedNode(193 /* ObjectLiteralExpression */);
70582         node.properties = createNodeArray(properties);
70583         if (multiLine)
70584             node.multiLine = true;
70585         return node;
70586     }
70587     ts.createObjectLiteral = createObjectLiteral;
70588     function updateObjectLiteral(node, properties) {
70589         return node.properties !== properties
70590             ? updateNode(createObjectLiteral(properties, node.multiLine), node)
70591             : node;
70592     }
70593     ts.updateObjectLiteral = updateObjectLiteral;
70594     function createPropertyAccess(expression, name) {
70595         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70596         node.expression = ts.parenthesizeForAccess(expression);
70597         node.name = asName(name);
70598         setEmitFlags(node, 131072 /* NoIndentation */);
70599         return node;
70600     }
70601     ts.createPropertyAccess = createPropertyAccess;
70602     function updatePropertyAccess(node, expression, name) {
70603         if (ts.isPropertyAccessChain(node)) {
70604             return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
70605         }
70606         // Because we are updating existed propertyAccess we want to inherit its emitFlags
70607         // instead of using the default from createPropertyAccess
70608         return node.expression !== expression
70609             || node.name !== name
70610             ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
70611             : node;
70612     }
70613     ts.updatePropertyAccess = updatePropertyAccess;
70614     function createPropertyAccessChain(expression, questionDotToken, name) {
70615         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70616         node.flags |= 32 /* OptionalChain */;
70617         node.expression = ts.parenthesizeForAccess(expression);
70618         node.questionDotToken = questionDotToken;
70619         node.name = asName(name);
70620         setEmitFlags(node, 131072 /* NoIndentation */);
70621         return node;
70622     }
70623     ts.createPropertyAccessChain = createPropertyAccessChain;
70624     function updatePropertyAccessChain(node, expression, questionDotToken, name) {
70625         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
70626         // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
70627         // instead of using the default from createPropertyAccess
70628         return node.expression !== expression
70629             || node.questionDotToken !== questionDotToken
70630             || node.name !== name
70631             ? updateNode(setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), ts.getEmitFlags(node)), node)
70632             : node;
70633     }
70634     ts.updatePropertyAccessChain = updatePropertyAccessChain;
70635     function createElementAccess(expression, index) {
70636         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70637         node.expression = ts.parenthesizeForAccess(expression);
70638         node.argumentExpression = asExpression(index);
70639         return node;
70640     }
70641     ts.createElementAccess = createElementAccess;
70642     function updateElementAccess(node, expression, argumentExpression) {
70643         if (ts.isOptionalChain(node)) {
70644             return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
70645         }
70646         return node.expression !== expression
70647             || node.argumentExpression !== argumentExpression
70648             ? updateNode(createElementAccess(expression, argumentExpression), node)
70649             : node;
70650     }
70651     ts.updateElementAccess = updateElementAccess;
70652     function createElementAccessChain(expression, questionDotToken, index) {
70653         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70654         node.flags |= 32 /* OptionalChain */;
70655         node.expression = ts.parenthesizeForAccess(expression);
70656         node.questionDotToken = questionDotToken;
70657         node.argumentExpression = asExpression(index);
70658         return node;
70659     }
70660     ts.createElementAccessChain = createElementAccessChain;
70661     function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
70662         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
70663         return node.expression !== expression
70664             || node.questionDotToken !== questionDotToken
70665             || node.argumentExpression !== argumentExpression
70666             ? updateNode(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
70667             : node;
70668     }
70669     ts.updateElementAccessChain = updateElementAccessChain;
70670     function createCall(expression, typeArguments, argumentsArray) {
70671         var node = createSynthesizedNode(196 /* CallExpression */);
70672         node.expression = ts.parenthesizeForAccess(expression);
70673         node.typeArguments = asNodeArray(typeArguments);
70674         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70675         return node;
70676     }
70677     ts.createCall = createCall;
70678     function updateCall(node, expression, typeArguments, argumentsArray) {
70679         if (ts.isOptionalChain(node)) {
70680             return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
70681         }
70682         return node.expression !== expression
70683             || node.typeArguments !== typeArguments
70684             || node.arguments !== argumentsArray
70685             ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
70686             : node;
70687     }
70688     ts.updateCall = updateCall;
70689     function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
70690         var node = createSynthesizedNode(196 /* CallExpression */);
70691         node.flags |= 32 /* OptionalChain */;
70692         node.expression = ts.parenthesizeForAccess(expression);
70693         node.questionDotToken = questionDotToken;
70694         node.typeArguments = asNodeArray(typeArguments);
70695         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70696         return node;
70697     }
70698     ts.createCallChain = createCallChain;
70699     function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
70700         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
70701         return node.expression !== expression
70702             || node.questionDotToken !== questionDotToken
70703             || node.typeArguments !== typeArguments
70704             || node.arguments !== argumentsArray
70705             ? updateNode(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
70706             : node;
70707     }
70708     ts.updateCallChain = updateCallChain;
70709     function createNew(expression, typeArguments, argumentsArray) {
70710         var node = createSynthesizedNode(197 /* NewExpression */);
70711         node.expression = ts.parenthesizeForNew(expression);
70712         node.typeArguments = asNodeArray(typeArguments);
70713         node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
70714         return node;
70715     }
70716     ts.createNew = createNew;
70717     function updateNew(node, expression, typeArguments, argumentsArray) {
70718         return node.expression !== expression
70719             || node.typeArguments !== typeArguments
70720             || node.arguments !== argumentsArray
70721             ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
70722             : node;
70723     }
70724     ts.updateNew = updateNew;
70725     function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
70726         var node = createSynthesizedNode(198 /* TaggedTemplateExpression */);
70727         node.tag = ts.parenthesizeForAccess(tag);
70728         if (template) {
70729             node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
70730             node.template = template;
70731         }
70732         else {
70733             node.typeArguments = undefined;
70734             node.template = typeArgumentsOrTemplate;
70735         }
70736         return node;
70737     }
70738     ts.createTaggedTemplate = createTaggedTemplate;
70739     function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
70740         return node.tag !== tag
70741             || (template
70742                 ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
70743                 : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
70744             ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
70745             : node;
70746     }
70747     ts.updateTaggedTemplate = updateTaggedTemplate;
70748     function createTypeAssertion(type, expression) {
70749         var node = createSynthesizedNode(199 /* TypeAssertionExpression */);
70750         node.type = type;
70751         node.expression = ts.parenthesizePrefixOperand(expression);
70752         return node;
70753     }
70754     ts.createTypeAssertion = createTypeAssertion;
70755     function updateTypeAssertion(node, type, expression) {
70756         return node.type !== type
70757             || node.expression !== expression
70758             ? updateNode(createTypeAssertion(type, expression), node)
70759             : node;
70760     }
70761     ts.updateTypeAssertion = updateTypeAssertion;
70762     function createParen(expression) {
70763         var node = createSynthesizedNode(200 /* ParenthesizedExpression */);
70764         node.expression = expression;
70765         return node;
70766     }
70767     ts.createParen = createParen;
70768     function updateParen(node, expression) {
70769         return node.expression !== expression
70770             ? updateNode(createParen(expression), node)
70771             : node;
70772     }
70773     ts.updateParen = updateParen;
70774     function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70775         var node = createSynthesizedNode(201 /* FunctionExpression */);
70776         node.modifiers = asNodeArray(modifiers);
70777         node.asteriskToken = asteriskToken;
70778         node.name = asName(name);
70779         node.typeParameters = asNodeArray(typeParameters);
70780         node.parameters = createNodeArray(parameters);
70781         node.type = type;
70782         node.body = body;
70783         return node;
70784     }
70785     ts.createFunctionExpression = createFunctionExpression;
70786     function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70787         return node.name !== name
70788             || node.modifiers !== modifiers
70789             || node.asteriskToken !== asteriskToken
70790             || node.typeParameters !== typeParameters
70791             || node.parameters !== parameters
70792             || node.type !== type
70793             || node.body !== body
70794             ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
70795             : node;
70796     }
70797     ts.updateFunctionExpression = updateFunctionExpression;
70798     function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70799         var node = createSynthesizedNode(202 /* ArrowFunction */);
70800         node.modifiers = asNodeArray(modifiers);
70801         node.typeParameters = asNodeArray(typeParameters);
70802         node.parameters = createNodeArray(parameters);
70803         node.type = type;
70804         node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(38 /* EqualsGreaterThanToken */);
70805         node.body = ts.parenthesizeConciseBody(body);
70806         return node;
70807     }
70808     ts.createArrowFunction = createArrowFunction;
70809     function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70810         return node.modifiers !== modifiers
70811             || node.typeParameters !== typeParameters
70812             || node.parameters !== parameters
70813             || node.type !== type
70814             || node.equalsGreaterThanToken !== equalsGreaterThanToken
70815             || node.body !== body
70816             ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
70817             : node;
70818     }
70819     ts.updateArrowFunction = updateArrowFunction;
70820     function createDelete(expression) {
70821         var node = createSynthesizedNode(203 /* DeleteExpression */);
70822         node.expression = ts.parenthesizePrefixOperand(expression);
70823         return node;
70824     }
70825     ts.createDelete = createDelete;
70826     function updateDelete(node, expression) {
70827         return node.expression !== expression
70828             ? updateNode(createDelete(expression), node)
70829             : node;
70830     }
70831     ts.updateDelete = updateDelete;
70832     function createTypeOf(expression) {
70833         var node = createSynthesizedNode(204 /* TypeOfExpression */);
70834         node.expression = ts.parenthesizePrefixOperand(expression);
70835         return node;
70836     }
70837     ts.createTypeOf = createTypeOf;
70838     function updateTypeOf(node, expression) {
70839         return node.expression !== expression
70840             ? updateNode(createTypeOf(expression), node)
70841             : node;
70842     }
70843     ts.updateTypeOf = updateTypeOf;
70844     function createVoid(expression) {
70845         var node = createSynthesizedNode(205 /* VoidExpression */);
70846         node.expression = ts.parenthesizePrefixOperand(expression);
70847         return node;
70848     }
70849     ts.createVoid = createVoid;
70850     function updateVoid(node, expression) {
70851         return node.expression !== expression
70852             ? updateNode(createVoid(expression), node)
70853             : node;
70854     }
70855     ts.updateVoid = updateVoid;
70856     function createAwait(expression) {
70857         var node = createSynthesizedNode(206 /* AwaitExpression */);
70858         node.expression = ts.parenthesizePrefixOperand(expression);
70859         return node;
70860     }
70861     ts.createAwait = createAwait;
70862     function updateAwait(node, expression) {
70863         return node.expression !== expression
70864             ? updateNode(createAwait(expression), node)
70865             : node;
70866     }
70867     ts.updateAwait = updateAwait;
70868     function createPrefix(operator, operand) {
70869         var node = createSynthesizedNode(207 /* PrefixUnaryExpression */);
70870         node.operator = operator;
70871         node.operand = ts.parenthesizePrefixOperand(operand);
70872         return node;
70873     }
70874     ts.createPrefix = createPrefix;
70875     function updatePrefix(node, operand) {
70876         return node.operand !== operand
70877             ? updateNode(createPrefix(node.operator, operand), node)
70878             : node;
70879     }
70880     ts.updatePrefix = updatePrefix;
70881     function createPostfix(operand, operator) {
70882         var node = createSynthesizedNode(208 /* PostfixUnaryExpression */);
70883         node.operand = ts.parenthesizePostfixOperand(operand);
70884         node.operator = operator;
70885         return node;
70886     }
70887     ts.createPostfix = createPostfix;
70888     function updatePostfix(node, operand) {
70889         return node.operand !== operand
70890             ? updateNode(createPostfix(operand, node.operator), node)
70891             : node;
70892     }
70893     ts.updatePostfix = updatePostfix;
70894     function createBinary(left, operator, right) {
70895         var node = createSynthesizedNode(209 /* BinaryExpression */);
70896         var operatorToken = asToken(operator);
70897         var operatorKind = operatorToken.kind;
70898         node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
70899         node.operatorToken = operatorToken;
70900         node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
70901         return node;
70902     }
70903     ts.createBinary = createBinary;
70904     function updateBinary(node, left, right, operator) {
70905         return node.left !== left
70906             || node.right !== right
70907             ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
70908             : node;
70909     }
70910     ts.updateBinary = updateBinary;
70911     function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
70912         var node = createSynthesizedNode(210 /* ConditionalExpression */);
70913         node.condition = ts.parenthesizeForConditionalHead(condition);
70914         node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(57 /* QuestionToken */);
70915         node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
70916         node.colonToken = whenFalse ? colonToken : createToken(58 /* ColonToken */);
70917         node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
70918         return node;
70919     }
70920     ts.createConditional = createConditional;
70921     function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
70922         return node.condition !== condition
70923             || node.questionToken !== questionToken
70924             || node.whenTrue !== whenTrue
70925             || node.colonToken !== colonToken
70926             || node.whenFalse !== whenFalse
70927             ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
70928             : node;
70929     }
70930     ts.updateConditional = updateConditional;
70931     function createTemplateExpression(head, templateSpans) {
70932         var node = createSynthesizedNode(211 /* TemplateExpression */);
70933         node.head = head;
70934         node.templateSpans = createNodeArray(templateSpans);
70935         return node;
70936     }
70937     ts.createTemplateExpression = createTemplateExpression;
70938     function updateTemplateExpression(node, head, templateSpans) {
70939         return node.head !== head
70940             || node.templateSpans !== templateSpans
70941             ? updateNode(createTemplateExpression(head, templateSpans), node)
70942             : node;
70943     }
70944     ts.updateTemplateExpression = updateTemplateExpression;
70945     var rawTextScanner;
70946     var invalidValueSentinel = {};
70947     function getCookedText(kind, rawText) {
70948         if (!rawTextScanner) {
70949             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
70950         }
70951         switch (kind) {
70952             case 14 /* NoSubstitutionTemplateLiteral */:
70953                 rawTextScanner.setText("`" + rawText + "`");
70954                 break;
70955             case 15 /* TemplateHead */:
70956                 rawTextScanner.setText("`" + rawText + "${");
70957                 break;
70958             case 16 /* TemplateMiddle */:
70959                 rawTextScanner.setText("}" + rawText + "${");
70960                 break;
70961             case 17 /* TemplateTail */:
70962                 rawTextScanner.setText("}" + rawText + "`");
70963                 break;
70964         }
70965         var token = rawTextScanner.scan();
70966         if (token === 23 /* CloseBracketToken */) {
70967             token = rawTextScanner.reScanTemplateToken(/* isTaggedTemplate */ false);
70968         }
70969         if (rawTextScanner.isUnterminated()) {
70970             rawTextScanner.setText(undefined);
70971             return invalidValueSentinel;
70972         }
70973         var tokenValue;
70974         switch (token) {
70975             case 14 /* NoSubstitutionTemplateLiteral */:
70976             case 15 /* TemplateHead */:
70977             case 16 /* TemplateMiddle */:
70978             case 17 /* TemplateTail */:
70979                 tokenValue = rawTextScanner.getTokenValue();
70980                 break;
70981         }
70982         if (rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
70983             rawTextScanner.setText(undefined);
70984             return invalidValueSentinel;
70985         }
70986         rawTextScanner.setText(undefined);
70987         return tokenValue;
70988     }
70989     function createTemplateLiteralLikeNode(kind, text, rawText) {
70990         var node = createSynthesizedNode(kind);
70991         node.text = text;
70992         if (rawText === undefined || text === rawText) {
70993             node.rawText = rawText;
70994         }
70995         else {
70996             var cooked = getCookedText(kind, rawText);
70997             if (typeof cooked === "object") {
70998                 return ts.Debug.fail("Invalid raw text");
70999             }
71000             ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
71001             node.rawText = rawText;
71002         }
71003         return node;
71004     }
71005     function createTemplateHead(text, rawText) {
71006         var node = createTemplateLiteralLikeNode(15 /* TemplateHead */, text, rawText);
71007         node.text = text;
71008         return node;
71009     }
71010     ts.createTemplateHead = createTemplateHead;
71011     function createTemplateMiddle(text, rawText) {
71012         var node = createTemplateLiteralLikeNode(16 /* TemplateMiddle */, text, rawText);
71013         node.text = text;
71014         return node;
71015     }
71016     ts.createTemplateMiddle = createTemplateMiddle;
71017     function createTemplateTail(text, rawText) {
71018         var node = createTemplateLiteralLikeNode(17 /* TemplateTail */, text, rawText);
71019         node.text = text;
71020         return node;
71021     }
71022     ts.createTemplateTail = createTemplateTail;
71023     function createNoSubstitutionTemplateLiteral(text, rawText) {
71024         var node = createTemplateLiteralLikeNode(14 /* NoSubstitutionTemplateLiteral */, text, rawText);
71025         return node;
71026     }
71027     ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
71028     function createYield(asteriskTokenOrExpression, expression) {
71029         var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
71030         expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
71031         var node = createSynthesizedNode(212 /* YieldExpression */);
71032         node.asteriskToken = asteriskToken;
71033         node.expression = expression && ts.parenthesizeExpressionForList(expression);
71034         return node;
71035     }
71036     ts.createYield = createYield;
71037     function updateYield(node, asteriskToken, expression) {
71038         return node.expression !== expression
71039             || node.asteriskToken !== asteriskToken
71040             ? updateNode(createYield(asteriskToken, expression), node)
71041             : node;
71042     }
71043     ts.updateYield = updateYield;
71044     function createSpread(expression) {
71045         var node = createSynthesizedNode(213 /* SpreadElement */);
71046         node.expression = ts.parenthesizeExpressionForList(expression);
71047         return node;
71048     }
71049     ts.createSpread = createSpread;
71050     function updateSpread(node, expression) {
71051         return node.expression !== expression
71052             ? updateNode(createSpread(expression), node)
71053             : node;
71054     }
71055     ts.updateSpread = updateSpread;
71056     function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
71057         var node = createSynthesizedNode(214 /* ClassExpression */);
71058         node.decorators = undefined;
71059         node.modifiers = asNodeArray(modifiers);
71060         node.name = asName(name);
71061         node.typeParameters = asNodeArray(typeParameters);
71062         node.heritageClauses = asNodeArray(heritageClauses);
71063         node.members = createNodeArray(members);
71064         return node;
71065     }
71066     ts.createClassExpression = createClassExpression;
71067     function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
71068         return node.modifiers !== modifiers
71069             || node.name !== name
71070             || node.typeParameters !== typeParameters
71071             || node.heritageClauses !== heritageClauses
71072             || node.members !== members
71073             ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
71074             : node;
71075     }
71076     ts.updateClassExpression = updateClassExpression;
71077     function createOmittedExpression() {
71078         return createSynthesizedNode(215 /* OmittedExpression */);
71079     }
71080     ts.createOmittedExpression = createOmittedExpression;
71081     function createExpressionWithTypeArguments(typeArguments, expression) {
71082         var node = createSynthesizedNode(216 /* ExpressionWithTypeArguments */);
71083         node.expression = ts.parenthesizeForAccess(expression);
71084         node.typeArguments = asNodeArray(typeArguments);
71085         return node;
71086     }
71087     ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
71088     function updateExpressionWithTypeArguments(node, typeArguments, expression) {
71089         return node.typeArguments !== typeArguments
71090             || node.expression !== expression
71091             ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
71092             : node;
71093     }
71094     ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
71095     function createAsExpression(expression, type) {
71096         var node = createSynthesizedNode(217 /* AsExpression */);
71097         node.expression = expression;
71098         node.type = type;
71099         return node;
71100     }
71101     ts.createAsExpression = createAsExpression;
71102     function updateAsExpression(node, expression, type) {
71103         return node.expression !== expression
71104             || node.type !== type
71105             ? updateNode(createAsExpression(expression, type), node)
71106             : node;
71107     }
71108     ts.updateAsExpression = updateAsExpression;
71109     function createNonNullExpression(expression) {
71110         var node = createSynthesizedNode(218 /* NonNullExpression */);
71111         node.expression = ts.parenthesizeForAccess(expression);
71112         return node;
71113     }
71114     ts.createNonNullExpression = createNonNullExpression;
71115     function updateNonNullExpression(node, expression) {
71116         if (ts.isNonNullChain(node)) {
71117             return updateNonNullChain(node, expression);
71118         }
71119         return node.expression !== expression
71120             ? updateNode(createNonNullExpression(expression), node)
71121             : node;
71122     }
71123     ts.updateNonNullExpression = updateNonNullExpression;
71124     function createNonNullChain(expression) {
71125         var node = createSynthesizedNode(218 /* NonNullExpression */);
71126         node.flags |= 32 /* OptionalChain */;
71127         node.expression = ts.parenthesizeForAccess(expression);
71128         return node;
71129     }
71130     ts.createNonNullChain = createNonNullChain;
71131     function updateNonNullChain(node, expression) {
71132         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
71133         return node.expression !== expression
71134             ? updateNode(createNonNullChain(expression), node)
71135             : node;
71136     }
71137     ts.updateNonNullChain = updateNonNullChain;
71138     function createMetaProperty(keywordToken, name) {
71139         var node = createSynthesizedNode(219 /* MetaProperty */);
71140         node.keywordToken = keywordToken;
71141         node.name = name;
71142         return node;
71143     }
71144     ts.createMetaProperty = createMetaProperty;
71145     function updateMetaProperty(node, name) {
71146         return node.name !== name
71147             ? updateNode(createMetaProperty(node.keywordToken, name), node)
71148             : node;
71149     }
71150     ts.updateMetaProperty = updateMetaProperty;
71151     // Misc
71152     function createTemplateSpan(expression, literal) {
71153         var node = createSynthesizedNode(221 /* TemplateSpan */);
71154         node.expression = expression;
71155         node.literal = literal;
71156         return node;
71157     }
71158     ts.createTemplateSpan = createTemplateSpan;
71159     function updateTemplateSpan(node, expression, literal) {
71160         return node.expression !== expression
71161             || node.literal !== literal
71162             ? updateNode(createTemplateSpan(expression, literal), node)
71163             : node;
71164     }
71165     ts.updateTemplateSpan = updateTemplateSpan;
71166     function createSemicolonClassElement() {
71167         return createSynthesizedNode(222 /* SemicolonClassElement */);
71168     }
71169     ts.createSemicolonClassElement = createSemicolonClassElement;
71170     // Element
71171     function createBlock(statements, multiLine) {
71172         var block = createSynthesizedNode(223 /* Block */);
71173         block.statements = createNodeArray(statements);
71174         if (multiLine)
71175             block.multiLine = multiLine;
71176         return block;
71177     }
71178     ts.createBlock = createBlock;
71179     function updateBlock(node, statements) {
71180         return node.statements !== statements
71181             ? updateNode(createBlock(statements, node.multiLine), node)
71182             : node;
71183     }
71184     ts.updateBlock = updateBlock;
71185     function createVariableStatement(modifiers, declarationList) {
71186         var node = createSynthesizedNode(225 /* VariableStatement */);
71187         node.decorators = undefined;
71188         node.modifiers = asNodeArray(modifiers);
71189         node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
71190         return node;
71191     }
71192     ts.createVariableStatement = createVariableStatement;
71193     function updateVariableStatement(node, modifiers, declarationList) {
71194         return node.modifiers !== modifiers
71195             || node.declarationList !== declarationList
71196             ? updateNode(createVariableStatement(modifiers, declarationList), node)
71197             : node;
71198     }
71199     ts.updateVariableStatement = updateVariableStatement;
71200     function createEmptyStatement() {
71201         return createSynthesizedNode(224 /* EmptyStatement */);
71202     }
71203     ts.createEmptyStatement = createEmptyStatement;
71204     function createExpressionStatement(expression) {
71205         var node = createSynthesizedNode(226 /* ExpressionStatement */);
71206         node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
71207         return node;
71208     }
71209     ts.createExpressionStatement = createExpressionStatement;
71210     function updateExpressionStatement(node, expression) {
71211         return node.expression !== expression
71212             ? updateNode(createExpressionStatement(expression), node)
71213             : node;
71214     }
71215     ts.updateExpressionStatement = updateExpressionStatement;
71216     /** @deprecated Use `createExpressionStatement` instead.  */
71217     ts.createStatement = createExpressionStatement;
71218     /** @deprecated Use `updateExpressionStatement` instead.  */
71219     ts.updateStatement = updateExpressionStatement;
71220     function createIf(expression, thenStatement, elseStatement) {
71221         var node = createSynthesizedNode(227 /* IfStatement */);
71222         node.expression = expression;
71223         node.thenStatement = asEmbeddedStatement(thenStatement);
71224         node.elseStatement = asEmbeddedStatement(elseStatement);
71225         return node;
71226     }
71227     ts.createIf = createIf;
71228     function updateIf(node, expression, thenStatement, elseStatement) {
71229         return node.expression !== expression
71230             || node.thenStatement !== thenStatement
71231             || node.elseStatement !== elseStatement
71232             ? updateNode(createIf(expression, thenStatement, elseStatement), node)
71233             : node;
71234     }
71235     ts.updateIf = updateIf;
71236     function createDo(statement, expression) {
71237         var node = createSynthesizedNode(228 /* DoStatement */);
71238         node.statement = asEmbeddedStatement(statement);
71239         node.expression = expression;
71240         return node;
71241     }
71242     ts.createDo = createDo;
71243     function updateDo(node, statement, expression) {
71244         return node.statement !== statement
71245             || node.expression !== expression
71246             ? updateNode(createDo(statement, expression), node)
71247             : node;
71248     }
71249     ts.updateDo = updateDo;
71250     function createWhile(expression, statement) {
71251         var node = createSynthesizedNode(229 /* WhileStatement */);
71252         node.expression = expression;
71253         node.statement = asEmbeddedStatement(statement);
71254         return node;
71255     }
71256     ts.createWhile = createWhile;
71257     function updateWhile(node, expression, statement) {
71258         return node.expression !== expression
71259             || node.statement !== statement
71260             ? updateNode(createWhile(expression, statement), node)
71261             : node;
71262     }
71263     ts.updateWhile = updateWhile;
71264     function createFor(initializer, condition, incrementor, statement) {
71265         var node = createSynthesizedNode(230 /* ForStatement */);
71266         node.initializer = initializer;
71267         node.condition = condition;
71268         node.incrementor = incrementor;
71269         node.statement = asEmbeddedStatement(statement);
71270         return node;
71271     }
71272     ts.createFor = createFor;
71273     function updateFor(node, initializer, condition, incrementor, statement) {
71274         return node.initializer !== initializer
71275             || node.condition !== condition
71276             || node.incrementor !== incrementor
71277             || node.statement !== statement
71278             ? updateNode(createFor(initializer, condition, incrementor, statement), node)
71279             : node;
71280     }
71281     ts.updateFor = updateFor;
71282     function createForIn(initializer, expression, statement) {
71283         var node = createSynthesizedNode(231 /* ForInStatement */);
71284         node.initializer = initializer;
71285         node.expression = expression;
71286         node.statement = asEmbeddedStatement(statement);
71287         return node;
71288     }
71289     ts.createForIn = createForIn;
71290     function updateForIn(node, initializer, expression, statement) {
71291         return node.initializer !== initializer
71292             || node.expression !== expression
71293             || node.statement !== statement
71294             ? updateNode(createForIn(initializer, expression, statement), node)
71295             : node;
71296     }
71297     ts.updateForIn = updateForIn;
71298     function createForOf(awaitModifier, initializer, expression, statement) {
71299         var node = createSynthesizedNode(232 /* ForOfStatement */);
71300         node.awaitModifier = awaitModifier;
71301         node.initializer = initializer;
71302         node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression;
71303         node.statement = asEmbeddedStatement(statement);
71304         return node;
71305     }
71306     ts.createForOf = createForOf;
71307     function updateForOf(node, awaitModifier, initializer, expression, statement) {
71308         return node.awaitModifier !== awaitModifier
71309             || node.initializer !== initializer
71310             || node.expression !== expression
71311             || node.statement !== statement
71312             ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
71313             : node;
71314     }
71315     ts.updateForOf = updateForOf;
71316     function createContinue(label) {
71317         var node = createSynthesizedNode(233 /* ContinueStatement */);
71318         node.label = asName(label);
71319         return node;
71320     }
71321     ts.createContinue = createContinue;
71322     function updateContinue(node, label) {
71323         return node.label !== label
71324             ? updateNode(createContinue(label), node)
71325             : node;
71326     }
71327     ts.updateContinue = updateContinue;
71328     function createBreak(label) {
71329         var node = createSynthesizedNode(234 /* BreakStatement */);
71330         node.label = asName(label);
71331         return node;
71332     }
71333     ts.createBreak = createBreak;
71334     function updateBreak(node, label) {
71335         return node.label !== label
71336             ? updateNode(createBreak(label), node)
71337             : node;
71338     }
71339     ts.updateBreak = updateBreak;
71340     function createReturn(expression) {
71341         var node = createSynthesizedNode(235 /* ReturnStatement */);
71342         node.expression = expression;
71343         return node;
71344     }
71345     ts.createReturn = createReturn;
71346     function updateReturn(node, expression) {
71347         return node.expression !== expression
71348             ? updateNode(createReturn(expression), node)
71349             : node;
71350     }
71351     ts.updateReturn = updateReturn;
71352     function createWith(expression, statement) {
71353         var node = createSynthesizedNode(236 /* WithStatement */);
71354         node.expression = expression;
71355         node.statement = asEmbeddedStatement(statement);
71356         return node;
71357     }
71358     ts.createWith = createWith;
71359     function updateWith(node, expression, statement) {
71360         return node.expression !== expression
71361             || node.statement !== statement
71362             ? updateNode(createWith(expression, statement), node)
71363             : node;
71364     }
71365     ts.updateWith = updateWith;
71366     function createSwitch(expression, caseBlock) {
71367         var node = createSynthesizedNode(237 /* SwitchStatement */);
71368         node.expression = ts.parenthesizeExpressionForList(expression);
71369         node.caseBlock = caseBlock;
71370         return node;
71371     }
71372     ts.createSwitch = createSwitch;
71373     function updateSwitch(node, expression, caseBlock) {
71374         return node.expression !== expression
71375             || node.caseBlock !== caseBlock
71376             ? updateNode(createSwitch(expression, caseBlock), node)
71377             : node;
71378     }
71379     ts.updateSwitch = updateSwitch;
71380     function createLabel(label, statement) {
71381         var node = createSynthesizedNode(238 /* LabeledStatement */);
71382         node.label = asName(label);
71383         node.statement = asEmbeddedStatement(statement);
71384         return node;
71385     }
71386     ts.createLabel = createLabel;
71387     function updateLabel(node, label, statement) {
71388         return node.label !== label
71389             || node.statement !== statement
71390             ? updateNode(createLabel(label, statement), node)
71391             : node;
71392     }
71393     ts.updateLabel = updateLabel;
71394     function createThrow(expression) {
71395         var node = createSynthesizedNode(239 /* ThrowStatement */);
71396         node.expression = expression;
71397         return node;
71398     }
71399     ts.createThrow = createThrow;
71400     function updateThrow(node, expression) {
71401         return node.expression !== expression
71402             ? updateNode(createThrow(expression), node)
71403             : node;
71404     }
71405     ts.updateThrow = updateThrow;
71406     function createTry(tryBlock, catchClause, finallyBlock) {
71407         var node = createSynthesizedNode(240 /* TryStatement */);
71408         node.tryBlock = tryBlock;
71409         node.catchClause = catchClause;
71410         node.finallyBlock = finallyBlock;
71411         return node;
71412     }
71413     ts.createTry = createTry;
71414     function updateTry(node, tryBlock, catchClause, finallyBlock) {
71415         return node.tryBlock !== tryBlock
71416             || node.catchClause !== catchClause
71417             || node.finallyBlock !== finallyBlock
71418             ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
71419             : node;
71420     }
71421     ts.updateTry = updateTry;
71422     function createDebuggerStatement() {
71423         return createSynthesizedNode(241 /* DebuggerStatement */);
71424     }
71425     ts.createDebuggerStatement = createDebuggerStatement;
71426     function createVariableDeclaration(name, type, initializer) {
71427         /* Internally, one should probably use createTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71428         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71429         node.name = asName(name);
71430         node.type = type;
71431         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71432         return node;
71433     }
71434     ts.createVariableDeclaration = createVariableDeclaration;
71435     function updateVariableDeclaration(node, name, type, initializer) {
71436         /* Internally, one should probably use updateTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71437         return node.name !== name
71438             || node.type !== type
71439             || node.initializer !== initializer
71440             ? updateNode(createVariableDeclaration(name, type, initializer), node)
71441             : node;
71442     }
71443     ts.updateVariableDeclaration = updateVariableDeclaration;
71444     /* @internal */
71445     function createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer) {
71446         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71447         node.name = asName(name);
71448         node.type = type;
71449         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71450         node.exclamationToken = exclaimationToken;
71451         return node;
71452     }
71453     ts.createTypeScriptVariableDeclaration = createTypeScriptVariableDeclaration;
71454     /* @internal */
71455     function updateTypeScriptVariableDeclaration(node, name, exclaimationToken, type, initializer) {
71456         return node.name !== name
71457             || node.type !== type
71458             || node.initializer !== initializer
71459             || node.exclamationToken !== exclaimationToken
71460             ? updateNode(createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer), node)
71461             : node;
71462     }
71463     ts.updateTypeScriptVariableDeclaration = updateTypeScriptVariableDeclaration;
71464     function createVariableDeclarationList(declarations, flags) {
71465         if (flags === void 0) { flags = 0 /* None */; }
71466         var node = createSynthesizedNode(243 /* VariableDeclarationList */);
71467         node.flags |= flags & 3 /* BlockScoped */;
71468         node.declarations = createNodeArray(declarations);
71469         return node;
71470     }
71471     ts.createVariableDeclarationList = createVariableDeclarationList;
71472     function updateVariableDeclarationList(node, declarations) {
71473         return node.declarations !== declarations
71474             ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
71475             : node;
71476     }
71477     ts.updateVariableDeclarationList = updateVariableDeclarationList;
71478     function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71479         var node = createSynthesizedNode(244 /* FunctionDeclaration */);
71480         node.decorators = asNodeArray(decorators);
71481         node.modifiers = asNodeArray(modifiers);
71482         node.asteriskToken = asteriskToken;
71483         node.name = asName(name);
71484         node.typeParameters = asNodeArray(typeParameters);
71485         node.parameters = createNodeArray(parameters);
71486         node.type = type;
71487         node.body = body;
71488         return node;
71489     }
71490     ts.createFunctionDeclaration = createFunctionDeclaration;
71491     function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71492         return node.decorators !== decorators
71493             || node.modifiers !== modifiers
71494             || node.asteriskToken !== asteriskToken
71495             || node.name !== name
71496             || node.typeParameters !== typeParameters
71497             || node.parameters !== parameters
71498             || node.type !== type
71499             || node.body !== body
71500             ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
71501             : node;
71502     }
71503     ts.updateFunctionDeclaration = updateFunctionDeclaration;
71504     /* @internal */
71505     function updateFunctionLikeBody(declaration, body) {
71506         switch (declaration.kind) {
71507             case 244 /* FunctionDeclaration */:
71508                 return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71509             case 161 /* MethodDeclaration */:
71510                 return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body);
71511             case 163 /* GetAccessor */:
71512                 return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body);
71513             case 164 /* SetAccessor */:
71514                 return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body);
71515             case 162 /* Constructor */:
71516                 return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body);
71517             case 201 /* FunctionExpression */:
71518                 return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71519             case 202 /* ArrowFunction */:
71520                 return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body);
71521         }
71522     }
71523     ts.updateFunctionLikeBody = updateFunctionLikeBody;
71524     function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71525         var node = createSynthesizedNode(245 /* ClassDeclaration */);
71526         node.decorators = asNodeArray(decorators);
71527         node.modifiers = asNodeArray(modifiers);
71528         node.name = asName(name);
71529         node.typeParameters = asNodeArray(typeParameters);
71530         node.heritageClauses = asNodeArray(heritageClauses);
71531         node.members = createNodeArray(members);
71532         return node;
71533     }
71534     ts.createClassDeclaration = createClassDeclaration;
71535     function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71536         return node.decorators !== decorators
71537             || node.modifiers !== modifiers
71538             || node.name !== name
71539             || node.typeParameters !== typeParameters
71540             || node.heritageClauses !== heritageClauses
71541             || node.members !== members
71542             ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71543             : node;
71544     }
71545     ts.updateClassDeclaration = updateClassDeclaration;
71546     function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71547         var node = createSynthesizedNode(246 /* InterfaceDeclaration */);
71548         node.decorators = asNodeArray(decorators);
71549         node.modifiers = asNodeArray(modifiers);
71550         node.name = asName(name);
71551         node.typeParameters = asNodeArray(typeParameters);
71552         node.heritageClauses = asNodeArray(heritageClauses);
71553         node.members = createNodeArray(members);
71554         return node;
71555     }
71556     ts.createInterfaceDeclaration = createInterfaceDeclaration;
71557     function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71558         return node.decorators !== decorators
71559             || node.modifiers !== modifiers
71560             || node.name !== name
71561             || node.typeParameters !== typeParameters
71562             || node.heritageClauses !== heritageClauses
71563             || node.members !== members
71564             ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71565             : node;
71566     }
71567     ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
71568     function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
71569         var node = createSynthesizedNode(247 /* TypeAliasDeclaration */);
71570         node.decorators = asNodeArray(decorators);
71571         node.modifiers = asNodeArray(modifiers);
71572         node.name = asName(name);
71573         node.typeParameters = asNodeArray(typeParameters);
71574         node.type = type;
71575         return node;
71576     }
71577     ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
71578     function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
71579         return node.decorators !== decorators
71580             || node.modifiers !== modifiers
71581             || node.name !== name
71582             || node.typeParameters !== typeParameters
71583             || node.type !== type
71584             ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
71585             : node;
71586     }
71587     ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
71588     function createEnumDeclaration(decorators, modifiers, name, members) {
71589         var node = createSynthesizedNode(248 /* EnumDeclaration */);
71590         node.decorators = asNodeArray(decorators);
71591         node.modifiers = asNodeArray(modifiers);
71592         node.name = asName(name);
71593         node.members = createNodeArray(members);
71594         return node;
71595     }
71596     ts.createEnumDeclaration = createEnumDeclaration;
71597     function updateEnumDeclaration(node, decorators, modifiers, name, members) {
71598         return node.decorators !== decorators
71599             || node.modifiers !== modifiers
71600             || node.name !== name
71601             || node.members !== members
71602             ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
71603             : node;
71604     }
71605     ts.updateEnumDeclaration = updateEnumDeclaration;
71606     function createModuleDeclaration(decorators, modifiers, name, body, flags) {
71607         if (flags === void 0) { flags = 0 /* None */; }
71608         var node = createSynthesizedNode(249 /* ModuleDeclaration */);
71609         node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
71610         node.decorators = asNodeArray(decorators);
71611         node.modifiers = asNodeArray(modifiers);
71612         node.name = name;
71613         node.body = body;
71614         return node;
71615     }
71616     ts.createModuleDeclaration = createModuleDeclaration;
71617     function updateModuleDeclaration(node, decorators, modifiers, name, body) {
71618         return node.decorators !== decorators
71619             || node.modifiers !== modifiers
71620             || node.name !== name
71621             || node.body !== body
71622             ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
71623             : node;
71624     }
71625     ts.updateModuleDeclaration = updateModuleDeclaration;
71626     function createModuleBlock(statements) {
71627         var node = createSynthesizedNode(250 /* ModuleBlock */);
71628         node.statements = createNodeArray(statements);
71629         return node;
71630     }
71631     ts.createModuleBlock = createModuleBlock;
71632     function updateModuleBlock(node, statements) {
71633         return node.statements !== statements
71634             ? updateNode(createModuleBlock(statements), node)
71635             : node;
71636     }
71637     ts.updateModuleBlock = updateModuleBlock;
71638     function createCaseBlock(clauses) {
71639         var node = createSynthesizedNode(251 /* CaseBlock */);
71640         node.clauses = createNodeArray(clauses);
71641         return node;
71642     }
71643     ts.createCaseBlock = createCaseBlock;
71644     function updateCaseBlock(node, clauses) {
71645         return node.clauses !== clauses
71646             ? updateNode(createCaseBlock(clauses), node)
71647             : node;
71648     }
71649     ts.updateCaseBlock = updateCaseBlock;
71650     function createNamespaceExportDeclaration(name) {
71651         var node = createSynthesizedNode(252 /* NamespaceExportDeclaration */);
71652         node.name = asName(name);
71653         return node;
71654     }
71655     ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
71656     function updateNamespaceExportDeclaration(node, name) {
71657         return node.name !== name
71658             ? updateNode(createNamespaceExportDeclaration(name), node)
71659             : node;
71660     }
71661     ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
71662     function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
71663         var node = createSynthesizedNode(253 /* ImportEqualsDeclaration */);
71664         node.decorators = asNodeArray(decorators);
71665         node.modifiers = asNodeArray(modifiers);
71666         node.name = asName(name);
71667         node.moduleReference = moduleReference;
71668         return node;
71669     }
71670     ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
71671     function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
71672         return node.decorators !== decorators
71673             || node.modifiers !== modifiers
71674             || node.name !== name
71675             || node.moduleReference !== moduleReference
71676             ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
71677             : node;
71678     }
71679     ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
71680     function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
71681         var node = createSynthesizedNode(254 /* ImportDeclaration */);
71682         node.decorators = asNodeArray(decorators);
71683         node.modifiers = asNodeArray(modifiers);
71684         node.importClause = importClause;
71685         node.moduleSpecifier = moduleSpecifier;
71686         return node;
71687     }
71688     ts.createImportDeclaration = createImportDeclaration;
71689     function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
71690         return node.decorators !== decorators
71691             || node.modifiers !== modifiers
71692             || node.importClause !== importClause
71693             || node.moduleSpecifier !== moduleSpecifier
71694             ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
71695             : node;
71696     }
71697     ts.updateImportDeclaration = updateImportDeclaration;
71698     function createImportClause(name, namedBindings, isTypeOnly) {
71699         if (isTypeOnly === void 0) { isTypeOnly = false; }
71700         var node = createSynthesizedNode(255 /* ImportClause */);
71701         node.name = name;
71702         node.namedBindings = namedBindings;
71703         node.isTypeOnly = isTypeOnly;
71704         return node;
71705     }
71706     ts.createImportClause = createImportClause;
71707     function updateImportClause(node, name, namedBindings, isTypeOnly) {
71708         return node.name !== name
71709             || node.namedBindings !== namedBindings
71710             || node.isTypeOnly !== isTypeOnly
71711             ? updateNode(createImportClause(name, namedBindings, isTypeOnly), node)
71712             : node;
71713     }
71714     ts.updateImportClause = updateImportClause;
71715     function createNamespaceImport(name) {
71716         var node = createSynthesizedNode(256 /* NamespaceImport */);
71717         node.name = name;
71718         return node;
71719     }
71720     ts.createNamespaceImport = createNamespaceImport;
71721     function createNamespaceExport(name) {
71722         var node = createSynthesizedNode(262 /* NamespaceExport */);
71723         node.name = name;
71724         return node;
71725     }
71726     ts.createNamespaceExport = createNamespaceExport;
71727     function updateNamespaceImport(node, name) {
71728         return node.name !== name
71729             ? updateNode(createNamespaceImport(name), node)
71730             : node;
71731     }
71732     ts.updateNamespaceImport = updateNamespaceImport;
71733     function updateNamespaceExport(node, name) {
71734         return node.name !== name
71735             ? updateNode(createNamespaceExport(name), node)
71736             : node;
71737     }
71738     ts.updateNamespaceExport = updateNamespaceExport;
71739     function createNamedImports(elements) {
71740         var node = createSynthesizedNode(257 /* NamedImports */);
71741         node.elements = createNodeArray(elements);
71742         return node;
71743     }
71744     ts.createNamedImports = createNamedImports;
71745     function updateNamedImports(node, elements) {
71746         return node.elements !== elements
71747             ? updateNode(createNamedImports(elements), node)
71748             : node;
71749     }
71750     ts.updateNamedImports = updateNamedImports;
71751     function createImportSpecifier(propertyName, name) {
71752         var node = createSynthesizedNode(258 /* ImportSpecifier */);
71753         node.propertyName = propertyName;
71754         node.name = name;
71755         return node;
71756     }
71757     ts.createImportSpecifier = createImportSpecifier;
71758     function updateImportSpecifier(node, propertyName, name) {
71759         return node.propertyName !== propertyName
71760             || node.name !== name
71761             ? updateNode(createImportSpecifier(propertyName, name), node)
71762             : node;
71763     }
71764     ts.updateImportSpecifier = updateImportSpecifier;
71765     function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
71766         var node = createSynthesizedNode(259 /* ExportAssignment */);
71767         node.decorators = asNodeArray(decorators);
71768         node.modifiers = asNodeArray(modifiers);
71769         node.isExportEquals = isExportEquals;
71770         node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(62 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
71771         return node;
71772     }
71773     ts.createExportAssignment = createExportAssignment;
71774     function updateExportAssignment(node, decorators, modifiers, expression) {
71775         return node.decorators !== decorators
71776             || node.modifiers !== modifiers
71777             || node.expression !== expression
71778             ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
71779             : node;
71780     }
71781     ts.updateExportAssignment = updateExportAssignment;
71782     function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71783         if (isTypeOnly === void 0) { isTypeOnly = false; }
71784         var node = createSynthesizedNode(260 /* ExportDeclaration */);
71785         node.decorators = asNodeArray(decorators);
71786         node.modifiers = asNodeArray(modifiers);
71787         node.isTypeOnly = isTypeOnly;
71788         node.exportClause = exportClause;
71789         node.moduleSpecifier = moduleSpecifier;
71790         return node;
71791     }
71792     ts.createExportDeclaration = createExportDeclaration;
71793     function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71794         return node.decorators !== decorators
71795             || node.modifiers !== modifiers
71796             || node.isTypeOnly !== isTypeOnly
71797             || node.exportClause !== exportClause
71798             || node.moduleSpecifier !== moduleSpecifier
71799             ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly), node)
71800             : node;
71801     }
71802     ts.updateExportDeclaration = updateExportDeclaration;
71803     /* @internal */
71804     function createEmptyExports() {
71805         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined);
71806     }
71807     ts.createEmptyExports = createEmptyExports;
71808     function createNamedExports(elements) {
71809         var node = createSynthesizedNode(261 /* NamedExports */);
71810         node.elements = createNodeArray(elements);
71811         return node;
71812     }
71813     ts.createNamedExports = createNamedExports;
71814     function updateNamedExports(node, elements) {
71815         return node.elements !== elements
71816             ? updateNode(createNamedExports(elements), node)
71817             : node;
71818     }
71819     ts.updateNamedExports = updateNamedExports;
71820     function createExportSpecifier(propertyName, name) {
71821         var node = createSynthesizedNode(263 /* ExportSpecifier */);
71822         node.propertyName = asName(propertyName);
71823         node.name = asName(name);
71824         return node;
71825     }
71826     ts.createExportSpecifier = createExportSpecifier;
71827     function updateExportSpecifier(node, propertyName, name) {
71828         return node.propertyName !== propertyName
71829             || node.name !== name
71830             ? updateNode(createExportSpecifier(propertyName, name), node)
71831             : node;
71832     }
71833     ts.updateExportSpecifier = updateExportSpecifier;
71834     // Module references
71835     function createExternalModuleReference(expression) {
71836         var node = createSynthesizedNode(265 /* ExternalModuleReference */);
71837         node.expression = expression;
71838         return node;
71839     }
71840     ts.createExternalModuleReference = createExternalModuleReference;
71841     function updateExternalModuleReference(node, expression) {
71842         return node.expression !== expression
71843             ? updateNode(createExternalModuleReference(expression), node)
71844             : node;
71845     }
71846     ts.updateExternalModuleReference = updateExternalModuleReference;
71847     // JSDoc
71848     /* @internal */
71849     function createJSDocTypeExpression(type) {
71850         var node = createSynthesizedNode(294 /* JSDocTypeExpression */);
71851         node.type = type;
71852         return node;
71853     }
71854     ts.createJSDocTypeExpression = createJSDocTypeExpression;
71855     /* @internal */
71856     function createJSDocTypeTag(typeExpression, comment) {
71857         var tag = createJSDocTag(320 /* JSDocTypeTag */, "type");
71858         tag.typeExpression = typeExpression;
71859         tag.comment = comment;
71860         return tag;
71861     }
71862     ts.createJSDocTypeTag = createJSDocTypeTag;
71863     /* @internal */
71864     function createJSDocReturnTag(typeExpression, comment) {
71865         var tag = createJSDocTag(318 /* JSDocReturnTag */, "returns");
71866         tag.typeExpression = typeExpression;
71867         tag.comment = comment;
71868         return tag;
71869     }
71870     ts.createJSDocReturnTag = createJSDocReturnTag;
71871     /** @internal */
71872     function createJSDocThisTag(typeExpression) {
71873         var tag = createJSDocTag(319 /* JSDocThisTag */, "this");
71874         tag.typeExpression = typeExpression;
71875         return tag;
71876     }
71877     ts.createJSDocThisTag = createJSDocThisTag;
71878     /* @internal */
71879     function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
71880         var tag = createJSDocTag(317 /* JSDocParameterTag */, "param");
71881         tag.typeExpression = typeExpression;
71882         tag.name = name;
71883         tag.isBracketed = isBracketed;
71884         tag.comment = comment;
71885         return tag;
71886     }
71887     ts.createJSDocParamTag = createJSDocParamTag;
71888     /* @internal */
71889     function createJSDocClassTag() {
71890         return createJSDocTag(310 /* JSDocClassTag */, "class");
71891     }
71892     ts.createJSDocClassTag = createJSDocClassTag;
71893     /* @internal */
71894     function createJSDocComment(comment, tags) {
71895         var node = createSynthesizedNode(303 /* JSDocComment */);
71896         node.comment = comment;
71897         node.tags = tags;
71898         return node;
71899     }
71900     ts.createJSDocComment = createJSDocComment;
71901     /* @internal */
71902     function createJSDocTag(kind, tagName) {
71903         var node = createSynthesizedNode(kind);
71904         node.tagName = createIdentifier(tagName);
71905         return node;
71906     }
71907     // JSX
71908     function createJsxElement(openingElement, children, closingElement) {
71909         var node = createSynthesizedNode(266 /* JsxElement */);
71910         node.openingElement = openingElement;
71911         node.children = createNodeArray(children);
71912         node.closingElement = closingElement;
71913         return node;
71914     }
71915     ts.createJsxElement = createJsxElement;
71916     function updateJsxElement(node, openingElement, children, closingElement) {
71917         return node.openingElement !== openingElement
71918             || node.children !== children
71919             || node.closingElement !== closingElement
71920             ? updateNode(createJsxElement(openingElement, children, closingElement), node)
71921             : node;
71922     }
71923     ts.updateJsxElement = updateJsxElement;
71924     function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
71925         var node = createSynthesizedNode(267 /* JsxSelfClosingElement */);
71926         node.tagName = tagName;
71927         node.typeArguments = asNodeArray(typeArguments);
71928         node.attributes = attributes;
71929         return node;
71930     }
71931     ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
71932     function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
71933         return node.tagName !== tagName
71934             || node.typeArguments !== typeArguments
71935             || node.attributes !== attributes
71936             ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
71937             : node;
71938     }
71939     ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
71940     function createJsxOpeningElement(tagName, typeArguments, attributes) {
71941         var node = createSynthesizedNode(268 /* JsxOpeningElement */);
71942         node.tagName = tagName;
71943         node.typeArguments = asNodeArray(typeArguments);
71944         node.attributes = attributes;
71945         return node;
71946     }
71947     ts.createJsxOpeningElement = createJsxOpeningElement;
71948     function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
71949         return node.tagName !== tagName
71950             || node.typeArguments !== typeArguments
71951             || node.attributes !== attributes
71952             ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
71953             : node;
71954     }
71955     ts.updateJsxOpeningElement = updateJsxOpeningElement;
71956     function createJsxClosingElement(tagName) {
71957         var node = createSynthesizedNode(269 /* JsxClosingElement */);
71958         node.tagName = tagName;
71959         return node;
71960     }
71961     ts.createJsxClosingElement = createJsxClosingElement;
71962     function updateJsxClosingElement(node, tagName) {
71963         return node.tagName !== tagName
71964             ? updateNode(createJsxClosingElement(tagName), node)
71965             : node;
71966     }
71967     ts.updateJsxClosingElement = updateJsxClosingElement;
71968     function createJsxFragment(openingFragment, children, closingFragment) {
71969         var node = createSynthesizedNode(270 /* JsxFragment */);
71970         node.openingFragment = openingFragment;
71971         node.children = createNodeArray(children);
71972         node.closingFragment = closingFragment;
71973         return node;
71974     }
71975     ts.createJsxFragment = createJsxFragment;
71976     function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
71977         var node = createSynthesizedNode(11 /* JsxText */);
71978         node.text = text;
71979         node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
71980         return node;
71981     }
71982     ts.createJsxText = createJsxText;
71983     function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
71984         return node.text !== text
71985             || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
71986             ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
71987             : node;
71988     }
71989     ts.updateJsxText = updateJsxText;
71990     function createJsxOpeningFragment() {
71991         return createSynthesizedNode(271 /* JsxOpeningFragment */);
71992     }
71993     ts.createJsxOpeningFragment = createJsxOpeningFragment;
71994     function createJsxJsxClosingFragment() {
71995         return createSynthesizedNode(272 /* JsxClosingFragment */);
71996     }
71997     ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
71998     function updateJsxFragment(node, openingFragment, children, closingFragment) {
71999         return node.openingFragment !== openingFragment
72000             || node.children !== children
72001             || node.closingFragment !== closingFragment
72002             ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
72003             : node;
72004     }
72005     ts.updateJsxFragment = updateJsxFragment;
72006     function createJsxAttribute(name, initializer) {
72007         var node = createSynthesizedNode(273 /* JsxAttribute */);
72008         node.name = name;
72009         node.initializer = initializer;
72010         return node;
72011     }
72012     ts.createJsxAttribute = createJsxAttribute;
72013     function updateJsxAttribute(node, name, initializer) {
72014         return node.name !== name
72015             || node.initializer !== initializer
72016             ? updateNode(createJsxAttribute(name, initializer), node)
72017             : node;
72018     }
72019     ts.updateJsxAttribute = updateJsxAttribute;
72020     function createJsxAttributes(properties) {
72021         var node = createSynthesizedNode(274 /* JsxAttributes */);
72022         node.properties = createNodeArray(properties);
72023         return node;
72024     }
72025     ts.createJsxAttributes = createJsxAttributes;
72026     function updateJsxAttributes(node, properties) {
72027         return node.properties !== properties
72028             ? updateNode(createJsxAttributes(properties), node)
72029             : node;
72030     }
72031     ts.updateJsxAttributes = updateJsxAttributes;
72032     function createJsxSpreadAttribute(expression) {
72033         var node = createSynthesizedNode(275 /* JsxSpreadAttribute */);
72034         node.expression = expression;
72035         return node;
72036     }
72037     ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
72038     function updateJsxSpreadAttribute(node, expression) {
72039         return node.expression !== expression
72040             ? updateNode(createJsxSpreadAttribute(expression), node)
72041             : node;
72042     }
72043     ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
72044     function createJsxExpression(dotDotDotToken, expression) {
72045         var node = createSynthesizedNode(276 /* JsxExpression */);
72046         node.dotDotDotToken = dotDotDotToken;
72047         node.expression = expression;
72048         return node;
72049     }
72050     ts.createJsxExpression = createJsxExpression;
72051     function updateJsxExpression(node, expression) {
72052         return node.expression !== expression
72053             ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
72054             : node;
72055     }
72056     ts.updateJsxExpression = updateJsxExpression;
72057     // Clauses
72058     function createCaseClause(expression, statements) {
72059         var node = createSynthesizedNode(277 /* CaseClause */);
72060         node.expression = ts.parenthesizeExpressionForList(expression);
72061         node.statements = createNodeArray(statements);
72062         return node;
72063     }
72064     ts.createCaseClause = createCaseClause;
72065     function updateCaseClause(node, expression, statements) {
72066         return node.expression !== expression
72067             || node.statements !== statements
72068             ? updateNode(createCaseClause(expression, statements), node)
72069             : node;
72070     }
72071     ts.updateCaseClause = updateCaseClause;
72072     function createDefaultClause(statements) {
72073         var node = createSynthesizedNode(278 /* DefaultClause */);
72074         node.statements = createNodeArray(statements);
72075         return node;
72076     }
72077     ts.createDefaultClause = createDefaultClause;
72078     function updateDefaultClause(node, statements) {
72079         return node.statements !== statements
72080             ? updateNode(createDefaultClause(statements), node)
72081             : node;
72082     }
72083     ts.updateDefaultClause = updateDefaultClause;
72084     function createHeritageClause(token, types) {
72085         var node = createSynthesizedNode(279 /* HeritageClause */);
72086         node.token = token;
72087         node.types = createNodeArray(types);
72088         return node;
72089     }
72090     ts.createHeritageClause = createHeritageClause;
72091     function updateHeritageClause(node, types) {
72092         return node.types !== types
72093             ? updateNode(createHeritageClause(node.token, types), node)
72094             : node;
72095     }
72096     ts.updateHeritageClause = updateHeritageClause;
72097     function createCatchClause(variableDeclaration, block) {
72098         var node = createSynthesizedNode(280 /* CatchClause */);
72099         node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
72100         node.block = block;
72101         return node;
72102     }
72103     ts.createCatchClause = createCatchClause;
72104     function updateCatchClause(node, variableDeclaration, block) {
72105         return node.variableDeclaration !== variableDeclaration
72106             || node.block !== block
72107             ? updateNode(createCatchClause(variableDeclaration, block), node)
72108             : node;
72109     }
72110     ts.updateCatchClause = updateCatchClause;
72111     // Property assignments
72112     function createPropertyAssignment(name, initializer) {
72113         var node = createSynthesizedNode(281 /* PropertyAssignment */);
72114         node.name = asName(name);
72115         node.questionToken = undefined;
72116         node.initializer = ts.parenthesizeExpressionForList(initializer);
72117         return node;
72118     }
72119     ts.createPropertyAssignment = createPropertyAssignment;
72120     function updatePropertyAssignment(node, name, initializer) {
72121         return node.name !== name
72122             || node.initializer !== initializer
72123             ? updateNode(createPropertyAssignment(name, initializer), node)
72124             : node;
72125     }
72126     ts.updatePropertyAssignment = updatePropertyAssignment;
72127     function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
72128         var node = createSynthesizedNode(282 /* ShorthandPropertyAssignment */);
72129         node.name = asName(name);
72130         node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
72131         return node;
72132     }
72133     ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
72134     function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
72135         return node.name !== name
72136             || node.objectAssignmentInitializer !== objectAssignmentInitializer
72137             ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
72138             : node;
72139     }
72140     ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
72141     function createSpreadAssignment(expression) {
72142         var node = createSynthesizedNode(283 /* SpreadAssignment */);
72143         node.expression = ts.parenthesizeExpressionForList(expression);
72144         return node;
72145     }
72146     ts.createSpreadAssignment = createSpreadAssignment;
72147     function updateSpreadAssignment(node, expression) {
72148         return node.expression !== expression
72149             ? updateNode(createSpreadAssignment(expression), node)
72150             : node;
72151     }
72152     ts.updateSpreadAssignment = updateSpreadAssignment;
72153     // Enum
72154     function createEnumMember(name, initializer) {
72155         var node = createSynthesizedNode(284 /* EnumMember */);
72156         node.name = asName(name);
72157         node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
72158         return node;
72159     }
72160     ts.createEnumMember = createEnumMember;
72161     function updateEnumMember(node, name, initializer) {
72162         return node.name !== name
72163             || node.initializer !== initializer
72164             ? updateNode(createEnumMember(name, initializer), node)
72165             : node;
72166     }
72167     ts.updateEnumMember = updateEnumMember;
72168     // Top-level nodes
72169     function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
72170         if (node.statements !== statements ||
72171             (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
72172             (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
72173             (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
72174             (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
72175             (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
72176             var updated = createSynthesizedNode(290 /* SourceFile */);
72177             updated.flags |= node.flags;
72178             updated.statements = createNodeArray(statements);
72179             updated.endOfFileToken = node.endOfFileToken;
72180             updated.fileName = node.fileName;
72181             updated.path = node.path;
72182             updated.text = node.text;
72183             updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
72184             updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
72185             updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
72186             updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
72187             updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
72188             if (node.amdDependencies !== undefined)
72189                 updated.amdDependencies = node.amdDependencies;
72190             if (node.moduleName !== undefined)
72191                 updated.moduleName = node.moduleName;
72192             if (node.languageVariant !== undefined)
72193                 updated.languageVariant = node.languageVariant;
72194             if (node.renamedDependencies !== undefined)
72195                 updated.renamedDependencies = node.renamedDependencies;
72196             if (node.languageVersion !== undefined)
72197                 updated.languageVersion = node.languageVersion;
72198             if (node.scriptKind !== undefined)
72199                 updated.scriptKind = node.scriptKind;
72200             if (node.externalModuleIndicator !== undefined)
72201                 updated.externalModuleIndicator = node.externalModuleIndicator;
72202             if (node.commonJsModuleIndicator !== undefined)
72203                 updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
72204             if (node.identifiers !== undefined)
72205                 updated.identifiers = node.identifiers;
72206             if (node.nodeCount !== undefined)
72207                 updated.nodeCount = node.nodeCount;
72208             if (node.identifierCount !== undefined)
72209                 updated.identifierCount = node.identifierCount;
72210             if (node.symbolCount !== undefined)
72211                 updated.symbolCount = node.symbolCount;
72212             if (node.parseDiagnostics !== undefined)
72213                 updated.parseDiagnostics = node.parseDiagnostics;
72214             if (node.bindDiagnostics !== undefined)
72215                 updated.bindDiagnostics = node.bindDiagnostics;
72216             if (node.bindSuggestionDiagnostics !== undefined)
72217                 updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
72218             if (node.lineMap !== undefined)
72219                 updated.lineMap = node.lineMap;
72220             if (node.classifiableNames !== undefined)
72221                 updated.classifiableNames = node.classifiableNames;
72222             if (node.resolvedModules !== undefined)
72223                 updated.resolvedModules = node.resolvedModules;
72224             if (node.resolvedTypeReferenceDirectiveNames !== undefined)
72225                 updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
72226             if (node.imports !== undefined)
72227                 updated.imports = node.imports;
72228             if (node.moduleAugmentations !== undefined)
72229                 updated.moduleAugmentations = node.moduleAugmentations;
72230             if (node.pragmas !== undefined)
72231                 updated.pragmas = node.pragmas;
72232             if (node.localJsxFactory !== undefined)
72233                 updated.localJsxFactory = node.localJsxFactory;
72234             if (node.localJsxNamespace !== undefined)
72235                 updated.localJsxNamespace = node.localJsxNamespace;
72236             return updateNode(updated, node);
72237         }
72238         return node;
72239     }
72240     ts.updateSourceFileNode = updateSourceFileNode;
72241     /**
72242      * Creates a shallow, memberwise clone of a node for mutation.
72243      */
72244     function getMutableClone(node) {
72245         var clone = getSynthesizedClone(node);
72246         clone.pos = node.pos;
72247         clone.end = node.end;
72248         clone.parent = node.parent;
72249         return clone;
72250     }
72251     ts.getMutableClone = getMutableClone;
72252     // Transformation nodes
72253     /**
72254      * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
72255      * order to preserve comments.
72256      *
72257      * @param original The original statement.
72258      */
72259     function createNotEmittedStatement(original) {
72260         var node = createSynthesizedNode(325 /* NotEmittedStatement */);
72261         node.original = original;
72262         setTextRange(node, original);
72263         return node;
72264     }
72265     ts.createNotEmittedStatement = createNotEmittedStatement;
72266     /**
72267      * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
72268      * order to properly emit exports.
72269      */
72270     /* @internal */
72271     function createEndOfDeclarationMarker(original) {
72272         var node = createSynthesizedNode(329 /* EndOfDeclarationMarker */);
72273         node.emitNode = {};
72274         node.original = original;
72275         return node;
72276     }
72277     ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
72278     /**
72279      * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
72280      * order to properly emit exports.
72281      */
72282     /* @internal */
72283     function createMergeDeclarationMarker(original) {
72284         var node = createSynthesizedNode(328 /* MergeDeclarationMarker */);
72285         node.emitNode = {};
72286         node.original = original;
72287         return node;
72288     }
72289     ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
72290     /**
72291      * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
72292      * order to preserve comments or sourcemap positions.
72293      *
72294      * @param expression The inner expression to emit.
72295      * @param original The original outer expression.
72296      * @param location The location for the expression. Defaults to the positions from "original" if provided.
72297      */
72298     function createPartiallyEmittedExpression(expression, original) {
72299         var node = createSynthesizedNode(326 /* PartiallyEmittedExpression */);
72300         node.expression = expression;
72301         node.original = original;
72302         setTextRange(node, original);
72303         return node;
72304     }
72305     ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
72306     function updatePartiallyEmittedExpression(node, expression) {
72307         if (node.expression !== expression) {
72308             return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
72309         }
72310         return node;
72311     }
72312     ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
72313     function flattenCommaElements(node) {
72314         if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
72315             if (node.kind === 327 /* CommaListExpression */) {
72316                 return node.elements;
72317             }
72318             if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
72319                 return [node.left, node.right];
72320             }
72321         }
72322         return node;
72323     }
72324     function createCommaList(elements) {
72325         var node = createSynthesizedNode(327 /* CommaListExpression */);
72326         node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
72327         return node;
72328     }
72329     ts.createCommaList = createCommaList;
72330     function updateCommaList(node, elements) {
72331         return node.elements !== elements
72332             ? updateNode(createCommaList(elements), node)
72333             : node;
72334     }
72335     ts.updateCommaList = updateCommaList;
72336     /* @internal */
72337     function createSyntheticReferenceExpression(expression, thisArg) {
72338         var node = createSynthesizedNode(330 /* SyntheticReferenceExpression */);
72339         node.expression = expression;
72340         node.thisArg = thisArg;
72341         return node;
72342     }
72343     ts.createSyntheticReferenceExpression = createSyntheticReferenceExpression;
72344     /* @internal */
72345     function updateSyntheticReferenceExpression(node, expression, thisArg) {
72346         return node.expression !== expression
72347             || node.thisArg !== thisArg
72348             ? updateNode(createSyntheticReferenceExpression(expression, thisArg), node)
72349             : node;
72350     }
72351     ts.updateSyntheticReferenceExpression = updateSyntheticReferenceExpression;
72352     function createBundle(sourceFiles, prepends) {
72353         if (prepends === void 0) { prepends = ts.emptyArray; }
72354         var node = ts.createNode(291 /* Bundle */);
72355         node.prepends = prepends;
72356         node.sourceFiles = sourceFiles;
72357         return node;
72358     }
72359     ts.createBundle = createBundle;
72360     var allUnscopedEmitHelpers;
72361     function getAllUnscopedEmitHelpers() {
72362         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
72363             ts.valuesHelper,
72364             ts.readHelper,
72365             ts.spreadHelper,
72366             ts.spreadArraysHelper,
72367             ts.restHelper,
72368             ts.decorateHelper,
72369             ts.metadataHelper,
72370             ts.paramHelper,
72371             ts.awaiterHelper,
72372             ts.assignHelper,
72373             ts.awaitHelper,
72374             ts.asyncGeneratorHelper,
72375             ts.asyncDelegator,
72376             ts.asyncValues,
72377             ts.extendsHelper,
72378             ts.templateObjectHelper,
72379             ts.generatorHelper,
72380             ts.importStarHelper,
72381             ts.importDefaultHelper,
72382             ts.classPrivateFieldGetHelper,
72383             ts.classPrivateFieldSetHelper,
72384             ts.createBindingHelper,
72385             ts.setModuleDefaultHelper
72386         ], function (helper) { return helper.name; }));
72387     }
72388     function createUnparsedSource() {
72389         var node = ts.createNode(292 /* UnparsedSource */);
72390         node.prologues = ts.emptyArray;
72391         node.referencedFiles = ts.emptyArray;
72392         node.libReferenceDirectives = ts.emptyArray;
72393         node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
72394         return node;
72395     }
72396     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
72397         var node = createUnparsedSource();
72398         var stripInternal;
72399         var bundleFileInfo;
72400         if (!ts.isString(textOrInputFiles)) {
72401             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
72402             node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
72403             node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
72404             Object.defineProperties(node, {
72405                 text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
72406                 sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
72407             });
72408             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
72409                 node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
72410                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
72411                 stripInternal = mapTextOrStripInternal;
72412                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
72413                 if (node.oldFileOfCurrentEmit) {
72414                     parseOldFileOfCurrentEmit(node, ts.Debug.checkDefined(bundleFileInfo));
72415                     return node;
72416                 }
72417             }
72418         }
72419         else {
72420             node.fileName = "";
72421             node.text = textOrInputFiles;
72422             node.sourceMapPath = mapPathOrType;
72423             node.sourceMapText = mapTextOrStripInternal;
72424         }
72425         ts.Debug.assert(!node.oldFileOfCurrentEmit);
72426         parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
72427         return node;
72428     }
72429     ts.createUnparsedSourceFile = createUnparsedSourceFile;
72430     function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
72431         var prologues;
72432         var helpers;
72433         var referencedFiles;
72434         var typeReferenceDirectives;
72435         var libReferenceDirectives;
72436         var texts;
72437         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
72438             var section = _a[_i];
72439             switch (section.kind) {
72440                 case "prologue" /* Prologue */:
72441                     (prologues || (prologues = [])).push(createUnparsedNode(section, node));
72442                     break;
72443                 case "emitHelpers" /* EmitHelpers */:
72444                     (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
72445                     break;
72446                 case "no-default-lib" /* NoDefaultLib */:
72447                     node.hasNoDefaultLib = true;
72448                     break;
72449                 case "reference" /* Reference */:
72450                     (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
72451                     break;
72452                 case "type" /* Type */:
72453                     (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
72454                     break;
72455                 case "lib" /* Lib */:
72456                     (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
72457                     break;
72458                 case "prepend" /* Prepend */:
72459                     var prependNode = createUnparsedNode(section, node);
72460                     var prependTexts = void 0;
72461                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
72462                         var text = _c[_b];
72463                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
72464                             (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
72465                         }
72466                     }
72467                     prependNode.texts = prependTexts || ts.emptyArray;
72468                     (texts || (texts = [])).push(prependNode);
72469                     break;
72470                 case "internal" /* Internal */:
72471                     if (stripInternal) {
72472                         if (!texts)
72473                             texts = [];
72474                         break;
72475                     }
72476                 // falls through
72477                 case "text" /* Text */:
72478                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72479                     break;
72480                 default:
72481                     ts.Debug.assertNever(section);
72482             }
72483         }
72484         node.prologues = prologues || ts.emptyArray;
72485         node.helpers = helpers;
72486         node.referencedFiles = referencedFiles || ts.emptyArray;
72487         node.typeReferenceDirectives = typeReferenceDirectives;
72488         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
72489         node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
72490     }
72491     function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
72492         ts.Debug.assert(!!node.oldFileOfCurrentEmit);
72493         var texts;
72494         var syntheticReferences;
72495         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
72496             var section = _a[_i];
72497             switch (section.kind) {
72498                 case "internal" /* Internal */:
72499                 case "text" /* Text */:
72500                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72501                     break;
72502                 case "no-default-lib" /* NoDefaultLib */:
72503                 case "reference" /* Reference */:
72504                 case "type" /* Type */:
72505                 case "lib" /* Lib */:
72506                     (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
72507                     break;
72508                 // Ignore
72509                 case "prologue" /* Prologue */:
72510                 case "emitHelpers" /* EmitHelpers */:
72511                 case "prepend" /* Prepend */:
72512                     break;
72513                 default:
72514                     ts.Debug.assertNever(section);
72515             }
72516         }
72517         node.texts = texts || ts.emptyArray;
72518         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
72519         node.syntheticReferences = syntheticReferences;
72520         return node;
72521     }
72522     function mapBundleFileSectionKindToSyntaxKind(kind) {
72523         switch (kind) {
72524             case "prologue" /* Prologue */: return 285 /* UnparsedPrologue */;
72525             case "prepend" /* Prepend */: return 286 /* UnparsedPrepend */;
72526             case "internal" /* Internal */: return 288 /* UnparsedInternalText */;
72527             case "text" /* Text */: return 287 /* UnparsedText */;
72528             case "emitHelpers" /* EmitHelpers */:
72529             case "no-default-lib" /* NoDefaultLib */:
72530             case "reference" /* Reference */:
72531             case "type" /* Type */:
72532             case "lib" /* Lib */:
72533                 return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
72534             default:
72535                 return ts.Debug.assertNever(kind);
72536         }
72537     }
72538     function createUnparsedNode(section, parent) {
72539         var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
72540         node.parent = parent;
72541         node.data = section.data;
72542         return node;
72543     }
72544     function createUnparsedSyntheticReference(section, parent) {
72545         var node = ts.createNode(289 /* UnparsedSyntheticReference */, section.pos, section.end);
72546         node.parent = parent;
72547         node.data = section.data;
72548         node.section = section;
72549         return node;
72550     }
72551     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
72552         var node = ts.createNode(293 /* InputFiles */);
72553         if (!ts.isString(javascriptTextOrReadFileText)) {
72554             var cache_1 = ts.createMap();
72555             var textGetter_1 = function (path) {
72556                 if (path === undefined)
72557                     return undefined;
72558                 var value = cache_1.get(path);
72559                 if (value === undefined) {
72560                     value = javascriptTextOrReadFileText(path);
72561                     cache_1.set(path, value !== undefined ? value : false);
72562                 }
72563                 return value !== false ? value : undefined;
72564             };
72565             var definedTextGetter_1 = function (path) {
72566                 var result = textGetter_1(path);
72567                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
72568             };
72569             var buildInfo_1;
72570             var getAndCacheBuildInfo_1 = function (getText) {
72571                 if (buildInfo_1 === undefined) {
72572                     var result = getText();
72573                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
72574                 }
72575                 return buildInfo_1 || undefined;
72576             };
72577             node.javascriptPath = declarationTextOrJavascriptPath;
72578             node.javascriptMapPath = javascriptMapPath;
72579             node.declarationPath = ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath);
72580             node.declarationMapPath = declarationMapPath;
72581             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
72582             Object.defineProperties(node, {
72583                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
72584                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
72585                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
72586                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
72587                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
72588             });
72589         }
72590         else {
72591             node.javascriptText = javascriptTextOrReadFileText;
72592             node.javascriptMapPath = javascriptMapPath;
72593             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
72594             node.declarationText = declarationTextOrJavascriptPath;
72595             node.declarationMapPath = declarationMapPath;
72596             node.declarationMapText = declarationMapTextOrBuildInfoPath;
72597             node.javascriptPath = javascriptPath;
72598             node.declarationPath = declarationPath;
72599             node.buildInfoPath = buildInfoPath;
72600             node.buildInfo = buildInfo;
72601             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
72602         }
72603         return node;
72604     }
72605     ts.createInputFiles = createInputFiles;
72606     function updateBundle(node, sourceFiles, prepends) {
72607         if (prepends === void 0) { prepends = ts.emptyArray; }
72608         if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
72609             return createBundle(sourceFiles, prepends);
72610         }
72611         return node;
72612     }
72613     ts.updateBundle = updateBundle;
72614     function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
72615         return createCall(createFunctionExpression(
72616         /*modifiers*/ undefined, 
72617         /*asteriskToken*/ undefined, 
72618         /*name*/ undefined, 
72619         /*typeParameters*/ undefined, 
72620         /*parameters*/ param ? [param] : [], 
72621         /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72622         /*typeArguments*/ undefined, 
72623         /*argumentsArray*/ paramValue ? [paramValue] : []);
72624     }
72625     ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
72626     function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
72627         return createCall(createArrowFunction(
72628         /*modifiers*/ undefined, 
72629         /*typeParameters*/ undefined, 
72630         /*parameters*/ param ? [param] : [], 
72631         /*type*/ undefined, 
72632         /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72633         /*typeArguments*/ undefined, 
72634         /*argumentsArray*/ paramValue ? [paramValue] : []);
72635     }
72636     ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
72637     function createComma(left, right) {
72638         return createBinary(left, 27 /* CommaToken */, right);
72639     }
72640     ts.createComma = createComma;
72641     function createLessThan(left, right) {
72642         return createBinary(left, 29 /* LessThanToken */, right);
72643     }
72644     ts.createLessThan = createLessThan;
72645     function createAssignment(left, right) {
72646         return createBinary(left, 62 /* EqualsToken */, right);
72647     }
72648     ts.createAssignment = createAssignment;
72649     function createStrictEquality(left, right) {
72650         return createBinary(left, 36 /* EqualsEqualsEqualsToken */, right);
72651     }
72652     ts.createStrictEquality = createStrictEquality;
72653     function createStrictInequality(left, right) {
72654         return createBinary(left, 37 /* ExclamationEqualsEqualsToken */, right);
72655     }
72656     ts.createStrictInequality = createStrictInequality;
72657     function createAdd(left, right) {
72658         return createBinary(left, 39 /* PlusToken */, right);
72659     }
72660     ts.createAdd = createAdd;
72661     function createSubtract(left, right) {
72662         return createBinary(left, 40 /* MinusToken */, right);
72663     }
72664     ts.createSubtract = createSubtract;
72665     function createPostfixIncrement(operand) {
72666         return createPostfix(operand, 45 /* PlusPlusToken */);
72667     }
72668     ts.createPostfixIncrement = createPostfixIncrement;
72669     function createLogicalAnd(left, right) {
72670         return createBinary(left, 55 /* AmpersandAmpersandToken */, right);
72671     }
72672     ts.createLogicalAnd = createLogicalAnd;
72673     function createLogicalOr(left, right) {
72674         return createBinary(left, 56 /* BarBarToken */, right);
72675     }
72676     ts.createLogicalOr = createLogicalOr;
72677     function createNullishCoalesce(left, right) {
72678         return createBinary(left, 60 /* QuestionQuestionToken */, right);
72679     }
72680     ts.createNullishCoalesce = createNullishCoalesce;
72681     function createLogicalNot(operand) {
72682         return createPrefix(53 /* ExclamationToken */, operand);
72683     }
72684     ts.createLogicalNot = createLogicalNot;
72685     function createVoidZero() {
72686         return createVoid(createLiteral(0));
72687     }
72688     ts.createVoidZero = createVoidZero;
72689     function createExportDefault(expression) {
72690         return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
72691     }
72692     ts.createExportDefault = createExportDefault;
72693     function createExternalModuleExport(exportName) {
72694         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
72695     }
72696     ts.createExternalModuleExport = createExternalModuleExport;
72697     // Utilities
72698     function asName(name) {
72699         return ts.isString(name) ? createIdentifier(name) : name;
72700     }
72701     function asExpression(value) {
72702         return typeof value === "string" ? createStringLiteral(value) :
72703             typeof value === "number" ? createNumericLiteral("" + value) :
72704                 typeof value === "boolean" ? value ? createTrue() : createFalse() :
72705                     value;
72706     }
72707     function asNodeArray(array) {
72708         return array ? createNodeArray(array) : undefined;
72709     }
72710     function asToken(value) {
72711         return typeof value === "number" ? createToken(value) : value;
72712     }
72713     function asEmbeddedStatement(statement) {
72714         return statement && ts.isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
72715     }
72716     /**
72717      * Clears any EmitNode entries from parse-tree nodes.
72718      * @param sourceFile A source file.
72719      */
72720     function disposeEmitNodes(sourceFile) {
72721         // During transformation we may need to annotate a parse tree node with transient
72722         // transformation properties. As parse tree nodes live longer than transformation
72723         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
72724         // from these nodes to ensure we do not hold onto entire subtrees just for position
72725         // information. We also need to reset these nodes to a pre-transformation state
72726         // for incremental parsing scenarios so that we do not impact later emit.
72727         sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
72728         var emitNode = sourceFile && sourceFile.emitNode;
72729         var annotatedNodes = emitNode && emitNode.annotatedNodes;
72730         if (annotatedNodes) {
72731             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
72732                 var node = annotatedNodes_1[_i];
72733                 node.emitNode = undefined;
72734             }
72735         }
72736     }
72737     ts.disposeEmitNodes = disposeEmitNodes;
72738     /**
72739      * Associates a node with the current transformation, initializing
72740      * various transient transformation properties.
72741      */
72742     /* @internal */
72743     function getOrCreateEmitNode(node) {
72744         if (!node.emitNode) {
72745             if (ts.isParseTreeNode(node)) {
72746                 // To avoid holding onto transformation artifacts, we keep track of any
72747                 // parse tree node we are annotating. This allows us to clean them up after
72748                 // all transformations have completed.
72749                 if (node.kind === 290 /* SourceFile */) {
72750                     return node.emitNode = { annotatedNodes: [node] };
72751                 }
72752                 var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
72753                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
72754             }
72755             node.emitNode = {};
72756         }
72757         return node.emitNode;
72758     }
72759     ts.getOrCreateEmitNode = getOrCreateEmitNode;
72760     /**
72761      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
72762      * @internal
72763      */
72764     function removeAllComments(node) {
72765         var emitNode = getOrCreateEmitNode(node);
72766         emitNode.flags |= 1536 /* NoComments */;
72767         emitNode.leadingComments = undefined;
72768         emitNode.trailingComments = undefined;
72769         return node;
72770     }
72771     ts.removeAllComments = removeAllComments;
72772     function setTextRange(range, location) {
72773         if (location) {
72774             range.pos = location.pos;
72775             range.end = location.end;
72776         }
72777         return range;
72778     }
72779     ts.setTextRange = setTextRange;
72780     /**
72781      * Sets flags that control emit behavior of a node.
72782      */
72783     function setEmitFlags(node, emitFlags) {
72784         getOrCreateEmitNode(node).flags = emitFlags;
72785         return node;
72786     }
72787     ts.setEmitFlags = setEmitFlags;
72788     /**
72789      * Sets flags that control emit behavior of a node.
72790      */
72791     /* @internal */
72792     function addEmitFlags(node, emitFlags) {
72793         var emitNode = getOrCreateEmitNode(node);
72794         emitNode.flags = emitNode.flags | emitFlags;
72795         return node;
72796     }
72797     ts.addEmitFlags = addEmitFlags;
72798     /**
72799      * Gets a custom text range to use when emitting source maps.
72800      */
72801     function getSourceMapRange(node) {
72802         var emitNode = node.emitNode;
72803         return (emitNode && emitNode.sourceMapRange) || node;
72804     }
72805     ts.getSourceMapRange = getSourceMapRange;
72806     /**
72807      * Sets a custom text range to use when emitting source maps.
72808      */
72809     function setSourceMapRange(node, range) {
72810         getOrCreateEmitNode(node).sourceMapRange = range;
72811         return node;
72812     }
72813     ts.setSourceMapRange = setSourceMapRange;
72814     var SourceMapSource;
72815     /**
72816      * Create an external source map source file reference
72817      */
72818     function createSourceMapSource(fileName, text, skipTrivia) {
72819         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
72820     }
72821     ts.createSourceMapSource = createSourceMapSource;
72822     /**
72823      * Gets the TextRange to use for source maps for a token of a node.
72824      */
72825     function getTokenSourceMapRange(node, token) {
72826         var emitNode = node.emitNode;
72827         var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
72828         return tokenSourceMapRanges && tokenSourceMapRanges[token];
72829     }
72830     ts.getTokenSourceMapRange = getTokenSourceMapRange;
72831     /**
72832      * Sets the TextRange to use for source maps for a token of a node.
72833      */
72834     function setTokenSourceMapRange(node, token, range) {
72835         var emitNode = getOrCreateEmitNode(node);
72836         var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
72837         tokenSourceMapRanges[token] = range;
72838         return node;
72839     }
72840     ts.setTokenSourceMapRange = setTokenSourceMapRange;
72841     /**
72842      * Gets a custom text range to use when emitting comments.
72843      */
72844     /*@internal*/
72845     function getStartsOnNewLine(node) {
72846         var emitNode = node.emitNode;
72847         return emitNode && emitNode.startsOnNewLine;
72848     }
72849     ts.getStartsOnNewLine = getStartsOnNewLine;
72850     /**
72851      * Sets a custom text range to use when emitting comments.
72852      */
72853     /*@internal*/
72854     function setStartsOnNewLine(node, newLine) {
72855         getOrCreateEmitNode(node).startsOnNewLine = newLine;
72856         return node;
72857     }
72858     ts.setStartsOnNewLine = setStartsOnNewLine;
72859     /**
72860      * Gets a custom text range to use when emitting comments.
72861      */
72862     function getCommentRange(node) {
72863         var emitNode = node.emitNode;
72864         return (emitNode && emitNode.commentRange) || node;
72865     }
72866     ts.getCommentRange = getCommentRange;
72867     /**
72868      * Sets a custom text range to use when emitting comments.
72869      */
72870     function setCommentRange(node, range) {
72871         getOrCreateEmitNode(node).commentRange = range;
72872         return node;
72873     }
72874     ts.setCommentRange = setCommentRange;
72875     function getSyntheticLeadingComments(node) {
72876         var emitNode = node.emitNode;
72877         return emitNode && emitNode.leadingComments;
72878     }
72879     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
72880     function setSyntheticLeadingComments(node, comments) {
72881         getOrCreateEmitNode(node).leadingComments = comments;
72882         return node;
72883     }
72884     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
72885     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
72886         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72887     }
72888     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
72889     function getSyntheticTrailingComments(node) {
72890         var emitNode = node.emitNode;
72891         return emitNode && emitNode.trailingComments;
72892     }
72893     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
72894     function setSyntheticTrailingComments(node, comments) {
72895         getOrCreateEmitNode(node).trailingComments = comments;
72896         return node;
72897     }
72898     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
72899     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
72900         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72901     }
72902     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
72903     function moveSyntheticComments(node, original) {
72904         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
72905         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
72906         var emit = getOrCreateEmitNode(original);
72907         emit.leadingComments = undefined;
72908         emit.trailingComments = undefined;
72909         return node;
72910     }
72911     ts.moveSyntheticComments = moveSyntheticComments;
72912     /** @internal */
72913     function ignoreSourceNewlines(node) {
72914         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
72915         return node;
72916     }
72917     ts.ignoreSourceNewlines = ignoreSourceNewlines;
72918     /**
72919      * Gets the constant value to emit for an expression.
72920      */
72921     function getConstantValue(node) {
72922         var emitNode = node.emitNode;
72923         return emitNode && emitNode.constantValue;
72924     }
72925     ts.getConstantValue = getConstantValue;
72926     /**
72927      * Sets the constant value to emit for an expression.
72928      */
72929     function setConstantValue(node, value) {
72930         var emitNode = getOrCreateEmitNode(node);
72931         emitNode.constantValue = value;
72932         return node;
72933     }
72934     ts.setConstantValue = setConstantValue;
72935     /**
72936      * Adds an EmitHelper to a node.
72937      */
72938     function addEmitHelper(node, helper) {
72939         var emitNode = getOrCreateEmitNode(node);
72940         emitNode.helpers = ts.append(emitNode.helpers, helper);
72941         return node;
72942     }
72943     ts.addEmitHelper = addEmitHelper;
72944     /**
72945      * Add EmitHelpers to a node.
72946      */
72947     function addEmitHelpers(node, helpers) {
72948         if (ts.some(helpers)) {
72949             var emitNode = getOrCreateEmitNode(node);
72950             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
72951                 var helper = helpers_1[_i];
72952                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
72953             }
72954         }
72955         return node;
72956     }
72957     ts.addEmitHelpers = addEmitHelpers;
72958     /**
72959      * Removes an EmitHelper from a node.
72960      */
72961     function removeEmitHelper(node, helper) {
72962         var emitNode = node.emitNode;
72963         if (emitNode) {
72964             var helpers = emitNode.helpers;
72965             if (helpers) {
72966                 return ts.orderedRemoveItem(helpers, helper);
72967             }
72968         }
72969         return false;
72970     }
72971     ts.removeEmitHelper = removeEmitHelper;
72972     /**
72973      * Gets the EmitHelpers of a node.
72974      */
72975     function getEmitHelpers(node) {
72976         var emitNode = node.emitNode;
72977         return emitNode && emitNode.helpers;
72978     }
72979     ts.getEmitHelpers = getEmitHelpers;
72980     /**
72981      * Moves matching emit helpers from a source node to a target node.
72982      */
72983     function moveEmitHelpers(source, target, predicate) {
72984         var sourceEmitNode = source.emitNode;
72985         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
72986         if (!ts.some(sourceEmitHelpers))
72987             return;
72988         var targetEmitNode = getOrCreateEmitNode(target);
72989         var helpersRemoved = 0;
72990         for (var i = 0; i < sourceEmitHelpers.length; i++) {
72991             var helper = sourceEmitHelpers[i];
72992             if (predicate(helper)) {
72993                 helpersRemoved++;
72994                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
72995             }
72996             else if (helpersRemoved > 0) {
72997                 sourceEmitHelpers[i - helpersRemoved] = helper;
72998             }
72999         }
73000         if (helpersRemoved > 0) {
73001             sourceEmitHelpers.length -= helpersRemoved;
73002         }
73003     }
73004     ts.moveEmitHelpers = moveEmitHelpers;
73005     /* @internal */
73006     function compareEmitHelpers(x, y) {
73007         if (x === y)
73008             return 0 /* EqualTo */;
73009         if (x.priority === y.priority)
73010             return 0 /* EqualTo */;
73011         if (x.priority === undefined)
73012             return 1 /* GreaterThan */;
73013         if (y.priority === undefined)
73014             return -1 /* LessThan */;
73015         return ts.compareValues(x.priority, y.priority);
73016     }
73017     ts.compareEmitHelpers = compareEmitHelpers;
73018     function setOriginalNode(node, original) {
73019         node.original = original;
73020         if (original) {
73021             var emitNode = original.emitNode;
73022             if (emitNode)
73023                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
73024         }
73025         return node;
73026     }
73027     ts.setOriginalNode = setOriginalNode;
73028     function mergeEmitNode(sourceEmitNode, destEmitNode) {
73029         var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine;
73030         if (!destEmitNode)
73031             destEmitNode = {};
73032         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
73033         if (leadingComments)
73034             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
73035         if (trailingComments)
73036             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
73037         if (flags)
73038             destEmitNode.flags = flags;
73039         if (commentRange)
73040             destEmitNode.commentRange = commentRange;
73041         if (sourceMapRange)
73042             destEmitNode.sourceMapRange = sourceMapRange;
73043         if (tokenSourceMapRanges)
73044             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
73045         if (constantValue !== undefined)
73046             destEmitNode.constantValue = constantValue;
73047         if (helpers)
73048             destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
73049         if (startsOnNewLine !== undefined)
73050             destEmitNode.startsOnNewLine = startsOnNewLine;
73051         return destEmitNode;
73052     }
73053     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
73054         if (!destRanges)
73055             destRanges = [];
73056         for (var key in sourceRanges) {
73057             destRanges[key] = sourceRanges[key];
73058         }
73059         return destRanges;
73060     }
73061 })(ts || (ts = {}));
73062 /* @internal */
73063 var ts;
73064 (function (ts) {
73065     ts.nullTransformationContext = {
73066         enableEmitNotification: ts.noop,
73067         enableSubstitution: ts.noop,
73068         endLexicalEnvironment: ts.returnUndefined,
73069         getCompilerOptions: function () { return ({}); },
73070         getEmitHost: ts.notImplemented,
73071         getEmitResolver: ts.notImplemented,
73072         setLexicalEnvironmentFlags: ts.noop,
73073         getLexicalEnvironmentFlags: function () { return 0; },
73074         hoistFunctionDeclaration: ts.noop,
73075         hoistVariableDeclaration: ts.noop,
73076         addInitializationStatement: ts.noop,
73077         isEmitNotificationEnabled: ts.notImplemented,
73078         isSubstitutionEnabled: ts.notImplemented,
73079         onEmitNode: ts.noop,
73080         onSubstituteNode: ts.notImplemented,
73081         readEmitHelpers: ts.notImplemented,
73082         requestEmitHelper: ts.noop,
73083         resumeLexicalEnvironment: ts.noop,
73084         startLexicalEnvironment: ts.noop,
73085         suspendLexicalEnvironment: ts.noop,
73086         addDiagnostic: ts.noop,
73087     };
73088     function createTypeCheck(value, tag) {
73089         return tag === "undefined"
73090             ? ts.createStrictEquality(value, ts.createVoidZero())
73091             : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
73092     }
73093     ts.createTypeCheck = createTypeCheck;
73094     function createMemberAccessForPropertyName(target, memberName, location) {
73095         if (ts.isComputedPropertyName(memberName)) {
73096             return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
73097         }
73098         else {
73099             var expression = ts.setTextRange((ts.isIdentifier(memberName) || ts.isPrivateIdentifier(memberName))
73100                 ? ts.createPropertyAccess(target, memberName)
73101                 : ts.createElementAccess(target, memberName), memberName);
73102             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
73103             return expression;
73104         }
73105     }
73106     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
73107     function createFunctionCall(func, thisArg, argumentsList, location) {
73108         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), 
73109         /*typeArguments*/ undefined, __spreadArrays([
73110             thisArg
73111         ], argumentsList)), location);
73112     }
73113     ts.createFunctionCall = createFunctionCall;
73114     function createFunctionApply(func, thisArg, argumentsExpression, location) {
73115         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), 
73116         /*typeArguments*/ undefined, [
73117             thisArg,
73118             argumentsExpression
73119         ]), location);
73120     }
73121     ts.createFunctionApply = createFunctionApply;
73122     function createArraySlice(array, start) {
73123         var argumentsList = [];
73124         if (start !== undefined) {
73125             argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
73126         }
73127         return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
73128     }
73129     ts.createArraySlice = createArraySlice;
73130     function createArrayConcat(array, values) {
73131         return ts.createCall(ts.createPropertyAccess(array, "concat"), 
73132         /*typeArguments*/ undefined, values);
73133     }
73134     ts.createArrayConcat = createArrayConcat;
73135     function createMathPow(left, right, location) {
73136         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), 
73137         /*typeArguments*/ undefined, [left, right]), location);
73138     }
73139     ts.createMathPow = createMathPow;
73140     function createReactNamespace(reactNamespace, parent) {
73141         // To ensure the emit resolver can properly resolve the namespace, we need to
73142         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
73143         // flag and setting a parent node.
73144         var react = ts.createIdentifier(reactNamespace || "React");
73145         react.flags &= ~8 /* Synthesized */;
73146         // Set the parent that is in parse tree
73147         // this makes sure that parent chain is intact for checker to traverse complete scope tree
73148         react.parent = ts.getParseTreeNode(parent);
73149         return react;
73150     }
73151     function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
73152         if (ts.isQualifiedName(jsxFactory)) {
73153             var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
73154             var right = ts.createIdentifier(ts.idText(jsxFactory.right));
73155             right.escapedText = jsxFactory.right.escapedText;
73156             return ts.createPropertyAccess(left, right);
73157         }
73158         else {
73159             return createReactNamespace(ts.idText(jsxFactory), parent);
73160         }
73161     }
73162     function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
73163         return jsxFactoryEntity ?
73164             createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
73165             ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
73166     }
73167     function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
73168         var argumentsList = [tagName];
73169         if (props) {
73170             argumentsList.push(props);
73171         }
73172         if (children && children.length > 0) {
73173             if (!props) {
73174                 argumentsList.push(ts.createNull());
73175             }
73176             if (children.length > 1) {
73177                 for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
73178                     var child = children_2[_i];
73179                     startOnNewLine(child);
73180                     argumentsList.push(child);
73181                 }
73182             }
73183             else {
73184                 argumentsList.push(children[0]);
73185             }
73186         }
73187         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73188         /*typeArguments*/ undefined, argumentsList), location);
73189     }
73190     ts.createExpressionForJsxElement = createExpressionForJsxElement;
73191     function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
73192         var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
73193         var argumentsList = [tagName];
73194         argumentsList.push(ts.createNull());
73195         if (children && children.length > 0) {
73196             if (children.length > 1) {
73197                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
73198                     var child = children_3[_i];
73199                     startOnNewLine(child);
73200                     argumentsList.push(child);
73201                 }
73202             }
73203             else {
73204                 argumentsList.push(children[0]);
73205             }
73206         }
73207         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73208         /*typeArguments*/ undefined, argumentsList), location);
73209     }
73210     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
73211     // Helpers
73212     /**
73213      * Gets an identifier for the name of an *unscoped* emit helper.
73214      */
73215     function getUnscopedHelperName(name) {
73216         return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
73217     }
73218     ts.getUnscopedHelperName = getUnscopedHelperName;
73219     ts.valuesHelper = {
73220         name: "typescript:values",
73221         importName: "__values",
73222         scoped: false,
73223         text: "\n            var __values = (this && this.__values) || function(o) {\n                var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n                if (m) return m.call(o);\n                if (o && typeof o.length === \"number\") return {\n                    next: function () {\n                        if (o && i >= o.length) o = void 0;\n                        return { value: o && o[i++], done: !o };\n                    }\n                };\n                throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n            };"
73224     };
73225     function createValuesHelper(context, expression, location) {
73226         context.requestEmitHelper(ts.valuesHelper);
73227         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__values"), 
73228         /*typeArguments*/ undefined, [expression]), location);
73229     }
73230     ts.createValuesHelper = createValuesHelper;
73231     ts.readHelper = {
73232         name: "typescript:read",
73233         importName: "__read",
73234         scoped: false,
73235         text: "\n            var __read = (this && this.__read) || function (o, n) {\n                var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n                if (!m) return o;\n                var i = m.call(o), r, ar = [], e;\n                try {\n                    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n                }\n                catch (error) { e = { error: error }; }\n                finally {\n                    try {\n                        if (r && !r.done && (m = i[\"return\"])) m.call(i);\n                    }\n                    finally { if (e) throw e.error; }\n                }\n                return ar;\n            };"
73236     };
73237     function createReadHelper(context, iteratorRecord, count, location) {
73238         context.requestEmitHelper(ts.readHelper);
73239         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__read"), 
73240         /*typeArguments*/ undefined, count !== undefined
73241             ? [iteratorRecord, ts.createLiteral(count)]
73242             : [iteratorRecord]), location);
73243     }
73244     ts.createReadHelper = createReadHelper;
73245     ts.spreadHelper = {
73246         name: "typescript:spread",
73247         importName: "__spread",
73248         scoped: false,
73249         dependencies: [ts.readHelper],
73250         text: "\n            var __spread = (this && this.__spread) || function () {\n                for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n                return ar;\n            };"
73251     };
73252     function createSpreadHelper(context, argumentList, location) {
73253         context.requestEmitHelper(ts.spreadHelper);
73254         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spread"), 
73255         /*typeArguments*/ undefined, argumentList), location);
73256     }
73257     ts.createSpreadHelper = createSpreadHelper;
73258     ts.spreadArraysHelper = {
73259         name: "typescript:spreadArrays",
73260         importName: "__spreadArrays",
73261         scoped: false,
73262         text: "\n            var __spreadArrays = (this && this.__spreadArrays) || function () {\n                for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n                for (var r = Array(s), k = 0, i = 0; i < il; i++)\n                    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n                        r[k] = a[j];\n                return r;\n            };"
73263     };
73264     function createSpreadArraysHelper(context, argumentList, location) {
73265         context.requestEmitHelper(ts.spreadArraysHelper);
73266         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spreadArrays"), 
73267         /*typeArguments*/ undefined, argumentList), location);
73268     }
73269     ts.createSpreadArraysHelper = createSpreadArraysHelper;
73270     // Utilities
73271     function createForOfBindingStatement(node, boundValue) {
73272         if (ts.isVariableDeclarationList(node)) {
73273             var firstDeclaration = ts.first(node.declarations);
73274             var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
73275             /*typeNode*/ undefined, boundValue);
73276             return ts.setTextRange(ts.createVariableStatement(
73277             /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), 
73278             /*location*/ node);
73279         }
73280         else {
73281             var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
73282             return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
73283         }
73284     }
73285     ts.createForOfBindingStatement = createForOfBindingStatement;
73286     function insertLeadingStatement(dest, source) {
73287         if (ts.isBlock(dest)) {
73288             return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
73289         }
73290         else {
73291             return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
73292         }
73293     }
73294     ts.insertLeadingStatement = insertLeadingStatement;
73295     function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
73296         if (!outermostLabeledStatement) {
73297             return node;
73298         }
73299         var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 238 /* LabeledStatement */
73300             ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
73301             : node);
73302         if (afterRestoreLabelCallback) {
73303             afterRestoreLabelCallback(outermostLabeledStatement);
73304         }
73305         return updated;
73306     }
73307     ts.restoreEnclosingLabel = restoreEnclosingLabel;
73308     function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
73309         var target = ts.skipParentheses(node);
73310         switch (target.kind) {
73311             case 75 /* Identifier */:
73312                 return cacheIdentifiers;
73313             case 104 /* ThisKeyword */:
73314             case 8 /* NumericLiteral */:
73315             case 9 /* BigIntLiteral */:
73316             case 10 /* StringLiteral */:
73317                 return false;
73318             case 192 /* ArrayLiteralExpression */:
73319                 var elements = target.elements;
73320                 if (elements.length === 0) {
73321                     return false;
73322                 }
73323                 return true;
73324             case 193 /* ObjectLiteralExpression */:
73325                 return target.properties.length > 0;
73326             default:
73327                 return true;
73328         }
73329     }
73330     function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
73331         if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
73332         var callee = skipOuterExpressions(expression, 15 /* All */);
73333         var thisArg;
73334         var target;
73335         if (ts.isSuperProperty(callee)) {
73336             thisArg = ts.createThis();
73337             target = callee;
73338         }
73339         else if (callee.kind === 102 /* SuperKeyword */) {
73340             thisArg = ts.createThis();
73341             target = languageVersion < 2 /* ES2015 */
73342                 ? ts.setTextRange(ts.createIdentifier("_super"), callee)
73343                 : callee;
73344         }
73345         else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
73346             thisArg = ts.createVoidZero();
73347             target = parenthesizeForAccess(callee);
73348         }
73349         else {
73350             switch (callee.kind) {
73351                 case 194 /* PropertyAccessExpression */: {
73352                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73353                         // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
73354                         thisArg = ts.createTempVariable(recordTempVariable);
73355                         target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
73356                         ts.setTextRange(target, callee);
73357                     }
73358                     else {
73359                         thisArg = callee.expression;
73360                         target = callee;
73361                     }
73362                     break;
73363                 }
73364                 case 195 /* ElementAccessExpression */: {
73365                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73366                         // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
73367                         thisArg = ts.createTempVariable(recordTempVariable);
73368                         target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
73369                         ts.setTextRange(target, callee);
73370                     }
73371                     else {
73372                         thisArg = callee.expression;
73373                         target = callee;
73374                     }
73375                     break;
73376                 }
73377                 default: {
73378                     // for `a()` target is `a` and thisArg is `void 0`
73379                     thisArg = ts.createVoidZero();
73380                     target = parenthesizeForAccess(expression);
73381                     break;
73382                 }
73383             }
73384         }
73385         return { target: target, thisArg: thisArg };
73386     }
73387     ts.createCallBinding = createCallBinding;
73388     function inlineExpressions(expressions) {
73389         // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
73390         // stack size exceeded" errors.
73391         return expressions.length > 10
73392             ? ts.createCommaList(expressions)
73393             : ts.reduceLeft(expressions, ts.createComma);
73394     }
73395     ts.inlineExpressions = inlineExpressions;
73396     function createExpressionFromEntityName(node) {
73397         if (ts.isQualifiedName(node)) {
73398             var left = createExpressionFromEntityName(node.left);
73399             var right = ts.getMutableClone(node.right);
73400             return ts.setTextRange(ts.createPropertyAccess(left, right), node);
73401         }
73402         else {
73403             return ts.getMutableClone(node);
73404         }
73405     }
73406     ts.createExpressionFromEntityName = createExpressionFromEntityName;
73407     function createExpressionForPropertyName(memberName) {
73408         if (ts.isIdentifier(memberName)) {
73409             return ts.createLiteral(memberName);
73410         }
73411         else if (ts.isComputedPropertyName(memberName)) {
73412             return ts.getMutableClone(memberName.expression);
73413         }
73414         else {
73415             return ts.getMutableClone(memberName);
73416         }
73417     }
73418     ts.createExpressionForPropertyName = createExpressionForPropertyName;
73419     function createExpressionForObjectLiteralElementLike(node, property, receiver) {
73420         if (property.name && ts.isPrivateIdentifier(property.name)) {
73421             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
73422         }
73423         switch (property.kind) {
73424             case 163 /* GetAccessor */:
73425             case 164 /* SetAccessor */:
73426                 return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
73427             case 281 /* PropertyAssignment */:
73428                 return createExpressionForPropertyAssignment(property, receiver);
73429             case 282 /* ShorthandPropertyAssignment */:
73430                 return createExpressionForShorthandPropertyAssignment(property, receiver);
73431             case 161 /* MethodDeclaration */:
73432                 return createExpressionForMethodDeclaration(property, receiver);
73433         }
73434     }
73435     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
73436     function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
73437         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
73438         if (property === firstAccessor) {
73439             var properties_7 = [];
73440             if (getAccessor) {
73441                 var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, 
73442                 /*asteriskToken*/ undefined, 
73443                 /*name*/ undefined, 
73444                 /*typeParameters*/ undefined, getAccessor.parameters, 
73445                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
73446                 );
73447                 ts.setTextRange(getterFunction, getAccessor);
73448                 ts.setOriginalNode(getterFunction, getAccessor);
73449                 var getter = ts.createPropertyAssignment("get", getterFunction);
73450                 properties_7.push(getter);
73451             }
73452             if (setAccessor) {
73453                 var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, 
73454                 /*asteriskToken*/ undefined, 
73455                 /*name*/ undefined, 
73456                 /*typeParameters*/ undefined, setAccessor.parameters, 
73457                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
73458                 );
73459                 ts.setTextRange(setterFunction, setAccessor);
73460                 ts.setOriginalNode(setterFunction, setAccessor);
73461                 var setter = ts.createPropertyAssignment("set", setterFunction);
73462                 properties_7.push(setter);
73463             }
73464             properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()));
73465             properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
73466             var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
73467             /*typeArguments*/ undefined, [
73468                 receiver,
73469                 createExpressionForPropertyName(property.name),
73470                 ts.createObjectLiteral(properties_7, multiLine)
73471             ]), 
73472             /*location*/ firstAccessor);
73473             return ts.aggregateTransformFlags(expression);
73474         }
73475         return undefined;
73476     }
73477     function createExpressionForPropertyAssignment(property, receiver) {
73478         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
73479     }
73480     function createExpressionForShorthandPropertyAssignment(property, receiver) {
73481         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), 
73482         /*location*/ property), 
73483         /*original*/ property));
73484     }
73485     function createExpressionForMethodDeclaration(method, receiver) {
73486         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, 
73487         /*name*/ undefined, 
73488         /*typeParameters*/ undefined, method.parameters, 
73489         /*type*/ undefined, method.body // TODO: GH#18217
73490         ), 
73491         /*location*/ method), 
73492         /*original*/ method)), 
73493         /*location*/ method), 
73494         /*original*/ method));
73495     }
73496     /**
73497      * Gets the internal name of a declaration. This is primarily used for declarations that can be
73498      * referred to by name in the body of an ES5 class function body. An internal name will *never*
73499      * be prefixed with an module or namespace export modifier like "exports." when emitted as an
73500      * expression. An internal name will also *never* be renamed due to a collision with a block
73501      * scoped variable.
73502      *
73503      * @param node The declaration.
73504      * @param allowComments A value indicating whether comments may be emitted for the name.
73505      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73506      */
73507     function getInternalName(node, allowComments, allowSourceMaps) {
73508         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
73509     }
73510     ts.getInternalName = getInternalName;
73511     /**
73512      * Gets whether an identifier should only be referred to by its internal name.
73513      */
73514     function isInternalName(node) {
73515         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
73516     }
73517     ts.isInternalName = isInternalName;
73518     /**
73519      * Gets the local name of a declaration. This is primarily used for declarations that can be
73520      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
73521      * local name will *never* be prefixed with an module or namespace export modifier like
73522      * "exports." when emitted as an expression.
73523      *
73524      * @param node The declaration.
73525      * @param allowComments A value indicating whether comments may be emitted for the name.
73526      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73527      */
73528     function getLocalName(node, allowComments, allowSourceMaps) {
73529         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
73530     }
73531     ts.getLocalName = getLocalName;
73532     /**
73533      * Gets whether an identifier should only be referred to by its local name.
73534      */
73535     function isLocalName(node) {
73536         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
73537     }
73538     ts.isLocalName = isLocalName;
73539     /**
73540      * Gets the export name of a declaration. This is primarily used for declarations that can be
73541      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
73542      * export name will *always* be prefixed with an module or namespace export modifier like
73543      * `"exports."` when emitted as an expression if the name points to an exported symbol.
73544      *
73545      * @param node The declaration.
73546      * @param allowComments A value indicating whether comments may be emitted for the name.
73547      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73548      */
73549     function getExportName(node, allowComments, allowSourceMaps) {
73550         return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
73551     }
73552     ts.getExportName = getExportName;
73553     /**
73554      * Gets whether an identifier should only be referred to by its export representation if the
73555      * name points to an exported symbol.
73556      */
73557     function isExportName(node) {
73558         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
73559     }
73560     ts.isExportName = isExportName;
73561     /**
73562      * Gets the name of a declaration for use in declarations.
73563      *
73564      * @param node The declaration.
73565      * @param allowComments A value indicating whether comments may be emitted for the name.
73566      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73567      */
73568     function getDeclarationName(node, allowComments, allowSourceMaps) {
73569         return getName(node, allowComments, allowSourceMaps);
73570     }
73571     ts.getDeclarationName = getDeclarationName;
73572     function getName(node, allowComments, allowSourceMaps, emitFlags) {
73573         if (emitFlags === void 0) { emitFlags = 0; }
73574         var nodeName = ts.getNameOfDeclaration(node);
73575         if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
73576             var name = ts.getMutableClone(nodeName);
73577             emitFlags |= ts.getEmitFlags(nodeName);
73578             if (!allowSourceMaps)
73579                 emitFlags |= 48 /* NoSourceMap */;
73580             if (!allowComments)
73581                 emitFlags |= 1536 /* NoComments */;
73582             if (emitFlags)
73583                 ts.setEmitFlags(name, emitFlags);
73584             return name;
73585         }
73586         return ts.getGeneratedNameForNode(node);
73587     }
73588     /**
73589      * Gets the exported name of a declaration for use in expressions.
73590      *
73591      * An exported name will *always* be prefixed with an module or namespace export modifier like
73592      * "exports." if the name points to an exported symbol.
73593      *
73594      * @param ns The namespace identifier.
73595      * @param node The declaration.
73596      * @param allowComments A value indicating whether comments may be emitted for the name.
73597      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73598      */
73599     function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
73600         if (ns && ts.hasModifier(node, 1 /* Export */)) {
73601             return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
73602         }
73603         return getExportName(node, allowComments, allowSourceMaps);
73604     }
73605     ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
73606     /**
73607      * Gets a namespace-qualified name for use in expressions.
73608      *
73609      * @param ns The namespace identifier.
73610      * @param name The name.
73611      * @param allowComments A value indicating whether comments may be emitted for the name.
73612      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73613      */
73614     function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
73615         var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
73616         ts.setTextRange(qualifiedName, name);
73617         var emitFlags = 0;
73618         if (!allowSourceMaps)
73619             emitFlags |= 48 /* NoSourceMap */;
73620         if (!allowComments)
73621             emitFlags |= 1536 /* NoComments */;
73622         if (emitFlags)
73623             ts.setEmitFlags(qualifiedName, emitFlags);
73624         return qualifiedName;
73625     }
73626     ts.getNamespaceMemberName = getNamespaceMemberName;
73627     function convertToFunctionBody(node, multiLine) {
73628         return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
73629     }
73630     ts.convertToFunctionBody = convertToFunctionBody;
73631     function convertFunctionDeclarationToExpression(node) {
73632         if (!node.body)
73633             return ts.Debug.fail();
73634         var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
73635         ts.setOriginalNode(updated, node);
73636         ts.setTextRange(updated, node);
73637         if (ts.getStartsOnNewLine(node)) {
73638             ts.setStartsOnNewLine(updated, /*newLine*/ true);
73639         }
73640         ts.aggregateTransformFlags(updated);
73641         return updated;
73642     }
73643     ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
73644     function isUseStrictPrologue(node) {
73645         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
73646     }
73647     /**
73648      * Add any necessary prologue-directives into target statement-array.
73649      * The function needs to be called during each transformation step.
73650      * This function needs to be called whenever we transform the statement
73651      * list of a source file, namespace, or function-like body.
73652      *
73653      * @param target: result statements array
73654      * @param source: origin statements array
73655      * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
73656      * @param visitor: Optional callback used to visit any custom prologue directives.
73657      */
73658     function addPrologue(target, source, ensureUseStrict, visitor) {
73659         var offset = addStandardPrologue(target, source, ensureUseStrict);
73660         return addCustomPrologue(target, source, offset, visitor);
73661     }
73662     ts.addPrologue = addPrologue;
73663     /**
73664      * Add just the standard (string-expression) prologue-directives into target statement-array.
73665      * The function needs to be called during each transformation step.
73666      * This function needs to be called whenever we transform the statement
73667      * list of a source file, namespace, or function-like body.
73668      */
73669     function addStandardPrologue(target, source, ensureUseStrict) {
73670         ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
73671         var foundUseStrict = false;
73672         var statementOffset = 0;
73673         var numStatements = source.length;
73674         while (statementOffset < numStatements) {
73675             var statement = source[statementOffset];
73676             if (ts.isPrologueDirective(statement)) {
73677                 if (isUseStrictPrologue(statement)) {
73678                     foundUseStrict = true;
73679                 }
73680                 target.push(statement);
73681             }
73682             else {
73683                 break;
73684             }
73685             statementOffset++;
73686         }
73687         if (ensureUseStrict && !foundUseStrict) {
73688             target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
73689         }
73690         return statementOffset;
73691     }
73692     ts.addStandardPrologue = addStandardPrologue;
73693     function addCustomPrologue(target, source, statementOffset, visitor, filter) {
73694         if (filter === void 0) { filter = ts.returnTrue; }
73695         var numStatements = source.length;
73696         while (statementOffset !== undefined && statementOffset < numStatements) {
73697             var statement = source[statementOffset];
73698             if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
73699                 ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
73700             }
73701             else {
73702                 break;
73703             }
73704             statementOffset++;
73705         }
73706         return statementOffset;
73707     }
73708     ts.addCustomPrologue = addCustomPrologue;
73709     function findUseStrictPrologue(statements) {
73710         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
73711             var statement = statements_4[_i];
73712             if (ts.isPrologueDirective(statement)) {
73713                 if (isUseStrictPrologue(statement)) {
73714                     return statement;
73715                 }
73716             }
73717             else {
73718                 break;
73719             }
73720         }
73721         return undefined;
73722     }
73723     ts.findUseStrictPrologue = findUseStrictPrologue;
73724     function startsWithUseStrict(statements) {
73725         var firstStatement = ts.firstOrUndefined(statements);
73726         return firstStatement !== undefined
73727             && ts.isPrologueDirective(firstStatement)
73728             && isUseStrictPrologue(firstStatement);
73729     }
73730     ts.startsWithUseStrict = startsWithUseStrict;
73731     /**
73732      * Ensures "use strict" directive is added
73733      *
73734      * @param statements An array of statements
73735      */
73736     function ensureUseStrict(statements) {
73737         var foundUseStrict = findUseStrictPrologue(statements);
73738         if (!foundUseStrict) {
73739             return ts.setTextRange(ts.createNodeArray(__spreadArrays([
73740                 startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
73741             ], statements)), statements);
73742         }
73743         return statements;
73744     }
73745     ts.ensureUseStrict = ensureUseStrict;
73746     /**
73747      * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
73748      * order of operations.
73749      *
73750      * @param binaryOperator The operator for the BinaryExpression.
73751      * @param operand The operand for the BinaryExpression.
73752      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73753      *                           BinaryExpression.
73754      */
73755     function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73756         var skipped = ts.skipPartiallyEmittedExpressions(operand);
73757         // If the resulting expression is already parenthesized, we do not need to do any further processing.
73758         if (skipped.kind === 200 /* ParenthesizedExpression */) {
73759             return operand;
73760         }
73761         return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
73762             ? ts.createParen(operand)
73763             : operand;
73764     }
73765     ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
73766     /**
73767      * Determines whether the operand to a BinaryExpression needs to be parenthesized.
73768      *
73769      * @param binaryOperator The operator for the BinaryExpression.
73770      * @param operand The operand for the BinaryExpression.
73771      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73772      *                           BinaryExpression.
73773      */
73774     function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73775         // If the operand has lower precedence, then it needs to be parenthesized to preserve the
73776         // intent of the expression. For example, if the operand is `a + b` and the operator is
73777         // `*`, then we need to parenthesize the operand to preserve the intended order of
73778         // operations: `(a + b) * x`.
73779         //
73780         // If the operand has higher precedence, then it does not need to be parenthesized. For
73781         // example, if the operand is `a * b` and the operator is `+`, then we do not need to
73782         // parenthesize to preserve the intended order of operations: `a * b + x`.
73783         //
73784         // If the operand has the same precedence, then we need to check the associativity of
73785         // the operator based on whether this is the left or right operand of the expression.
73786         //
73787         // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
73788         // to preserve the intended order of operations: `x * (a / d)`
73789         //
73790         // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
73791         // the intended order of operations: `(a ** b) ** c`
73792         var binaryOperatorPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, binaryOperator);
73793         var binaryOperatorAssociativity = ts.getOperatorAssociativity(209 /* BinaryExpression */, binaryOperator);
73794         var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
73795         if (!isLeftSideOfBinary && operand.kind === 202 /* ArrowFunction */ && binaryOperatorPrecedence > 3) {
73796             // We need to parenthesize arrow functions on the right side to avoid it being
73797             // parsed as parenthesized expression: `a && (() => {})`
73798             return true;
73799         }
73800         var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
73801         switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
73802             case -1 /* LessThan */:
73803                 // If the operand is the right side of a right-associative binary operation
73804                 // and is a yield expression, then we do not need parentheses.
73805                 if (!isLeftSideOfBinary
73806                     && binaryOperatorAssociativity === 1 /* Right */
73807                     && operand.kind === 212 /* YieldExpression */) {
73808                     return false;
73809                 }
73810                 return true;
73811             case 1 /* GreaterThan */:
73812                 return false;
73813             case 0 /* EqualTo */:
73814                 if (isLeftSideOfBinary) {
73815                     // No need to parenthesize the left operand when the binary operator is
73816                     // left associative:
73817                     //  (a*b)/x    -> a*b/x
73818                     //  (a**b)/x   -> a**b/x
73819                     //
73820                     // Parentheses are needed for the left operand when the binary operator is
73821                     // right associative:
73822                     //  (a/b)**x   -> (a/b)**x
73823                     //  (a**b)**x  -> (a**b)**x
73824                     return binaryOperatorAssociativity === 1 /* Right */;
73825                 }
73826                 else {
73827                     if (ts.isBinaryExpression(emittedOperand)
73828                         && emittedOperand.operatorToken.kind === binaryOperator) {
73829                         // No need to parenthesize the right operand when the binary operator and
73830                         // operand are the same and one of the following:
73831                         //  x*(a*b)     => x*a*b
73832                         //  x|(a|b)     => x|a|b
73833                         //  x&(a&b)     => x&a&b
73834                         //  x^(a^b)     => x^a^b
73835                         if (operatorHasAssociativeProperty(binaryOperator)) {
73836                             return false;
73837                         }
73838                         // No need to parenthesize the right operand when the binary operator
73839                         // is plus (+) if both the left and right operands consist solely of either
73840                         // literals of the same kind or binary plus (+) expressions for literals of
73841                         // the same kind (recursively).
73842                         //  "a"+(1+2)       => "a"+(1+2)
73843                         //  "a"+("b"+"c")   => "a"+"b"+"c"
73844                         if (binaryOperator === 39 /* PlusToken */) {
73845                             var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
73846                             if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
73847                                 return false;
73848                             }
73849                         }
73850                     }
73851                     // No need to parenthesize the right operand when the operand is right
73852                     // associative:
73853                     //  x/(a**b)    -> x/a**b
73854                     //  x**(a**b)   -> x**a**b
73855                     //
73856                     // Parentheses are needed for the right operand when the operand is left
73857                     // associative:
73858                     //  x/(a*b)     -> x/(a*b)
73859                     //  x**(a/b)    -> x**(a/b)
73860                     var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
73861                     return operandAssociativity === 0 /* Left */;
73862                 }
73863         }
73864     }
73865     /**
73866      * Determines whether a binary operator is mathematically associative.
73867      *
73868      * @param binaryOperator The binary operator.
73869      */
73870     function operatorHasAssociativeProperty(binaryOperator) {
73871         // The following operators are associative in JavaScript:
73872         //  (a*b)*c     -> a*(b*c)  -> a*b*c
73873         //  (a|b)|c     -> a|(b|c)  -> a|b|c
73874         //  (a&b)&c     -> a&(b&c)  -> a&b&c
73875         //  (a^b)^c     -> a^(b^c)  -> a^b^c
73876         //
73877         // While addition is associative in mathematics, JavaScript's `+` is not
73878         // guaranteed to be associative as it is overloaded with string concatenation.
73879         return binaryOperator === 41 /* AsteriskToken */
73880             || binaryOperator === 51 /* BarToken */
73881             || binaryOperator === 50 /* AmpersandToken */
73882             || binaryOperator === 52 /* CaretToken */;
73883     }
73884     /**
73885      * This function determines whether an expression consists of a homogeneous set of
73886      * literal expressions or binary plus expressions that all share the same literal kind.
73887      * It is used to determine whether the right-hand operand of a binary plus expression can be
73888      * emitted without parentheses.
73889      */
73890     function getLiteralKindOfBinaryPlusOperand(node) {
73891         node = ts.skipPartiallyEmittedExpressions(node);
73892         if (ts.isLiteralKind(node.kind)) {
73893             return node.kind;
73894         }
73895         if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
73896             if (node.cachedLiteralKind !== undefined) {
73897                 return node.cachedLiteralKind;
73898             }
73899             var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
73900             var literalKind = ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind :
73901                 0 /* Unknown */;
73902             node.cachedLiteralKind = literalKind;
73903             return literalKind;
73904         }
73905         return 0 /* Unknown */;
73906     }
73907     function parenthesizeForConditionalHead(condition) {
73908         var conditionalPrecedence = ts.getOperatorPrecedence(210 /* ConditionalExpression */, 57 /* QuestionToken */);
73909         var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
73910         var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
73911         if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
73912             return ts.createParen(condition);
73913         }
73914         return condition;
73915     }
73916     ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
73917     function parenthesizeSubexpressionOfConditionalExpression(e) {
73918         // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
73919         // so in case when comma expression is introduced as a part of previous transformations
73920         // if should be wrapped in parens since comma operator has the lowest precedence
73921         var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
73922         return isCommaSequence(emittedExpression)
73923             ? ts.createParen(e)
73924             : e;
73925     }
73926     ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
73927     /**
73928      *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
73929      *  has a lookahead restriction for `function`, `async function`, and `class`.
73930      *
73931      * Basically, that means we need to parenthesize in the following cases:
73932      *
73933      * - BinaryExpression of CommaToken
73934      * - CommaList (synthetic list of multiple comma expressions)
73935      * - FunctionExpression
73936      * - ClassExpression
73937      */
73938     function parenthesizeDefaultExpression(e) {
73939         var check = ts.skipPartiallyEmittedExpressions(e);
73940         var needsParens = isCommaSequence(check);
73941         if (!needsParens) {
73942             switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
73943                 case 214 /* ClassExpression */:
73944                 case 201 /* FunctionExpression */:
73945                     needsParens = true;
73946             }
73947         }
73948         return needsParens ? ts.createParen(e) : e;
73949     }
73950     ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
73951     /**
73952      * Wraps an expression in parentheses if it is needed in order to use the expression
73953      * as the expression of a NewExpression node.
73954      *
73955      * @param expression The Expression node.
73956      */
73957     function parenthesizeForNew(expression) {
73958         var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
73959         switch (leftmostExpr.kind) {
73960             case 196 /* CallExpression */:
73961                 return ts.createParen(expression);
73962             case 197 /* NewExpression */:
73963                 return !leftmostExpr.arguments
73964                     ? ts.createParen(expression)
73965                     : expression;
73966         }
73967         return parenthesizeForAccess(expression);
73968     }
73969     ts.parenthesizeForNew = parenthesizeForNew;
73970     /**
73971      * Wraps an expression in parentheses if it is needed in order to use the expression for
73972      * property or element access.
73973      *
73974      * @param expr The expression node.
73975      */
73976     function parenthesizeForAccess(expression) {
73977         // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
73978         // to parenthesize the expression before a dot. The known exception is:
73979         //
73980         //    NewExpression:
73981         //       new C.x        -> not the same as (new C).x
73982         //
73983         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
73984         if (ts.isLeftHandSideExpression(emittedExpression)
73985             && (emittedExpression.kind !== 197 /* NewExpression */ || emittedExpression.arguments)) {
73986             return expression;
73987         }
73988         return ts.setTextRange(ts.createParen(expression), expression);
73989     }
73990     ts.parenthesizeForAccess = parenthesizeForAccess;
73991     function parenthesizePostfixOperand(operand) {
73992         return ts.isLeftHandSideExpression(operand)
73993             ? operand
73994             : ts.setTextRange(ts.createParen(operand), operand);
73995     }
73996     ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
73997     function parenthesizePrefixOperand(operand) {
73998         return ts.isUnaryExpression(operand)
73999             ? operand
74000             : ts.setTextRange(ts.createParen(operand), operand);
74001     }
74002     ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
74003     function parenthesizeListElements(elements) {
74004         var result;
74005         for (var i = 0; i < elements.length; i++) {
74006             var element = parenthesizeExpressionForList(elements[i]);
74007             if (result !== undefined || element !== elements[i]) {
74008                 if (result === undefined) {
74009                     result = elements.slice(0, i);
74010                 }
74011                 result.push(element);
74012             }
74013         }
74014         if (result !== undefined) {
74015             return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
74016         }
74017         return elements;
74018     }
74019     ts.parenthesizeListElements = parenthesizeListElements;
74020     function parenthesizeExpressionForList(expression) {
74021         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74022         var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
74023         var commaPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, 27 /* CommaToken */);
74024         return expressionPrecedence > commaPrecedence
74025             ? expression
74026             : ts.setTextRange(ts.createParen(expression), expression);
74027     }
74028     ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
74029     function parenthesizeExpressionForExpressionStatement(expression) {
74030         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74031         if (ts.isCallExpression(emittedExpression)) {
74032             var callee = emittedExpression.expression;
74033             var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
74034             if (kind === 201 /* FunctionExpression */ || kind === 202 /* ArrowFunction */) {
74035                 var mutableCall = ts.getMutableClone(emittedExpression);
74036                 mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
74037                 return recreateOuterExpressions(expression, mutableCall, 8 /* PartiallyEmittedExpressions */);
74038             }
74039         }
74040         var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
74041         if (leftmostExpressionKind === 193 /* ObjectLiteralExpression */ || leftmostExpressionKind === 201 /* FunctionExpression */) {
74042             return ts.setTextRange(ts.createParen(expression), expression);
74043         }
74044         return expression;
74045     }
74046     ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
74047     function parenthesizeConditionalTypeMember(member) {
74048         return member.kind === 180 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
74049     }
74050     ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
74051     function parenthesizeElementTypeMember(member) {
74052         switch (member.kind) {
74053             case 178 /* UnionType */:
74054             case 179 /* IntersectionType */:
74055             case 170 /* FunctionType */:
74056             case 171 /* ConstructorType */:
74057                 return ts.createParenthesizedType(member);
74058         }
74059         return parenthesizeConditionalTypeMember(member);
74060     }
74061     ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
74062     function parenthesizeArrayTypeMember(member) {
74063         switch (member.kind) {
74064             case 172 /* TypeQuery */:
74065             case 184 /* TypeOperator */:
74066             case 181 /* InferType */:
74067                 return ts.createParenthesizedType(member);
74068         }
74069         return parenthesizeElementTypeMember(member);
74070     }
74071     ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
74072     function parenthesizeElementTypeMembers(members) {
74073         return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
74074     }
74075     ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
74076     function parenthesizeTypeParameters(typeParameters) {
74077         if (ts.some(typeParameters)) {
74078             var params = [];
74079             for (var i = 0; i < typeParameters.length; ++i) {
74080                 var entry = typeParameters[i];
74081                 params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
74082                     ts.createParenthesizedType(entry) :
74083                     entry);
74084             }
74085             return ts.createNodeArray(params);
74086         }
74087     }
74088     ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
74089     function getLeftmostExpression(node, stopAtCallExpressions) {
74090         while (true) {
74091             switch (node.kind) {
74092                 case 208 /* PostfixUnaryExpression */:
74093                     node = node.operand;
74094                     continue;
74095                 case 209 /* BinaryExpression */:
74096                     node = node.left;
74097                     continue;
74098                 case 210 /* ConditionalExpression */:
74099                     node = node.condition;
74100                     continue;
74101                 case 198 /* TaggedTemplateExpression */:
74102                     node = node.tag;
74103                     continue;
74104                 case 196 /* CallExpression */:
74105                     if (stopAtCallExpressions) {
74106                         return node;
74107                     }
74108                 // falls through
74109                 case 217 /* AsExpression */:
74110                 case 195 /* ElementAccessExpression */:
74111                 case 194 /* PropertyAccessExpression */:
74112                 case 218 /* NonNullExpression */:
74113                 case 326 /* PartiallyEmittedExpression */:
74114                     node = node.expression;
74115                     continue;
74116             }
74117             return node;
74118         }
74119     }
74120     ts.getLeftmostExpression = getLeftmostExpression;
74121     function parenthesizeConciseBody(body) {
74122         if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 193 /* ObjectLiteralExpression */)) {
74123             return ts.setTextRange(ts.createParen(body), body);
74124         }
74125         return body;
74126     }
74127     ts.parenthesizeConciseBody = parenthesizeConciseBody;
74128     function isCommaSequence(node) {
74129         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
74130             node.kind === 327 /* CommaListExpression */;
74131     }
74132     ts.isCommaSequence = isCommaSequence;
74133     var OuterExpressionKinds;
74134     (function (OuterExpressionKinds) {
74135         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
74136         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
74137         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
74138         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
74139         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
74140         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
74141     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
74142     function isOuterExpression(node, kinds) {
74143         if (kinds === void 0) { kinds = 15 /* All */; }
74144         switch (node.kind) {
74145             case 200 /* ParenthesizedExpression */:
74146                 return (kinds & 1 /* Parentheses */) !== 0;
74147             case 199 /* TypeAssertionExpression */:
74148             case 217 /* AsExpression */:
74149                 return (kinds & 2 /* TypeAssertions */) !== 0;
74150             case 218 /* NonNullExpression */:
74151                 return (kinds & 4 /* NonNullAssertions */) !== 0;
74152             case 326 /* PartiallyEmittedExpression */:
74153                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
74154         }
74155         return false;
74156     }
74157     ts.isOuterExpression = isOuterExpression;
74158     function skipOuterExpressions(node, kinds) {
74159         if (kinds === void 0) { kinds = 15 /* All */; }
74160         while (isOuterExpression(node, kinds)) {
74161             node = node.expression;
74162         }
74163         return node;
74164     }
74165     ts.skipOuterExpressions = skipOuterExpressions;
74166     function skipAssertions(node) {
74167         return skipOuterExpressions(node, 6 /* Assertions */);
74168     }
74169     ts.skipAssertions = skipAssertions;
74170     function updateOuterExpression(outerExpression, expression) {
74171         switch (outerExpression.kind) {
74172             case 200 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
74173             case 199 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
74174             case 217 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
74175             case 218 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
74176             case 326 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
74177         }
74178     }
74179     /**
74180      * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
74181      *
74182      * A parenthesized expression can be ignored when all of the following are true:
74183      *
74184      * - It's `pos` and `end` are not -1
74185      * - It does not have a custom source map range
74186      * - It does not have a custom comment range
74187      * - It does not have synthetic leading or trailing comments
74188      *
74189      * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
74190      * the expression to maintain precedence, a new parenthesized expression should be created automatically when
74191      * the containing expression is created/updated.
74192      */
74193     function isIgnorableParen(node) {
74194         return node.kind === 200 /* ParenthesizedExpression */
74195             && ts.nodeIsSynthesized(node)
74196             && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
74197             && ts.nodeIsSynthesized(ts.getCommentRange(node))
74198             && !ts.some(ts.getSyntheticLeadingComments(node))
74199             && !ts.some(ts.getSyntheticTrailingComments(node));
74200     }
74201     function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
74202         if (kinds === void 0) { kinds = 15 /* All */; }
74203         if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
74204             return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
74205         }
74206         return innerExpression;
74207     }
74208     ts.recreateOuterExpressions = recreateOuterExpressions;
74209     function startOnNewLine(node) {
74210         return ts.setStartsOnNewLine(node, /*newLine*/ true);
74211     }
74212     ts.startOnNewLine = startOnNewLine;
74213     function getExternalHelpersModuleName(node) {
74214         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74215         var emitNode = parseNode && parseNode.emitNode;
74216         return emitNode && emitNode.externalHelpersModuleName;
74217     }
74218     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
74219     function hasRecordedExternalHelpers(sourceFile) {
74220         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74221         var emitNode = parseNode && parseNode.emitNode;
74222         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
74223     }
74224     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
74225     function createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
74226         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
74227             var namedBindings = void 0;
74228             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74229             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
74230                 // use named imports
74231                 var helpers = ts.getEmitHelpers(sourceFile);
74232                 if (helpers) {
74233                     var helperNames = [];
74234                     for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
74235                         var helper = helpers_2[_i];
74236                         if (!helper.scoped) {
74237                             var importName = helper.importName;
74238                             if (importName) {
74239                                 ts.pushIfUnique(helperNames, importName);
74240                             }
74241                         }
74242                     }
74243                     if (ts.some(helperNames)) {
74244                         helperNames.sort(ts.compareStringsCaseSensitive);
74245                         // Alias the imports if the names are used somewhere in the file.
74246                         // NOTE: We don't need to care about global import collisions as this is a module.
74247                         namedBindings = ts.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
74248                             ? ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))
74249                             : ts.createImportSpecifier(ts.createIdentifier(name), getUnscopedHelperName(name)); }));
74250                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74251                         var emitNode = ts.getOrCreateEmitNode(parseNode);
74252                         emitNode.externalHelpers = true;
74253                     }
74254                 }
74255             }
74256             else {
74257                 // use a namespace import
74258                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
74259                 if (externalHelpersModuleName) {
74260                     namedBindings = ts.createNamespaceImport(externalHelpersModuleName);
74261                 }
74262             }
74263             if (namedBindings) {
74264                 var externalHelpersImportDeclaration = ts.createImportDeclaration(
74265                 /*decorators*/ undefined, 
74266                 /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, namedBindings), ts.createLiteral(ts.externalHelpersModuleNameText));
74267                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
74268                 return externalHelpersImportDeclaration;
74269             }
74270         }
74271     }
74272     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
74273     function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
74274         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
74275             var externalHelpersModuleName = getExternalHelpersModuleName(node);
74276             if (externalHelpersModuleName) {
74277                 return externalHelpersModuleName;
74278             }
74279             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74280             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
74281                 && moduleKind !== ts.ModuleKind.System
74282                 && moduleKind < ts.ModuleKind.ES2015;
74283             if (!create) {
74284                 var helpers = ts.getEmitHelpers(node);
74285                 if (helpers) {
74286                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
74287                         var helper = helpers_3[_i];
74288                         if (!helper.scoped) {
74289                             create = true;
74290                             break;
74291                         }
74292                     }
74293                 }
74294             }
74295             if (create) {
74296                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74297                 var emitNode = ts.getOrCreateEmitNode(parseNode);
74298                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
74299             }
74300         }
74301     }
74302     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
74303     /**
74304      * Get the name of that target module from an import or export declaration
74305      */
74306     function getLocalNameForExternalImport(node, sourceFile) {
74307         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
74308         if (namespaceDeclaration && !ts.isDefaultImport(node)) {
74309             var name = namespaceDeclaration.name;
74310             return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
74311         }
74312         if (node.kind === 254 /* ImportDeclaration */ && node.importClause) {
74313             return ts.getGeneratedNameForNode(node);
74314         }
74315         if (node.kind === 260 /* ExportDeclaration */ && node.moduleSpecifier) {
74316             return ts.getGeneratedNameForNode(node);
74317         }
74318         return undefined;
74319     }
74320     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
74321     /**
74322      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
74323      * The emitted output name can be different from the input if:
74324      *  1. The module has a /// <amd-module name="<new name>" />
74325      *  2. --out or --outFile is used, making the name relative to the rootDir
74326      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
74327      * Otherwise, a new StringLiteral node representing the module name will be returned.
74328      */
74329     function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
74330         var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
74331         if (moduleName.kind === 10 /* StringLiteral */) {
74332             return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
74333                 || tryRenameExternalModule(moduleName, sourceFile)
74334                 || ts.getSynthesizedClone(moduleName);
74335         }
74336         return undefined;
74337     }
74338     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
74339     /**
74340      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
74341      * Here we check if alternative name was provided for a given moduleName and return it if possible.
74342      */
74343     function tryRenameExternalModule(moduleName, sourceFile) {
74344         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
74345         return rename && ts.createLiteral(rename);
74346     }
74347     /**
74348      * Get the name of a module as should be written in the emitted output.
74349      * The emitted output name can be different from the input if:
74350      *  1. The module has a /// <amd-module name="<new name>" />
74351      *  2. --out or --outFile is used, making the name relative to the rootDir
74352      * Otherwise, a new StringLiteral node representing the module name will be returned.
74353      */
74354     function tryGetModuleNameFromFile(file, host, options) {
74355         if (!file) {
74356             return undefined;
74357         }
74358         if (file.moduleName) {
74359             return ts.createLiteral(file.moduleName);
74360         }
74361         if (!file.isDeclarationFile && (options.out || options.outFile)) {
74362             return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
74363         }
74364         return undefined;
74365     }
74366     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
74367     function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
74368         return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
74369     }
74370     /**
74371      * Gets the initializer of an BindingOrAssignmentElement.
74372      */
74373     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
74374         if (ts.isDeclarationBindingElement(bindingElement)) {
74375             // `1` in `let { a = 1 } = ...`
74376             // `1` in `let { a: b = 1 } = ...`
74377             // `1` in `let { a: {b} = 1 } = ...`
74378             // `1` in `let { a: [b] = 1 } = ...`
74379             // `1` in `let [a = 1] = ...`
74380             // `1` in `let [{a} = 1] = ...`
74381             // `1` in `let [[a] = 1] = ...`
74382             return bindingElement.initializer;
74383         }
74384         if (ts.isPropertyAssignment(bindingElement)) {
74385             // `1` in `({ a: b = 1 } = ...)`
74386             // `1` in `({ a: {b} = 1 } = ...)`
74387             // `1` in `({ a: [b] = 1 } = ...)`
74388             var initializer = bindingElement.initializer;
74389             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
74390                 ? initializer.right
74391                 : undefined;
74392         }
74393         if (ts.isShorthandPropertyAssignment(bindingElement)) {
74394             // `1` in `({ a = 1 } = ...)`
74395             return bindingElement.objectAssignmentInitializer;
74396         }
74397         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74398             // `1` in `[a = 1] = ...`
74399             // `1` in `[{a} = 1] = ...`
74400             // `1` in `[[a] = 1] = ...`
74401             return bindingElement.right;
74402         }
74403         if (ts.isSpreadElement(bindingElement)) {
74404             // Recovery consistent with existing emit.
74405             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
74406         }
74407     }
74408     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
74409     /**
74410      * Gets the name of an BindingOrAssignmentElement.
74411      */
74412     function getTargetOfBindingOrAssignmentElement(bindingElement) {
74413         if (ts.isDeclarationBindingElement(bindingElement)) {
74414             // `a` in `let { a } = ...`
74415             // `a` in `let { a = 1 } = ...`
74416             // `b` in `let { a: b } = ...`
74417             // `b` in `let { a: b = 1 } = ...`
74418             // `a` in `let { ...a } = ...`
74419             // `{b}` in `let { a: {b} } = ...`
74420             // `{b}` in `let { a: {b} = 1 } = ...`
74421             // `[b]` in `let { a: [b] } = ...`
74422             // `[b]` in `let { a: [b] = 1 } = ...`
74423             // `a` in `let [a] = ...`
74424             // `a` in `let [a = 1] = ...`
74425             // `a` in `let [...a] = ...`
74426             // `{a}` in `let [{a}] = ...`
74427             // `{a}` in `let [{a} = 1] = ...`
74428             // `[a]` in `let [[a]] = ...`
74429             // `[a]` in `let [[a] = 1] = ...`
74430             return bindingElement.name;
74431         }
74432         if (ts.isObjectLiteralElementLike(bindingElement)) {
74433             switch (bindingElement.kind) {
74434                 case 281 /* PropertyAssignment */:
74435                     // `b` in `({ a: b } = ...)`
74436                     // `b` in `({ a: b = 1 } = ...)`
74437                     // `{b}` in `({ a: {b} } = ...)`
74438                     // `{b}` in `({ a: {b} = 1 } = ...)`
74439                     // `[b]` in `({ a: [b] } = ...)`
74440                     // `[b]` in `({ a: [b] = 1 } = ...)`
74441                     // `b.c` in `({ a: b.c } = ...)`
74442                     // `b.c` in `({ a: b.c = 1 } = ...)`
74443                     // `b[0]` in `({ a: b[0] } = ...)`
74444                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
74445                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
74446                 case 282 /* ShorthandPropertyAssignment */:
74447                     // `a` in `({ a } = ...)`
74448                     // `a` in `({ a = 1 } = ...)`
74449                     return bindingElement.name;
74450                 case 283 /* SpreadAssignment */:
74451                     // `a` in `({ ...a } = ...)`
74452                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74453             }
74454             // no target
74455             return undefined;
74456         }
74457         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74458             // `a` in `[a = 1] = ...`
74459             // `{a}` in `[{a} = 1] = ...`
74460             // `[a]` in `[[a] = 1] = ...`
74461             // `a.b` in `[a.b = 1] = ...`
74462             // `a[0]` in `[a[0] = 1] = ...`
74463             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
74464         }
74465         if (ts.isSpreadElement(bindingElement)) {
74466             // `a` in `[...a] = ...`
74467             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74468         }
74469         // `a` in `[a] = ...`
74470         // `{a}` in `[{a}] = ...`
74471         // `[a]` in `[[a]] = ...`
74472         // `a.b` in `[a.b] = ...`
74473         // `a[0]` in `[a[0]] = ...`
74474         return bindingElement;
74475     }
74476     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
74477     /**
74478      * Determines whether an BindingOrAssignmentElement is a rest element.
74479      */
74480     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
74481         switch (bindingElement.kind) {
74482             case 156 /* Parameter */:
74483             case 191 /* BindingElement */:
74484                 // `...` in `let [...a] = ...`
74485                 return bindingElement.dotDotDotToken;
74486             case 213 /* SpreadElement */:
74487             case 283 /* SpreadAssignment */:
74488                 // `...` in `[...a] = ...`
74489                 return bindingElement;
74490         }
74491         return undefined;
74492     }
74493     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
74494     /**
74495      * Gets the property name of a BindingOrAssignmentElement
74496      */
74497     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74498         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
74499         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
74500         return propertyName;
74501     }
74502     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
74503     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74504         switch (bindingElement.kind) {
74505             case 191 /* BindingElement */:
74506                 // `a` in `let { a: b } = ...`
74507                 // `[a]` in `let { [a]: b } = ...`
74508                 // `"a"` in `let { "a": b } = ...`
74509                 // `1` in `let { 1: b } = ...`
74510                 if (bindingElement.propertyName) {
74511                     var propertyName = bindingElement.propertyName;
74512                     if (ts.isPrivateIdentifier(propertyName)) {
74513                         return ts.Debug.failBadSyntaxKind(propertyName);
74514                     }
74515                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74516                         ? propertyName.expression
74517                         : propertyName;
74518                 }
74519                 break;
74520             case 281 /* PropertyAssignment */:
74521                 // `a` in `({ a: b } = ...)`
74522                 // `[a]` in `({ [a]: b } = ...)`
74523                 // `"a"` in `({ "a": b } = ...)`
74524                 // `1` in `({ 1: b } = ...)`
74525                 if (bindingElement.name) {
74526                     var propertyName = bindingElement.name;
74527                     if (ts.isPrivateIdentifier(propertyName)) {
74528                         return ts.Debug.failBadSyntaxKind(propertyName);
74529                     }
74530                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74531                         ? propertyName.expression
74532                         : propertyName;
74533                 }
74534                 break;
74535             case 283 /* SpreadAssignment */:
74536                 // `a` in `({ ...a } = ...)`
74537                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
74538                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
74539                 }
74540                 return bindingElement.name;
74541         }
74542         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
74543         if (target && ts.isPropertyName(target)) {
74544             return target;
74545         }
74546     }
74547     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
74548     function isStringOrNumericLiteral(node) {
74549         var kind = node.kind;
74550         return kind === 10 /* StringLiteral */
74551             || kind === 8 /* NumericLiteral */;
74552     }
74553     /**
74554      * Gets the elements of a BindingOrAssignmentPattern
74555      */
74556     function getElementsOfBindingOrAssignmentPattern(name) {
74557         switch (name.kind) {
74558             case 189 /* ObjectBindingPattern */:
74559             case 190 /* ArrayBindingPattern */:
74560             case 192 /* ArrayLiteralExpression */:
74561                 // `a` in `{a}`
74562                 // `a` in `[a]`
74563                 return name.elements;
74564             case 193 /* ObjectLiteralExpression */:
74565                 // `a` in `{a}`
74566                 return name.properties;
74567         }
74568     }
74569     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
74570     function convertToArrayAssignmentElement(element) {
74571         if (ts.isBindingElement(element)) {
74572             if (element.dotDotDotToken) {
74573                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74574                 return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
74575             }
74576             var expression = convertToAssignmentElementTarget(element.name);
74577             return element.initializer
74578                 ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
74579                 : expression;
74580         }
74581         ts.Debug.assertNode(element, ts.isExpression);
74582         return element;
74583     }
74584     ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
74585     function convertToObjectAssignmentElement(element) {
74586         if (ts.isBindingElement(element)) {
74587             if (element.dotDotDotToken) {
74588                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74589                 return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
74590             }
74591             if (element.propertyName) {
74592                 var expression = convertToAssignmentElementTarget(element.name);
74593                 return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
74594             }
74595             ts.Debug.assertNode(element.name, ts.isIdentifier);
74596             return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
74597         }
74598         ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
74599         return element;
74600     }
74601     ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
74602     function convertToAssignmentPattern(node) {
74603         switch (node.kind) {
74604             case 190 /* ArrayBindingPattern */:
74605             case 192 /* ArrayLiteralExpression */:
74606                 return convertToArrayAssignmentPattern(node);
74607             case 189 /* ObjectBindingPattern */:
74608             case 193 /* ObjectLiteralExpression */:
74609                 return convertToObjectAssignmentPattern(node);
74610         }
74611     }
74612     ts.convertToAssignmentPattern = convertToAssignmentPattern;
74613     function convertToObjectAssignmentPattern(node) {
74614         if (ts.isObjectBindingPattern(node)) {
74615             return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
74616         }
74617         ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
74618         return node;
74619     }
74620     ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
74621     function convertToArrayAssignmentPattern(node) {
74622         if (ts.isArrayBindingPattern(node)) {
74623             return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
74624         }
74625         ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
74626         return node;
74627     }
74628     ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
74629     function convertToAssignmentElementTarget(node) {
74630         if (ts.isBindingPattern(node)) {
74631             return convertToAssignmentPattern(node);
74632         }
74633         ts.Debug.assertNode(node, ts.isExpression);
74634         return node;
74635     }
74636     ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
74637 })(ts || (ts = {}));
74638 var ts;
74639 (function (ts) {
74640     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
74641     function visitNode(node, visitor, test, lift) {
74642         if (node === undefined || visitor === undefined) {
74643             return node;
74644         }
74645         ts.aggregateTransformFlags(node);
74646         var visited = visitor(node);
74647         if (visited === node) {
74648             return node;
74649         }
74650         var visitedNode;
74651         if (visited === undefined) {
74652             return undefined;
74653         }
74654         else if (ts.isArray(visited)) {
74655             visitedNode = (lift || extractSingleNode)(visited);
74656         }
74657         else {
74658             visitedNode = visited;
74659         }
74660         ts.Debug.assertNode(visitedNode, test);
74661         ts.aggregateTransformFlags(visitedNode);
74662         return visitedNode;
74663     }
74664     ts.visitNode = visitNode;
74665     /**
74666      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
74667      *
74668      * @param nodes The NodeArray to visit.
74669      * @param visitor The callback used to visit a Node.
74670      * @param test A node test to execute for each node.
74671      * @param start An optional value indicating the starting offset at which to start visiting.
74672      * @param count An optional value indicating the maximum number of nodes to visit.
74673      */
74674     function visitNodes(nodes, visitor, test, start, count) {
74675         if (nodes === undefined || visitor === undefined) {
74676             return nodes;
74677         }
74678         var updated;
74679         // Ensure start and count have valid values
74680         var length = nodes.length;
74681         if (start === undefined || start < 0) {
74682             start = 0;
74683         }
74684         if (count === undefined || count > length - start) {
74685             count = length - start;
74686         }
74687         if (start > 0 || count < length) {
74688             // If we are not visiting all of the original nodes, we must always create a new array.
74689             // Since this is a fragment of a node array, we do not copy over the previous location
74690             // and will only copy over `hasTrailingComma` if we are including the last element.
74691             updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
74692         }
74693         // Visit each original node.
74694         for (var i = 0; i < count; i++) {
74695             var node = nodes[i + start];
74696             ts.aggregateTransformFlags(node);
74697             var visited = node !== undefined ? visitor(node) : undefined;
74698             if (updated !== undefined || visited === undefined || visited !== node) {
74699                 if (updated === undefined) {
74700                     // Ensure we have a copy of `nodes`, up to the current index.
74701                     updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
74702                     ts.setTextRange(updated, nodes);
74703                 }
74704                 if (visited) {
74705                     if (ts.isArray(visited)) {
74706                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
74707                             var visitedNode = visited_1[_i];
74708                             ts.Debug.assertNode(visitedNode, test);
74709                             ts.aggregateTransformFlags(visitedNode);
74710                             updated.push(visitedNode);
74711                         }
74712                     }
74713                     else {
74714                         ts.Debug.assertNode(visited, test);
74715                         ts.aggregateTransformFlags(visited);
74716                         updated.push(visited);
74717                     }
74718                 }
74719             }
74720         }
74721         return updated || nodes;
74722     }
74723     ts.visitNodes = visitNodes;
74724     /**
74725      * Starts a new lexical environment and visits a statement list, ending the lexical environment
74726      * and merging hoisted declarations upon completion.
74727      */
74728     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
74729         context.startLexicalEnvironment();
74730         statements = visitNodes(statements, visitor, ts.isStatement, start);
74731         if (ensureUseStrict)
74732             statements = ts.ensureUseStrict(statements); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
74733         return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
74734     }
74735     ts.visitLexicalEnvironment = visitLexicalEnvironment;
74736     function visitParameterList(nodes, visitor, context, nodesVisitor) {
74737         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74738         var updated;
74739         context.startLexicalEnvironment();
74740         if (nodes) {
74741             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
74742             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
74743             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
74744             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
74745             // that we might transform that introduces a temporary variable would fail as the temporary variable
74746             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
74747             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
74748             // when the emit target is greater than ES2015.
74749             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
74750                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
74751                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
74752             }
74753             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
74754         }
74755         context.suspendLexicalEnvironment();
74756         return updated;
74757     }
74758     ts.visitParameterList = visitParameterList;
74759     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
74760         var result;
74761         for (var i = 0; i < parameters.length; i++) {
74762             var parameter = parameters[i];
74763             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
74764             if (result || updated !== parameter) {
74765                 if (!result)
74766                     result = parameters.slice(0, i);
74767                 result[i] = updated;
74768             }
74769         }
74770         if (result) {
74771             return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters);
74772         }
74773         return parameters;
74774     }
74775     function addDefaultValueAssignmentIfNeeded(parameter, context) {
74776         // A rest parameter cannot have a binding pattern or an initializer,
74777         // so let's just ignore it.
74778         return parameter.dotDotDotToken ? parameter :
74779             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
74780                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
74781                     parameter;
74782     }
74783     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
74784         context.addInitializationStatement(ts.createVariableStatement(
74785         /*modifiers*/ undefined, ts.createVariableDeclarationList([
74786             ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ?
74787                 ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) :
74788                 ts.getGeneratedNameForNode(parameter)),
74789         ])));
74790         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
74791         /*initializer*/ undefined);
74792     }
74793     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
74794         context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
74795             ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
74796         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
74797         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
74798         /*initializer*/ undefined);
74799     }
74800     function visitFunctionBody(node, visitor, context) {
74801         context.resumeLexicalEnvironment();
74802         var updated = visitNode(node, visitor, ts.isConciseBody);
74803         var declarations = context.endLexicalEnvironment();
74804         if (ts.some(declarations)) {
74805             var block = ts.convertToFunctionBody(updated);
74806             var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
74807             return ts.updateBlock(block, statements);
74808         }
74809         return updated;
74810     }
74811     ts.visitFunctionBody = visitFunctionBody;
74812     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
74813         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74814         if (node === undefined) {
74815             return undefined;
74816         }
74817         var kind = node.kind;
74818         // No need to visit nodes with no children.
74819         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */) || kind === 183 /* ThisType */) {
74820             return node;
74821         }
74822         switch (kind) {
74823             // Names
74824             case 75 /* Identifier */:
74825                 return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
74826             case 153 /* QualifiedName */:
74827                 return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
74828             case 154 /* ComputedPropertyName */:
74829                 return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
74830             // Signature elements
74831             case 155 /* TypeParameter */:
74832                 return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
74833             case 156 /* Parameter */:
74834                 return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74835             case 157 /* Decorator */:
74836                 return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
74837             // Type elements
74838             case 158 /* PropertySignature */:
74839                 return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74840             case 159 /* PropertyDeclaration */:
74841                 return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), 
74842                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
74843                 visitNode(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74844             case 160 /* MethodSignature */:
74845                 return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken));
74846             case 161 /* MethodDeclaration */:
74847                 return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
74848             case 162 /* Constructor */:
74849                 return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
74850             case 163 /* GetAccessor */:
74851                 return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
74852             case 164 /* SetAccessor */:
74853                 return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
74854             case 165 /* CallSignature */:
74855                 return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74856             case 166 /* ConstructSignature */:
74857                 return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74858             case 167 /* IndexSignature */:
74859                 return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74860             // Types
74861             case 168 /* TypePredicate */:
74862                 return ts.updateTypePredicateNodeWithModifier(node, visitNode(node.assertsModifier, visitor), visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
74863             case 169 /* TypeReference */:
74864                 return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
74865             case 170 /* FunctionType */:
74866                 return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74867             case 171 /* ConstructorType */:
74868                 return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74869             case 172 /* TypeQuery */:
74870                 return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
74871             case 173 /* TypeLiteral */:
74872                 return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
74873             case 174 /* ArrayType */:
74874                 return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
74875             case 175 /* TupleType */:
74876                 return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
74877             case 176 /* OptionalType */:
74878                 return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74879             case 177 /* RestType */:
74880                 return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74881             case 178 /* UnionType */:
74882                 return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74883             case 179 /* IntersectionType */:
74884                 return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74885             case 180 /* ConditionalType */:
74886                 return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode));
74887             case 181 /* InferType */:
74888                 return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
74889             case 188 /* ImportType */:
74890                 return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
74891             case 182 /* ParenthesizedType */:
74892                 return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
74893             case 184 /* TypeOperator */:
74894                 return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74895             case 185 /* IndexedAccessType */:
74896                 return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
74897             case 186 /* MappedType */:
74898                 return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
74899             case 187 /* LiteralType */:
74900                 return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
74901             // Binding patterns
74902             case 189 /* ObjectBindingPattern */:
74903                 return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
74904             case 190 /* ArrayBindingPattern */:
74905                 return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
74906             case 191 /* BindingElement */:
74907                 return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression));
74908             // Expression
74909             case 192 /* ArrayLiteralExpression */:
74910                 return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
74911             case 193 /* ObjectLiteralExpression */:
74912                 return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
74913             case 194 /* PropertyAccessExpression */:
74914                 if (node.flags & 32 /* OptionalChain */) {
74915                     return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier));
74916                 }
74917                 return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
74918             case 195 /* ElementAccessExpression */:
74919                 if (node.flags & 32 /* OptionalChain */) {
74920                     return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression));
74921                 }
74922                 return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
74923             case 196 /* CallExpression */:
74924                 if (node.flags & 32 /* OptionalChain */) {
74925                     return ts.updateCallChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74926                 }
74927                 return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74928             case 197 /* NewExpression */:
74929                 return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74930             case 198 /* TaggedTemplateExpression */:
74931                 return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
74932             case 199 /* TypeAssertionExpression */:
74933                 return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74934             case 200 /* ParenthesizedExpression */:
74935                 return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
74936             case 201 /* FunctionExpression */:
74937                 return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
74938             case 202 /* ArrowFunction */:
74939                 return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context));
74940             case 203 /* DeleteExpression */:
74941                 return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
74942             case 204 /* TypeOfExpression */:
74943                 return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
74944             case 205 /* VoidExpression */:
74945                 return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
74946             case 206 /* AwaitExpression */:
74947                 return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
74948             case 207 /* PrefixUnaryExpression */:
74949                 return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
74950             case 208 /* PostfixUnaryExpression */:
74951                 return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
74952             case 209 /* BinaryExpression */:
74953                 return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, tokenVisitor, ts.isToken));
74954             case 210 /* ConditionalExpression */:
74955                 return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, tokenVisitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression));
74956             case 211 /* TemplateExpression */:
74957                 return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
74958             case 212 /* YieldExpression */:
74959                 return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
74960             case 213 /* SpreadElement */:
74961                 return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
74962             case 214 /* ClassExpression */:
74963                 return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
74964             case 216 /* ExpressionWithTypeArguments */:
74965                 return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74966             case 217 /* AsExpression */:
74967                 return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
74968             case 218 /* NonNullExpression */:
74969                 return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
74970             case 219 /* MetaProperty */:
74971                 return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
74972             // Misc
74973             case 221 /* TemplateSpan */:
74974                 return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
74975             // Element
74976             case 223 /* Block */:
74977                 return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
74978             case 225 /* VariableStatement */:
74979                 return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
74980             case 226 /* ExpressionStatement */:
74981                 return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
74982             case 227 /* IfStatement */:
74983                 return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock));
74984             case 228 /* DoStatement */:
74985                 return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
74986             case 229 /* WhileStatement */:
74987                 return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74988             case 230 /* ForStatement */:
74989                 return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74990             case 231 /* ForInStatement */:
74991                 return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74992             case 232 /* ForOfStatement */:
74993                 return ts.updateForOf(node, visitNode(node.awaitModifier, tokenVisitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74994             case 233 /* ContinueStatement */:
74995                 return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
74996             case 234 /* BreakStatement */:
74997                 return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
74998             case 235 /* ReturnStatement */:
74999                 return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
75000             case 236 /* WithStatement */:
75001                 return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75002             case 237 /* SwitchStatement */:
75003                 return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
75004             case 238 /* LabeledStatement */:
75005                 return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75006             case 239 /* ThrowStatement */:
75007                 return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
75008             case 240 /* TryStatement */:
75009                 return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
75010             case 242 /* VariableDeclaration */:
75011                 return ts.updateTypeScriptVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
75012             case 243 /* VariableDeclarationList */:
75013                 return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
75014             case 244 /* FunctionDeclaration */:
75015                 return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
75016             case 245 /* ClassDeclaration */:
75017                 return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
75018             case 246 /* InterfaceDeclaration */:
75019                 return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement));
75020             case 247 /* TypeAliasDeclaration */:
75021                 return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
75022             case 248 /* EnumDeclaration */:
75023                 return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember));
75024             case 249 /* ModuleDeclaration */:
75025                 return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody));
75026             case 250 /* ModuleBlock */:
75027                 return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75028             case 251 /* CaseBlock */:
75029                 return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
75030             case 252 /* NamespaceExportDeclaration */:
75031                 return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
75032             case 253 /* ImportEqualsDeclaration */:
75033                 return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference));
75034             case 254 /* ImportDeclaration */:
75035                 return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
75036             case 255 /* ImportClause */:
75037                 return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings), node.isTypeOnly);
75038             case 256 /* NamespaceImport */:
75039                 return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
75040             case 262 /* NamespaceExport */:
75041                 return ts.updateNamespaceExport(node, visitNode(node.name, visitor, ts.isIdentifier));
75042             case 257 /* NamedImports */:
75043                 return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
75044             case 258 /* ImportSpecifier */:
75045                 return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75046             case 259 /* ExportAssignment */:
75047                 return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
75048             case 260 /* ExportDeclaration */:
75049                 return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExportBindings), visitNode(node.moduleSpecifier, visitor, ts.isExpression), node.isTypeOnly);
75050             case 261 /* NamedExports */:
75051                 return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
75052             case 263 /* ExportSpecifier */:
75053                 return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75054             // Module references
75055             case 265 /* ExternalModuleReference */:
75056                 return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
75057             // JSX
75058             case 266 /* JsxElement */:
75059                 return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
75060             case 267 /* JsxSelfClosingElement */:
75061                 return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75062             case 268 /* JsxOpeningElement */:
75063                 return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75064             case 269 /* JsxClosingElement */:
75065                 return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
75066             case 270 /* JsxFragment */:
75067                 return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
75068             case 273 /* JsxAttribute */:
75069                 return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
75070             case 274 /* JsxAttributes */:
75071                 return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
75072             case 275 /* JsxSpreadAttribute */:
75073                 return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
75074             case 276 /* JsxExpression */:
75075                 return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75076             // Clauses
75077             case 277 /* CaseClause */:
75078                 return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
75079             case 278 /* DefaultClause */:
75080                 return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75081             case 279 /* HeritageClause */:
75082                 return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
75083             case 280 /* CatchClause */:
75084                 return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
75085             // Property assignments
75086             case 281 /* PropertyAssignment */:
75087                 return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75088             case 282 /* ShorthandPropertyAssignment */:
75089                 return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
75090             case 283 /* SpreadAssignment */:
75091                 return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
75092             // Enum
75093             case 284 /* EnumMember */:
75094                 return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75095             // Top-level nodes
75096             case 290 /* SourceFile */:
75097                 return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
75098             // Transformation nodes
75099             case 326 /* PartiallyEmittedExpression */:
75100                 return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75101             case 327 /* CommaListExpression */:
75102                 return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
75103             default:
75104                 // No need to visit nodes with no children.
75105                 return node;
75106         }
75107     }
75108     ts.visitEachChild = visitEachChild;
75109     /**
75110      * Extracts the single node from a NodeArray.
75111      *
75112      * @param nodes The NodeArray.
75113      */
75114     function extractSingleNode(nodes) {
75115         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
75116         return ts.singleOrUndefined(nodes);
75117     }
75118 })(ts || (ts = {}));
75119 /* @internal */
75120 var ts;
75121 (function (ts) {
75122     function reduceNode(node, f, initial) {
75123         return node ? f(initial, node) : initial;
75124     }
75125     function reduceNodeArray(nodes, f, initial) {
75126         return nodes ? f(initial, nodes) : initial;
75127     }
75128     /**
75129      * Similar to `reduceLeft`, performs a reduction against each child of a node.
75130      * NOTE: Unlike `forEachChild`, this does *not* visit every node.
75131      *
75132      * @param node The node containing the children to reduce.
75133      * @param initial The initial value to supply to the reduction.
75134      * @param f The callback function
75135      */
75136     function reduceEachChild(node, initial, cbNode, cbNodeArray) {
75137         if (node === undefined) {
75138             return initial;
75139         }
75140         var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
75141         var cbNodes = cbNodeArray || cbNode;
75142         var kind = node.kind;
75143         // No need to visit nodes with no children.
75144         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */)) {
75145             return initial;
75146         }
75147         // We do not yet support types.
75148         if ((kind >= 168 /* TypePredicate */ && kind <= 187 /* LiteralType */)) {
75149             return initial;
75150         }
75151         var result = initial;
75152         switch (node.kind) {
75153             // Leaf nodes
75154             case 222 /* SemicolonClassElement */:
75155             case 224 /* EmptyStatement */:
75156             case 215 /* OmittedExpression */:
75157             case 241 /* DebuggerStatement */:
75158             case 325 /* NotEmittedStatement */:
75159                 // No need to visit nodes with no children.
75160                 break;
75161             // Names
75162             case 153 /* QualifiedName */:
75163                 result = reduceNode(node.left, cbNode, result);
75164                 result = reduceNode(node.right, cbNode, result);
75165                 break;
75166             case 154 /* ComputedPropertyName */:
75167                 result = reduceNode(node.expression, cbNode, result);
75168                 break;
75169             // Signature elements
75170             case 156 /* Parameter */:
75171                 result = reduceNodes(node.decorators, cbNodes, result);
75172                 result = reduceNodes(node.modifiers, cbNodes, result);
75173                 result = reduceNode(node.name, cbNode, result);
75174                 result = reduceNode(node.type, cbNode, result);
75175                 result = reduceNode(node.initializer, cbNode, result);
75176                 break;
75177             case 157 /* Decorator */:
75178                 result = reduceNode(node.expression, cbNode, result);
75179                 break;
75180             // Type member
75181             case 158 /* PropertySignature */:
75182                 result = reduceNodes(node.modifiers, cbNodes, result);
75183                 result = reduceNode(node.name, cbNode, result);
75184                 result = reduceNode(node.questionToken, cbNode, result);
75185                 result = reduceNode(node.type, cbNode, result);
75186                 result = reduceNode(node.initializer, cbNode, result);
75187                 break;
75188             case 159 /* PropertyDeclaration */:
75189                 result = reduceNodes(node.decorators, cbNodes, result);
75190                 result = reduceNodes(node.modifiers, cbNodes, result);
75191                 result = reduceNode(node.name, cbNode, result);
75192                 result = reduceNode(node.type, cbNode, result);
75193                 result = reduceNode(node.initializer, cbNode, result);
75194                 break;
75195             case 161 /* MethodDeclaration */:
75196                 result = reduceNodes(node.decorators, cbNodes, result);
75197                 result = reduceNodes(node.modifiers, cbNodes, result);
75198                 result = reduceNode(node.name, cbNode, result);
75199                 result = reduceNodes(node.typeParameters, cbNodes, result);
75200                 result = reduceNodes(node.parameters, cbNodes, result);
75201                 result = reduceNode(node.type, cbNode, result);
75202                 result = reduceNode(node.body, cbNode, result);
75203                 break;
75204             case 162 /* Constructor */:
75205                 result = reduceNodes(node.modifiers, cbNodes, result);
75206                 result = reduceNodes(node.parameters, cbNodes, result);
75207                 result = reduceNode(node.body, cbNode, result);
75208                 break;
75209             case 163 /* GetAccessor */:
75210                 result = reduceNodes(node.decorators, cbNodes, result);
75211                 result = reduceNodes(node.modifiers, cbNodes, result);
75212                 result = reduceNode(node.name, cbNode, result);
75213                 result = reduceNodes(node.parameters, cbNodes, result);
75214                 result = reduceNode(node.type, cbNode, result);
75215                 result = reduceNode(node.body, cbNode, result);
75216                 break;
75217             case 164 /* SetAccessor */:
75218                 result = reduceNodes(node.decorators, cbNodes, result);
75219                 result = reduceNodes(node.modifiers, cbNodes, result);
75220                 result = reduceNode(node.name, cbNode, result);
75221                 result = reduceNodes(node.parameters, cbNodes, result);
75222                 result = reduceNode(node.body, cbNode, result);
75223                 break;
75224             // Binding patterns
75225             case 189 /* ObjectBindingPattern */:
75226             case 190 /* ArrayBindingPattern */:
75227                 result = reduceNodes(node.elements, cbNodes, result);
75228                 break;
75229             case 191 /* BindingElement */:
75230                 result = reduceNode(node.propertyName, cbNode, result);
75231                 result = reduceNode(node.name, cbNode, result);
75232                 result = reduceNode(node.initializer, cbNode, result);
75233                 break;
75234             // Expression
75235             case 192 /* ArrayLiteralExpression */:
75236                 result = reduceNodes(node.elements, cbNodes, result);
75237                 break;
75238             case 193 /* ObjectLiteralExpression */:
75239                 result = reduceNodes(node.properties, cbNodes, result);
75240                 break;
75241             case 194 /* PropertyAccessExpression */:
75242                 result = reduceNode(node.expression, cbNode, result);
75243                 result = reduceNode(node.name, cbNode, result);
75244                 break;
75245             case 195 /* ElementAccessExpression */:
75246                 result = reduceNode(node.expression, cbNode, result);
75247                 result = reduceNode(node.argumentExpression, cbNode, result);
75248                 break;
75249             case 196 /* CallExpression */:
75250                 result = reduceNode(node.expression, cbNode, result);
75251                 result = reduceNodes(node.typeArguments, cbNodes, result);
75252                 result = reduceNodes(node.arguments, cbNodes, result);
75253                 break;
75254             case 197 /* NewExpression */:
75255                 result = reduceNode(node.expression, cbNode, result);
75256                 result = reduceNodes(node.typeArguments, cbNodes, result);
75257                 result = reduceNodes(node.arguments, cbNodes, result);
75258                 break;
75259             case 198 /* TaggedTemplateExpression */:
75260                 result = reduceNode(node.tag, cbNode, result);
75261                 result = reduceNodes(node.typeArguments, cbNodes, result);
75262                 result = reduceNode(node.template, cbNode, result);
75263                 break;
75264             case 199 /* TypeAssertionExpression */:
75265                 result = reduceNode(node.type, cbNode, result);
75266                 result = reduceNode(node.expression, cbNode, result);
75267                 break;
75268             case 201 /* FunctionExpression */:
75269                 result = reduceNodes(node.modifiers, cbNodes, result);
75270                 result = reduceNode(node.name, cbNode, result);
75271                 result = reduceNodes(node.typeParameters, cbNodes, result);
75272                 result = reduceNodes(node.parameters, cbNodes, result);
75273                 result = reduceNode(node.type, cbNode, result);
75274                 result = reduceNode(node.body, cbNode, result);
75275                 break;
75276             case 202 /* ArrowFunction */:
75277                 result = reduceNodes(node.modifiers, cbNodes, result);
75278                 result = reduceNodes(node.typeParameters, cbNodes, result);
75279                 result = reduceNodes(node.parameters, cbNodes, result);
75280                 result = reduceNode(node.type, cbNode, result);
75281                 result = reduceNode(node.body, cbNode, result);
75282                 break;
75283             case 200 /* ParenthesizedExpression */:
75284             case 203 /* DeleteExpression */:
75285             case 204 /* TypeOfExpression */:
75286             case 205 /* VoidExpression */:
75287             case 206 /* AwaitExpression */:
75288             case 212 /* YieldExpression */:
75289             case 213 /* SpreadElement */:
75290             case 218 /* NonNullExpression */:
75291                 result = reduceNode(node.expression, cbNode, result);
75292                 break;
75293             case 207 /* PrefixUnaryExpression */:
75294             case 208 /* PostfixUnaryExpression */:
75295                 result = reduceNode(node.operand, cbNode, result);
75296                 break;
75297             case 209 /* BinaryExpression */:
75298                 result = reduceNode(node.left, cbNode, result);
75299                 result = reduceNode(node.right, cbNode, result);
75300                 break;
75301             case 210 /* ConditionalExpression */:
75302                 result = reduceNode(node.condition, cbNode, result);
75303                 result = reduceNode(node.whenTrue, cbNode, result);
75304                 result = reduceNode(node.whenFalse, cbNode, result);
75305                 break;
75306             case 211 /* TemplateExpression */:
75307                 result = reduceNode(node.head, cbNode, result);
75308                 result = reduceNodes(node.templateSpans, cbNodes, result);
75309                 break;
75310             case 214 /* ClassExpression */:
75311                 result = reduceNodes(node.modifiers, cbNodes, result);
75312                 result = reduceNode(node.name, cbNode, result);
75313                 result = reduceNodes(node.typeParameters, cbNodes, result);
75314                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75315                 result = reduceNodes(node.members, cbNodes, result);
75316                 break;
75317             case 216 /* ExpressionWithTypeArguments */:
75318                 result = reduceNode(node.expression, cbNode, result);
75319                 result = reduceNodes(node.typeArguments, cbNodes, result);
75320                 break;
75321             case 217 /* AsExpression */:
75322                 result = reduceNode(node.expression, cbNode, result);
75323                 result = reduceNode(node.type, cbNode, result);
75324                 break;
75325             // Misc
75326             case 221 /* TemplateSpan */:
75327                 result = reduceNode(node.expression, cbNode, result);
75328                 result = reduceNode(node.literal, cbNode, result);
75329                 break;
75330             // Element
75331             case 223 /* Block */:
75332                 result = reduceNodes(node.statements, cbNodes, result);
75333                 break;
75334             case 225 /* VariableStatement */:
75335                 result = reduceNodes(node.modifiers, cbNodes, result);
75336                 result = reduceNode(node.declarationList, cbNode, result);
75337                 break;
75338             case 226 /* ExpressionStatement */:
75339                 result = reduceNode(node.expression, cbNode, result);
75340                 break;
75341             case 227 /* IfStatement */:
75342                 result = reduceNode(node.expression, cbNode, result);
75343                 result = reduceNode(node.thenStatement, cbNode, result);
75344                 result = reduceNode(node.elseStatement, cbNode, result);
75345                 break;
75346             case 228 /* DoStatement */:
75347                 result = reduceNode(node.statement, cbNode, result);
75348                 result = reduceNode(node.expression, cbNode, result);
75349                 break;
75350             case 229 /* WhileStatement */:
75351             case 236 /* WithStatement */:
75352                 result = reduceNode(node.expression, cbNode, result);
75353                 result = reduceNode(node.statement, cbNode, result);
75354                 break;
75355             case 230 /* ForStatement */:
75356                 result = reduceNode(node.initializer, cbNode, result);
75357                 result = reduceNode(node.condition, cbNode, result);
75358                 result = reduceNode(node.incrementor, cbNode, result);
75359                 result = reduceNode(node.statement, cbNode, result);
75360                 break;
75361             case 231 /* ForInStatement */:
75362             case 232 /* ForOfStatement */:
75363                 result = reduceNode(node.initializer, cbNode, result);
75364                 result = reduceNode(node.expression, cbNode, result);
75365                 result = reduceNode(node.statement, cbNode, result);
75366                 break;
75367             case 235 /* ReturnStatement */:
75368             case 239 /* ThrowStatement */:
75369                 result = reduceNode(node.expression, cbNode, result);
75370                 break;
75371             case 237 /* SwitchStatement */:
75372                 result = reduceNode(node.expression, cbNode, result);
75373                 result = reduceNode(node.caseBlock, cbNode, result);
75374                 break;
75375             case 238 /* LabeledStatement */:
75376                 result = reduceNode(node.label, cbNode, result);
75377                 result = reduceNode(node.statement, cbNode, result);
75378                 break;
75379             case 240 /* TryStatement */:
75380                 result = reduceNode(node.tryBlock, cbNode, result);
75381                 result = reduceNode(node.catchClause, cbNode, result);
75382                 result = reduceNode(node.finallyBlock, cbNode, result);
75383                 break;
75384             case 242 /* VariableDeclaration */:
75385                 result = reduceNode(node.name, cbNode, result);
75386                 result = reduceNode(node.type, cbNode, result);
75387                 result = reduceNode(node.initializer, cbNode, result);
75388                 break;
75389             case 243 /* VariableDeclarationList */:
75390                 result = reduceNodes(node.declarations, cbNodes, result);
75391                 break;
75392             case 244 /* FunctionDeclaration */:
75393                 result = reduceNodes(node.decorators, cbNodes, result);
75394                 result = reduceNodes(node.modifiers, cbNodes, result);
75395                 result = reduceNode(node.name, cbNode, result);
75396                 result = reduceNodes(node.typeParameters, cbNodes, result);
75397                 result = reduceNodes(node.parameters, cbNodes, result);
75398                 result = reduceNode(node.type, cbNode, result);
75399                 result = reduceNode(node.body, cbNode, result);
75400                 break;
75401             case 245 /* ClassDeclaration */:
75402                 result = reduceNodes(node.decorators, cbNodes, result);
75403                 result = reduceNodes(node.modifiers, cbNodes, result);
75404                 result = reduceNode(node.name, cbNode, result);
75405                 result = reduceNodes(node.typeParameters, cbNodes, result);
75406                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75407                 result = reduceNodes(node.members, cbNodes, result);
75408                 break;
75409             case 248 /* EnumDeclaration */:
75410                 result = reduceNodes(node.decorators, cbNodes, result);
75411                 result = reduceNodes(node.modifiers, cbNodes, result);
75412                 result = reduceNode(node.name, cbNode, result);
75413                 result = reduceNodes(node.members, cbNodes, result);
75414                 break;
75415             case 249 /* ModuleDeclaration */:
75416                 result = reduceNodes(node.decorators, cbNodes, result);
75417                 result = reduceNodes(node.modifiers, cbNodes, result);
75418                 result = reduceNode(node.name, cbNode, result);
75419                 result = reduceNode(node.body, cbNode, result);
75420                 break;
75421             case 250 /* ModuleBlock */:
75422                 result = reduceNodes(node.statements, cbNodes, result);
75423                 break;
75424             case 251 /* CaseBlock */:
75425                 result = reduceNodes(node.clauses, cbNodes, result);
75426                 break;
75427             case 253 /* ImportEqualsDeclaration */:
75428                 result = reduceNodes(node.decorators, cbNodes, result);
75429                 result = reduceNodes(node.modifiers, cbNodes, result);
75430                 result = reduceNode(node.name, cbNode, result);
75431                 result = reduceNode(node.moduleReference, cbNode, result);
75432                 break;
75433             case 254 /* ImportDeclaration */:
75434                 result = reduceNodes(node.decorators, cbNodes, result);
75435                 result = reduceNodes(node.modifiers, cbNodes, result);
75436                 result = reduceNode(node.importClause, cbNode, result);
75437                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75438                 break;
75439             case 255 /* ImportClause */:
75440                 result = reduceNode(node.name, cbNode, result);
75441                 result = reduceNode(node.namedBindings, cbNode, result);
75442                 break;
75443             case 256 /* NamespaceImport */:
75444                 result = reduceNode(node.name, cbNode, result);
75445                 break;
75446             case 262 /* NamespaceExport */:
75447                 result = reduceNode(node.name, cbNode, result);
75448                 break;
75449             case 257 /* NamedImports */:
75450             case 261 /* NamedExports */:
75451                 result = reduceNodes(node.elements, cbNodes, result);
75452                 break;
75453             case 258 /* ImportSpecifier */:
75454             case 263 /* ExportSpecifier */:
75455                 result = reduceNode(node.propertyName, cbNode, result);
75456                 result = reduceNode(node.name, cbNode, result);
75457                 break;
75458             case 259 /* ExportAssignment */:
75459                 result = ts.reduceLeft(node.decorators, cbNode, result);
75460                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75461                 result = reduceNode(node.expression, cbNode, result);
75462                 break;
75463             case 260 /* ExportDeclaration */:
75464                 result = ts.reduceLeft(node.decorators, cbNode, result);
75465                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75466                 result = reduceNode(node.exportClause, cbNode, result);
75467                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75468                 break;
75469             // Module references
75470             case 265 /* ExternalModuleReference */:
75471                 result = reduceNode(node.expression, cbNode, result);
75472                 break;
75473             // JSX
75474             case 266 /* JsxElement */:
75475                 result = reduceNode(node.openingElement, cbNode, result);
75476                 result = ts.reduceLeft(node.children, cbNode, result);
75477                 result = reduceNode(node.closingElement, cbNode, result);
75478                 break;
75479             case 270 /* JsxFragment */:
75480                 result = reduceNode(node.openingFragment, cbNode, result);
75481                 result = ts.reduceLeft(node.children, cbNode, result);
75482                 result = reduceNode(node.closingFragment, cbNode, result);
75483                 break;
75484             case 267 /* JsxSelfClosingElement */:
75485             case 268 /* JsxOpeningElement */:
75486                 result = reduceNode(node.tagName, cbNode, result);
75487                 result = reduceNodes(node.typeArguments, cbNode, result);
75488                 result = reduceNode(node.attributes, cbNode, result);
75489                 break;
75490             case 274 /* JsxAttributes */:
75491                 result = reduceNodes(node.properties, cbNodes, result);
75492                 break;
75493             case 269 /* JsxClosingElement */:
75494                 result = reduceNode(node.tagName, cbNode, result);
75495                 break;
75496             case 273 /* JsxAttribute */:
75497                 result = reduceNode(node.name, cbNode, result);
75498                 result = reduceNode(node.initializer, cbNode, result);
75499                 break;
75500             case 275 /* JsxSpreadAttribute */:
75501                 result = reduceNode(node.expression, cbNode, result);
75502                 break;
75503             case 276 /* JsxExpression */:
75504                 result = reduceNode(node.expression, cbNode, result);
75505                 break;
75506             // Clauses
75507             case 277 /* CaseClause */:
75508                 result = reduceNode(node.expression, cbNode, result);
75509             // falls through
75510             case 278 /* DefaultClause */:
75511                 result = reduceNodes(node.statements, cbNodes, result);
75512                 break;
75513             case 279 /* HeritageClause */:
75514                 result = reduceNodes(node.types, cbNodes, result);
75515                 break;
75516             case 280 /* CatchClause */:
75517                 result = reduceNode(node.variableDeclaration, cbNode, result);
75518                 result = reduceNode(node.block, cbNode, result);
75519                 break;
75520             // Property assignments
75521             case 281 /* PropertyAssignment */:
75522                 result = reduceNode(node.name, cbNode, result);
75523                 result = reduceNode(node.initializer, cbNode, result);
75524                 break;
75525             case 282 /* ShorthandPropertyAssignment */:
75526                 result = reduceNode(node.name, cbNode, result);
75527                 result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
75528                 break;
75529             case 283 /* SpreadAssignment */:
75530                 result = reduceNode(node.expression, cbNode, result);
75531                 break;
75532             // Enum
75533             case 284 /* EnumMember */:
75534                 result = reduceNode(node.name, cbNode, result);
75535                 result = reduceNode(node.initializer, cbNode, result);
75536                 break;
75537             // Top-level nodes
75538             case 290 /* SourceFile */:
75539                 result = reduceNodes(node.statements, cbNodes, result);
75540                 break;
75541             // Transformation nodes
75542             case 326 /* PartiallyEmittedExpression */:
75543                 result = reduceNode(node.expression, cbNode, result);
75544                 break;
75545             case 327 /* CommaListExpression */:
75546                 result = reduceNodes(node.elements, cbNodes, result);
75547                 break;
75548             default:
75549                 break;
75550         }
75551         return result;
75552     }
75553     ts.reduceEachChild = reduceEachChild;
75554     function findSpanEnd(array, test, start) {
75555         var i = start;
75556         while (i < array.length && test(array[i])) {
75557             i++;
75558         }
75559         return i;
75560     }
75561     function mergeLexicalEnvironment(statements, declarations) {
75562         if (!ts.some(declarations)) {
75563             return statements;
75564         }
75565         // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
75566         //
75567         // Given:
75568         //
75569         // | Left                               | Right                               |
75570         // |------------------------------------|-------------------------------------|
75571         // | [standard prologues (left)]        | [standard prologues (right)]        |
75572         // | [hoisted functions (left)]         | [hoisted functions (right)]         |
75573         // | [hoisted variables (left)]         | [hoisted variables (right)]         |
75574         // | [lexical init statements (left)]   | [lexical init statements (right)]   |
75575         // | [other statements (left)]          |                                     |
75576         //
75577         // The resulting statement list will be:
75578         //
75579         // | Result                              |
75580         // |-------------------------------------|
75581         // | [standard prologues (right)]        |
75582         // | [standard prologues (left)]         |
75583         // | [hoisted functions (right)]         |
75584         // | [hoisted functions (left)]          |
75585         // | [hoisted variables (right)]         |
75586         // | [hoisted variables (left)]          |
75587         // | [lexical init statements (right)]   |
75588         // | [lexical init statements (left)]    |
75589         // | [other statements (left)]           |
75590         //
75591         // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
75592         // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
75593         // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
75594         var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
75595         var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
75596         var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
75597         // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
75598         var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
75599         var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
75600         var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
75601         var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
75602         ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
75603         // splice prologues from the right into the left. We do this in reverse order
75604         // so that we don't need to recompute the index on the left when we insert items.
75605         var left = ts.isNodeArray(statements) ? statements.slice() : statements;
75606         // splice other custom prologues from right into left
75607         if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
75608             left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
75609         }
75610         // splice hoisted variables from right into left
75611         if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
75612             left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
75613         }
75614         // splice hoisted functions from right into left
75615         if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
75616             left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
75617         }
75618         // splice standard prologues from right into left (that are not already in left)
75619         if (rightStandardPrologueEnd > 0) {
75620             if (leftStandardPrologueEnd === 0) {
75621                 left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
75622             }
75623             else {
75624                 var leftPrologues = ts.createMap();
75625                 for (var i = 0; i < leftStandardPrologueEnd; i++) {
75626                     var leftPrologue = statements[i];
75627                     leftPrologues.set(leftPrologue.expression.text, true);
75628                 }
75629                 for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
75630                     var rightPrologue = declarations[i];
75631                     if (!leftPrologues.has(rightPrologue.expression.text)) {
75632                         left.unshift(rightPrologue);
75633                     }
75634                 }
75635             }
75636         }
75637         if (ts.isNodeArray(statements)) {
75638             return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements);
75639         }
75640         return statements;
75641     }
75642     ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
75643     /**
75644      * Lifts a NodeArray containing only Statement nodes to a block.
75645      *
75646      * @param nodes The NodeArray.
75647      */
75648     function liftToBlock(nodes) {
75649         ts.Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
75650         return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
75651     }
75652     ts.liftToBlock = liftToBlock;
75653     /**
75654      * Aggregates the TransformFlags for a Node and its subtree.
75655      */
75656     function aggregateTransformFlags(node) {
75657         aggregateTransformFlagsForNode(node);
75658         return node;
75659     }
75660     ts.aggregateTransformFlags = aggregateTransformFlags;
75661     /**
75662      * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
75663      * computed first, then the transform flags for the current node are computed from the subtree
75664      * flags and the state of the current node. Finally, the transform flags of the node are
75665      * returned, excluding any flags that should not be included in its parent node's subtree
75666      * flags.
75667      */
75668     function aggregateTransformFlagsForNode(node) {
75669         if (node === undefined) {
75670             return 0 /* None */;
75671         }
75672         if (node.transformFlags & 536870912 /* HasComputedFlags */) {
75673             return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
75674         }
75675         var subtreeFlags = aggregateTransformFlagsForSubtree(node);
75676         return ts.computeTransformFlagsForNode(node, subtreeFlags);
75677     }
75678     function aggregateTransformFlagsForNodeArray(nodes) {
75679         if (nodes === undefined) {
75680             return 0 /* None */;
75681         }
75682         var subtreeFlags = 0 /* None */;
75683         var nodeArrayFlags = 0 /* None */;
75684         for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
75685             var node = nodes_3[_i];
75686             subtreeFlags |= aggregateTransformFlagsForNode(node);
75687             nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
75688         }
75689         nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
75690         return subtreeFlags;
75691     }
75692     /**
75693      * Aggregates the transform flags for the subtree of a node.
75694      */
75695     function aggregateTransformFlagsForSubtree(node) {
75696         // We do not transform ambient declarations or types, so there is no need to
75697         // recursively aggregate transform flags.
75698         if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 216 /* ExpressionWithTypeArguments */)) {
75699             return 0 /* None */;
75700         }
75701         // Aggregate the transform flags of each child.
75702         return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
75703     }
75704     /**
75705      * Aggregates the TransformFlags of a child node with the TransformFlags of its
75706      * siblings.
75707      */
75708     function aggregateTransformFlagsForChildNode(transformFlags, node) {
75709         return transformFlags | aggregateTransformFlagsForNode(node);
75710     }
75711     function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
75712         return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
75713     }
75714 })(ts || (ts = {}));
75715 /* @internal */
75716 var ts;
75717 (function (ts) {
75718     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
75719         var _a = generatorOptions.extendedDiagnostics
75720             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
75721             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
75722         // Current source map file and its index in the sources list
75723         var rawSources = [];
75724         var sources = [];
75725         var sourceToSourceIndexMap = ts.createMap();
75726         var sourcesContent;
75727         var names = [];
75728         var nameToNameIndexMap;
75729         var mappings = "";
75730         // Last recorded and encoded mappings
75731         var lastGeneratedLine = 0;
75732         var lastGeneratedCharacter = 0;
75733         var lastSourceIndex = 0;
75734         var lastSourceLine = 0;
75735         var lastSourceCharacter = 0;
75736         var lastNameIndex = 0;
75737         var hasLast = false;
75738         var pendingGeneratedLine = 0;
75739         var pendingGeneratedCharacter = 0;
75740         var pendingSourceIndex = 0;
75741         var pendingSourceLine = 0;
75742         var pendingSourceCharacter = 0;
75743         var pendingNameIndex = 0;
75744         var hasPending = false;
75745         var hasPendingSource = false;
75746         var hasPendingName = false;
75747         return {
75748             getSources: function () { return rawSources; },
75749             addSource: addSource,
75750             setSourceContent: setSourceContent,
75751             addName: addName,
75752             addMapping: addMapping,
75753             appendSourceMap: appendSourceMap,
75754             toJSON: toJSON,
75755             toString: function () { return JSON.stringify(toJSON()); }
75756         };
75757         function addSource(fileName) {
75758             enter();
75759             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
75760             /*isAbsolutePathAnUrl*/ true);
75761             var sourceIndex = sourceToSourceIndexMap.get(source);
75762             if (sourceIndex === undefined) {
75763                 sourceIndex = sources.length;
75764                 sources.push(source);
75765                 rawSources.push(fileName);
75766                 sourceToSourceIndexMap.set(source, sourceIndex);
75767             }
75768             exit();
75769             return sourceIndex;
75770         }
75771         /* eslint-disable boolean-trivia, no-null/no-null */
75772         function setSourceContent(sourceIndex, content) {
75773             enter();
75774             if (content !== null) {
75775                 if (!sourcesContent)
75776                     sourcesContent = [];
75777                 while (sourcesContent.length < sourceIndex) {
75778                     sourcesContent.push(null);
75779                 }
75780                 sourcesContent[sourceIndex] = content;
75781             }
75782             exit();
75783         }
75784         /* eslint-enable boolean-trivia, no-null/no-null */
75785         function addName(name) {
75786             enter();
75787             if (!nameToNameIndexMap)
75788                 nameToNameIndexMap = ts.createMap();
75789             var nameIndex = nameToNameIndexMap.get(name);
75790             if (nameIndex === undefined) {
75791                 nameIndex = names.length;
75792                 names.push(name);
75793                 nameToNameIndexMap.set(name, nameIndex);
75794             }
75795             exit();
75796             return nameIndex;
75797         }
75798         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
75799             return !hasPending
75800                 || pendingGeneratedLine !== generatedLine
75801                 || pendingGeneratedCharacter !== generatedCharacter;
75802         }
75803         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
75804             return sourceIndex !== undefined
75805                 && sourceLine !== undefined
75806                 && sourceCharacter !== undefined
75807                 && pendingSourceIndex === sourceIndex
75808                 && (pendingSourceLine > sourceLine
75809                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
75810         }
75811         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
75812             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75813             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75814             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
75815             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
75816             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
75817             enter();
75818             // If this location wasn't recorded or the location in source is going backwards, record the mapping
75819             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
75820                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
75821                 commitPendingMapping();
75822                 pendingGeneratedLine = generatedLine;
75823                 pendingGeneratedCharacter = generatedCharacter;
75824                 hasPendingSource = false;
75825                 hasPendingName = false;
75826                 hasPending = true;
75827             }
75828             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
75829                 pendingSourceIndex = sourceIndex;
75830                 pendingSourceLine = sourceLine;
75831                 pendingSourceCharacter = sourceCharacter;
75832                 hasPendingSource = true;
75833                 if (nameIndex !== undefined) {
75834                     pendingNameIndex = nameIndex;
75835                     hasPendingName = true;
75836                 }
75837             }
75838             exit();
75839         }
75840         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
75841             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75842             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75843             enter();
75844             // First, decode the old component sourcemap
75845             var sourceIndexToNewSourceIndexMap = [];
75846             var nameIndexToNewNameIndexMap;
75847             var mappingIterator = decodeMappings(map.mappings);
75848             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
75849                 var raw = iterResult.value;
75850                 if (end && (raw.generatedLine > end.line ||
75851                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
75852                     break;
75853                 }
75854                 if (start && (raw.generatedLine < start.line ||
75855                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
75856                     continue;
75857                 }
75858                 // Then reencode all the updated mappings into the overall map
75859                 var newSourceIndex = void 0;
75860                 var newSourceLine = void 0;
75861                 var newSourceCharacter = void 0;
75862                 var newNameIndex = void 0;
75863                 if (raw.sourceIndex !== undefined) {
75864                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
75865                     if (newSourceIndex === undefined) {
75866                         // Apply offsets to each position and fixup source entries
75867                         var rawPath = map.sources[raw.sourceIndex];
75868                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
75869                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
75870                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
75871                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
75872                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
75873                         }
75874                     }
75875                     newSourceLine = raw.sourceLine;
75876                     newSourceCharacter = raw.sourceCharacter;
75877                     if (map.names && raw.nameIndex !== undefined) {
75878                         if (!nameIndexToNewNameIndexMap)
75879                             nameIndexToNewNameIndexMap = [];
75880                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
75881                         if (newNameIndex === undefined) {
75882                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
75883                         }
75884                     }
75885                 }
75886                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
75887                 var newGeneratedLine = rawGeneratedLine + generatedLine;
75888                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
75889                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
75890                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
75891             }
75892             exit();
75893         }
75894         function shouldCommitMapping() {
75895             return !hasLast
75896                 || lastGeneratedLine !== pendingGeneratedLine
75897                 || lastGeneratedCharacter !== pendingGeneratedCharacter
75898                 || lastSourceIndex !== pendingSourceIndex
75899                 || lastSourceLine !== pendingSourceLine
75900                 || lastSourceCharacter !== pendingSourceCharacter
75901                 || lastNameIndex !== pendingNameIndex;
75902         }
75903         function commitPendingMapping() {
75904             if (!hasPending || !shouldCommitMapping()) {
75905                 return;
75906             }
75907             enter();
75908             // Line/Comma delimiters
75909             if (lastGeneratedLine < pendingGeneratedLine) {
75910                 // Emit line delimiters
75911                 do {
75912                     mappings += ";";
75913                     lastGeneratedLine++;
75914                     lastGeneratedCharacter = 0;
75915                 } while (lastGeneratedLine < pendingGeneratedLine);
75916             }
75917             else {
75918                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
75919                 // Emit comma to separate the entry
75920                 if (hasLast) {
75921                     mappings += ",";
75922                 }
75923             }
75924             // 1. Relative generated character
75925             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
75926             lastGeneratedCharacter = pendingGeneratedCharacter;
75927             if (hasPendingSource) {
75928                 // 2. Relative sourceIndex
75929                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
75930                 lastSourceIndex = pendingSourceIndex;
75931                 // 3. Relative source line
75932                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
75933                 lastSourceLine = pendingSourceLine;
75934                 // 4. Relative source character
75935                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
75936                 lastSourceCharacter = pendingSourceCharacter;
75937                 if (hasPendingName) {
75938                     // 5. Relative nameIndex
75939                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
75940                     lastNameIndex = pendingNameIndex;
75941                 }
75942             }
75943             hasLast = true;
75944             exit();
75945         }
75946         function toJSON() {
75947             commitPendingMapping();
75948             return {
75949                 version: 3,
75950                 file: file,
75951                 sourceRoot: sourceRoot,
75952                 sources: sources,
75953                 names: names,
75954                 mappings: mappings,
75955                 sourcesContent: sourcesContent,
75956             };
75957         }
75958     }
75959     ts.createSourceMapGenerator = createSourceMapGenerator;
75960     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
75961     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
75962     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
75963     function getLineInfo(text, lineStarts) {
75964         return {
75965             getLineCount: function () { return lineStarts.length; },
75966             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
75967         };
75968     }
75969     ts.getLineInfo = getLineInfo;
75970     /**
75971      * Tries to find the sourceMappingURL comment at the end of a file.
75972      */
75973     function tryGetSourceMappingURL(lineInfo) {
75974         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
75975             var line = lineInfo.getLineText(index);
75976             var comment = sourceMapCommentRegExp.exec(line);
75977             if (comment) {
75978                 return comment[1];
75979             }
75980             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
75981             else if (!line.match(whitespaceOrMapCommentRegExp)) {
75982                 break;
75983             }
75984         }
75985     }
75986     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
75987     /* eslint-disable no-null/no-null */
75988     function isStringOrNull(x) {
75989         return typeof x === "string" || x === null;
75990     }
75991     function isRawSourceMap(x) {
75992         return x !== null
75993             && typeof x === "object"
75994             && x.version === 3
75995             && typeof x.file === "string"
75996             && typeof x.mappings === "string"
75997             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
75998             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
75999             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
76000             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
76001     }
76002     ts.isRawSourceMap = isRawSourceMap;
76003     /* eslint-enable no-null/no-null */
76004     function tryParseRawSourceMap(text) {
76005         try {
76006             var parsed = JSON.parse(text);
76007             if (isRawSourceMap(parsed)) {
76008                 return parsed;
76009             }
76010         }
76011         catch (_a) {
76012             // empty
76013         }
76014         return undefined;
76015     }
76016     ts.tryParseRawSourceMap = tryParseRawSourceMap;
76017     function decodeMappings(mappings) {
76018         var done = false;
76019         var pos = 0;
76020         var generatedLine = 0;
76021         var generatedCharacter = 0;
76022         var sourceIndex = 0;
76023         var sourceLine = 0;
76024         var sourceCharacter = 0;
76025         var nameIndex = 0;
76026         var error;
76027         return {
76028             get pos() { return pos; },
76029             get error() { return error; },
76030             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
76031             next: function () {
76032                 while (!done && pos < mappings.length) {
76033                     var ch = mappings.charCodeAt(pos);
76034                     if (ch === 59 /* semicolon */) {
76035                         // new line
76036                         generatedLine++;
76037                         generatedCharacter = 0;
76038                         pos++;
76039                         continue;
76040                     }
76041                     if (ch === 44 /* comma */) {
76042                         // Next entry is on same line - no action needed
76043                         pos++;
76044                         continue;
76045                     }
76046                     var hasSource = false;
76047                     var hasName = false;
76048                     generatedCharacter += base64VLQFormatDecode();
76049                     if (hasReportedError())
76050                         return stopIterating();
76051                     if (generatedCharacter < 0)
76052                         return setErrorAndStopIterating("Invalid generatedCharacter found");
76053                     if (!isSourceMappingSegmentEnd()) {
76054                         hasSource = true;
76055                         sourceIndex += base64VLQFormatDecode();
76056                         if (hasReportedError())
76057                             return stopIterating();
76058                         if (sourceIndex < 0)
76059                             return setErrorAndStopIterating("Invalid sourceIndex found");
76060                         if (isSourceMappingSegmentEnd())
76061                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
76062                         sourceLine += base64VLQFormatDecode();
76063                         if (hasReportedError())
76064                             return stopIterating();
76065                         if (sourceLine < 0)
76066                             return setErrorAndStopIterating("Invalid sourceLine found");
76067                         if (isSourceMappingSegmentEnd())
76068                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
76069                         sourceCharacter += base64VLQFormatDecode();
76070                         if (hasReportedError())
76071                             return stopIterating();
76072                         if (sourceCharacter < 0)
76073                             return setErrorAndStopIterating("Invalid sourceCharacter found");
76074                         if (!isSourceMappingSegmentEnd()) {
76075                             hasName = true;
76076                             nameIndex += base64VLQFormatDecode();
76077                             if (hasReportedError())
76078                                 return stopIterating();
76079                             if (nameIndex < 0)
76080                                 return setErrorAndStopIterating("Invalid nameIndex found");
76081                             if (!isSourceMappingSegmentEnd())
76082                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
76083                         }
76084                     }
76085                     return { value: captureMapping(hasSource, hasName), done: done };
76086                 }
76087                 return stopIterating();
76088             }
76089         };
76090         function captureMapping(hasSource, hasName) {
76091             return {
76092                 generatedLine: generatedLine,
76093                 generatedCharacter: generatedCharacter,
76094                 sourceIndex: hasSource ? sourceIndex : undefined,
76095                 sourceLine: hasSource ? sourceLine : undefined,
76096                 sourceCharacter: hasSource ? sourceCharacter : undefined,
76097                 nameIndex: hasName ? nameIndex : undefined
76098             };
76099         }
76100         function stopIterating() {
76101             done = true;
76102             return { value: undefined, done: true };
76103         }
76104         function setError(message) {
76105             if (error === undefined) {
76106                 error = message;
76107             }
76108         }
76109         function setErrorAndStopIterating(message) {
76110             setError(message);
76111             return stopIterating();
76112         }
76113         function hasReportedError() {
76114             return error !== undefined;
76115         }
76116         function isSourceMappingSegmentEnd() {
76117             return (pos === mappings.length ||
76118                 mappings.charCodeAt(pos) === 44 /* comma */ ||
76119                 mappings.charCodeAt(pos) === 59 /* semicolon */);
76120         }
76121         function base64VLQFormatDecode() {
76122             var moreDigits = true;
76123             var shiftCount = 0;
76124             var value = 0;
76125             for (; moreDigits; pos++) {
76126                 if (pos >= mappings.length)
76127                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
76128                 // 6 digit number
76129                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
76130                 if (currentByte === -1)
76131                     return setError("Invalid character in VLQ"), -1;
76132                 // If msb is set, we still have more bits to continue
76133                 moreDigits = (currentByte & 32) !== 0;
76134                 // least significant 5 bits are the next msbs in the final value.
76135                 value = value | ((currentByte & 31) << shiftCount);
76136                 shiftCount += 5;
76137             }
76138             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
76139             if ((value & 1) === 0) {
76140                 // + number
76141                 value = value >> 1;
76142             }
76143             else {
76144                 // - number
76145                 value = value >> 1;
76146                 value = -value;
76147             }
76148             return value;
76149         }
76150     }
76151     ts.decodeMappings = decodeMappings;
76152     function sameMapping(left, right) {
76153         return left === right
76154             || left.generatedLine === right.generatedLine
76155                 && left.generatedCharacter === right.generatedCharacter
76156                 && left.sourceIndex === right.sourceIndex
76157                 && left.sourceLine === right.sourceLine
76158                 && left.sourceCharacter === right.sourceCharacter
76159                 && left.nameIndex === right.nameIndex;
76160     }
76161     ts.sameMapping = sameMapping;
76162     function isSourceMapping(mapping) {
76163         return mapping.sourceIndex !== undefined
76164             && mapping.sourceLine !== undefined
76165             && mapping.sourceCharacter !== undefined;
76166     }
76167     ts.isSourceMapping = isSourceMapping;
76168     function base64FormatEncode(value) {
76169         return value >= 0 && value < 26 ? 65 /* A */ + value :
76170             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
76171                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
76172                     value === 62 ? 43 /* plus */ :
76173                         value === 63 ? 47 /* slash */ :
76174                             ts.Debug.fail(value + ": not a base64 value");
76175     }
76176     function base64FormatDecode(ch) {
76177         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
76178             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
76179                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
76180                     ch === 43 /* plus */ ? 62 :
76181                         ch === 47 /* slash */ ? 63 :
76182                             -1;
76183     }
76184     function base64VLQFormatEncode(inValue) {
76185         // Add a new least significant bit that has the sign of the value.
76186         // if negative number the least significant bit that gets added to the number has value 1
76187         // else least significant bit value that gets added is 0
76188         // eg. -1 changes to binary : 01 [1] => 3
76189         //     +1 changes to binary : 01 [0] => 2
76190         if (inValue < 0) {
76191             inValue = ((-inValue) << 1) + 1;
76192         }
76193         else {
76194             inValue = inValue << 1;
76195         }
76196         // Encode 5 bits at a time starting from least significant bits
76197         var encodedStr = "";
76198         do {
76199             var currentDigit = inValue & 31; // 11111
76200             inValue = inValue >> 5;
76201             if (inValue > 0) {
76202                 // There are still more digits to decode, set the msb (6th bit)
76203                 currentDigit = currentDigit | 32;
76204             }
76205             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
76206         } while (inValue > 0);
76207         return encodedStr;
76208     }
76209     function isSourceMappedPosition(value) {
76210         return value.sourceIndex !== undefined
76211             && value.sourcePosition !== undefined;
76212     }
76213     function sameMappedPosition(left, right) {
76214         return left.generatedPosition === right.generatedPosition
76215             && left.sourceIndex === right.sourceIndex
76216             && left.sourcePosition === right.sourcePosition;
76217     }
76218     function compareSourcePositions(left, right) {
76219         // Compares sourcePosition without comparing sourceIndex
76220         // since the mappings are grouped by sourceIndex
76221         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
76222         return ts.compareValues(left.sourcePosition, right.sourcePosition);
76223     }
76224     function compareGeneratedPositions(left, right) {
76225         return ts.compareValues(left.generatedPosition, right.generatedPosition);
76226     }
76227     function getSourcePositionOfMapping(value) {
76228         return value.sourcePosition;
76229     }
76230     function getGeneratedPositionOfMapping(value) {
76231         return value.generatedPosition;
76232     }
76233     function createDocumentPositionMapper(host, map, mapPath) {
76234         var mapDirectory = ts.getDirectoryPath(mapPath);
76235         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
76236         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
76237         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
76238         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
76239         var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
76240         var decodedMappings;
76241         var generatedMappings;
76242         var sourceMappings;
76243         return {
76244             getSourcePosition: getSourcePosition,
76245             getGeneratedPosition: getGeneratedPosition
76246         };
76247         function processMapping(mapping) {
76248             var generatedPosition = generatedFile !== undefined
76249                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
76250                 : -1;
76251             var source;
76252             var sourcePosition;
76253             if (isSourceMapping(mapping)) {
76254                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
76255                 source = map.sources[mapping.sourceIndex];
76256                 sourcePosition = sourceFile !== undefined
76257                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
76258                     : -1;
76259             }
76260             return {
76261                 generatedPosition: generatedPosition,
76262                 source: source,
76263                 sourceIndex: mapping.sourceIndex,
76264                 sourcePosition: sourcePosition,
76265                 nameIndex: mapping.nameIndex
76266             };
76267         }
76268         function getDecodedMappings() {
76269             if (decodedMappings === undefined) {
76270                 var decoder = decodeMappings(map.mappings);
76271                 var mappings = ts.arrayFrom(decoder, processMapping);
76272                 if (decoder.error !== undefined) {
76273                     if (host.log) {
76274                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
76275                     }
76276                     decodedMappings = ts.emptyArray;
76277                 }
76278                 else {
76279                     decodedMappings = mappings;
76280                 }
76281             }
76282             return decodedMappings;
76283         }
76284         function getSourceMappings(sourceIndex) {
76285             if (sourceMappings === undefined) {
76286                 var lists = [];
76287                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76288                     var mapping = _a[_i];
76289                     if (!isSourceMappedPosition(mapping))
76290                         continue;
76291                     var list = lists[mapping.sourceIndex];
76292                     if (!list)
76293                         lists[mapping.sourceIndex] = list = [];
76294                     list.push(mapping);
76295                 }
76296                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
76297             }
76298             return sourceMappings[sourceIndex];
76299         }
76300         function getGeneratedMappings() {
76301             if (generatedMappings === undefined) {
76302                 var list = [];
76303                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76304                     var mapping = _a[_i];
76305                     list.push(mapping);
76306                 }
76307                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
76308             }
76309             return generatedMappings;
76310         }
76311         function getGeneratedPosition(loc) {
76312             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
76313             if (sourceIndex === undefined)
76314                 return loc;
76315             var sourceMappings = getSourceMappings(sourceIndex);
76316             if (!ts.some(sourceMappings))
76317                 return loc;
76318             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
76319             if (targetIndex < 0) {
76320                 // if no exact match, closest is 2's complement of result
76321                 targetIndex = ~targetIndex;
76322             }
76323             var mapping = sourceMappings[targetIndex];
76324             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
76325                 return loc;
76326             }
76327             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
76328         }
76329         function getSourcePosition(loc) {
76330             var generatedMappings = getGeneratedMappings();
76331             if (!ts.some(generatedMappings))
76332                 return loc;
76333             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
76334             if (targetIndex < 0) {
76335                 // if no exact match, closest is 2's complement of result
76336                 targetIndex = ~targetIndex;
76337             }
76338             var mapping = generatedMappings[targetIndex];
76339             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
76340                 return loc;
76341             }
76342             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
76343         }
76344     }
76345     ts.createDocumentPositionMapper = createDocumentPositionMapper;
76346     ts.identitySourceMapConsumer = {
76347         getSourcePosition: ts.identity,
76348         getGeneratedPosition: ts.identity
76349     };
76350 })(ts || (ts = {}));
76351 /* @internal */
76352 var ts;
76353 (function (ts) {
76354     function getOriginalNodeId(node) {
76355         node = ts.getOriginalNode(node);
76356         return node ? ts.getNodeId(node) : 0;
76357     }
76358     ts.getOriginalNodeId = getOriginalNodeId;
76359     function containsDefaultReference(node) {
76360         if (!node)
76361             return false;
76362         if (!ts.isNamedImports(node))
76363             return false;
76364         return ts.some(node.elements, isNamedDefaultReference);
76365     }
76366     function isNamedDefaultReference(e) {
76367         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
76368     }
76369     function chainBundle(transformSourceFile) {
76370         return transformSourceFileOrBundle;
76371         function transformSourceFileOrBundle(node) {
76372             return node.kind === 290 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
76373         }
76374         function transformBundle(node) {
76375             return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
76376         }
76377     }
76378     ts.chainBundle = chainBundle;
76379     function getExportNeedsImportStarHelper(node) {
76380         return !!ts.getNamespaceDeclarationNode(node);
76381     }
76382     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
76383     function getImportNeedsImportStarHelper(node) {
76384         if (!!ts.getNamespaceDeclarationNode(node)) {
76385             return true;
76386         }
76387         var bindings = node.importClause && node.importClause.namedBindings;
76388         if (!bindings) {
76389             return false;
76390         }
76391         if (!ts.isNamedImports(bindings))
76392             return false;
76393         var defaultRefCount = 0;
76394         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
76395             var binding = _a[_i];
76396             if (isNamedDefaultReference(binding)) {
76397                 defaultRefCount++;
76398             }
76399         }
76400         // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import
76401         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
76402     }
76403     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
76404     function getImportNeedsImportDefaultHelper(node) {
76405         // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
76406         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
76407     }
76408     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
76409     function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
76410         var externalImports = [];
76411         var exportSpecifiers = ts.createMultiMap();
76412         var exportedBindings = [];
76413         var uniqueExports = ts.createMap();
76414         var exportedNames;
76415         var hasExportDefault = false;
76416         var exportEquals;
76417         var hasExportStarsToExportValues = false;
76418         var hasImportStar = false;
76419         var hasImportDefault = false;
76420         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
76421             var node = _a[_i];
76422             switch (node.kind) {
76423                 case 254 /* ImportDeclaration */:
76424                     // import "mod"
76425                     // import x from "mod"
76426                     // import * as x from "mod"
76427                     // import { x, y } from "mod"
76428                     externalImports.push(node);
76429                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
76430                         hasImportStar = true;
76431                     }
76432                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
76433                         hasImportDefault = true;
76434                     }
76435                     break;
76436                 case 253 /* ImportEqualsDeclaration */:
76437                     if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
76438                         // import x = require("mod")
76439                         externalImports.push(node);
76440                     }
76441                     break;
76442                 case 260 /* ExportDeclaration */:
76443                     if (node.moduleSpecifier) {
76444                         if (!node.exportClause) {
76445                             // export * from "mod"
76446                             externalImports.push(node);
76447                             hasExportStarsToExportValues = true;
76448                         }
76449                         else {
76450                             // export * as ns from "mod"
76451                             // export { x, y } from "mod"
76452                             externalImports.push(node);
76453                         }
76454                     }
76455                     else {
76456                         // export { x, y }
76457                         for (var _b = 0, _c = ts.cast(node.exportClause, ts.isNamedExports).elements; _b < _c.length; _b++) {
76458                             var specifier = _c[_b];
76459                             if (!uniqueExports.get(ts.idText(specifier.name))) {
76460                                 var name = specifier.propertyName || specifier.name;
76461                                 exportSpecifiers.add(ts.idText(name), specifier);
76462                                 var decl = resolver.getReferencedImportDeclaration(name)
76463                                     || resolver.getReferencedValueDeclaration(name);
76464                                 if (decl) {
76465                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
76466                                 }
76467                                 uniqueExports.set(ts.idText(specifier.name), true);
76468                                 exportedNames = ts.append(exportedNames, specifier.name);
76469                             }
76470                         }
76471                     }
76472                     break;
76473                 case 259 /* ExportAssignment */:
76474                     if (node.isExportEquals && !exportEquals) {
76475                         // export = x
76476                         exportEquals = node;
76477                     }
76478                     break;
76479                 case 225 /* VariableStatement */:
76480                     if (ts.hasModifier(node, 1 /* Export */)) {
76481                         for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
76482                             var decl = _e[_d];
76483                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
76484                         }
76485                     }
76486                     break;
76487                 case 244 /* FunctionDeclaration */:
76488                     if (ts.hasModifier(node, 1 /* Export */)) {
76489                         if (ts.hasModifier(node, 512 /* Default */)) {
76490                             // export default function() { }
76491                             if (!hasExportDefault) {
76492                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76493                                 hasExportDefault = true;
76494                             }
76495                         }
76496                         else {
76497                             // export function x() { }
76498                             var name = node.name;
76499                             if (!uniqueExports.get(ts.idText(name))) {
76500                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76501                                 uniqueExports.set(ts.idText(name), true);
76502                                 exportedNames = ts.append(exportedNames, name);
76503                             }
76504                         }
76505                     }
76506                     break;
76507                 case 245 /* ClassDeclaration */:
76508                     if (ts.hasModifier(node, 1 /* Export */)) {
76509                         if (ts.hasModifier(node, 512 /* Default */)) {
76510                             // export default class { }
76511                             if (!hasExportDefault) {
76512                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76513                                 hasExportDefault = true;
76514                             }
76515                         }
76516                         else {
76517                             // export class x { }
76518                             var name = node.name;
76519                             if (name && !uniqueExports.get(ts.idText(name))) {
76520                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76521                                 uniqueExports.set(ts.idText(name), true);
76522                                 exportedNames = ts.append(exportedNames, name);
76523                             }
76524                         }
76525                     }
76526                     break;
76527             }
76528         }
76529         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
76530         if (externalHelpersImportDeclaration) {
76531             externalImports.unshift(externalHelpersImportDeclaration);
76532         }
76533         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
76534     }
76535     ts.collectExternalModuleInfo = collectExternalModuleInfo;
76536     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
76537         if (ts.isBindingPattern(decl.name)) {
76538             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
76539                 var element = _a[_i];
76540                 if (!ts.isOmittedExpression(element)) {
76541                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
76542                 }
76543             }
76544         }
76545         else if (!ts.isGeneratedIdentifier(decl.name)) {
76546             var text = ts.idText(decl.name);
76547             if (!uniqueExports.get(text)) {
76548                 uniqueExports.set(text, true);
76549                 exportedNames = ts.append(exportedNames, decl.name);
76550             }
76551         }
76552         return exportedNames;
76553     }
76554     /** Use a sparse array as a multi-map. */
76555     function multiMapSparseArrayAdd(map, key, value) {
76556         var values = map[key];
76557         if (values) {
76558             values.push(value);
76559         }
76560         else {
76561             map[key] = values = [value];
76562         }
76563         return values;
76564     }
76565     /**
76566      * Used in the module transformer to check if an expression is reasonably without sideeffect,
76567      *  and thus better to copy into multiple places rather than to cache in a temporary variable
76568      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
76569      */
76570     function isSimpleCopiableExpression(expression) {
76571         return ts.isStringLiteralLike(expression) ||
76572             expression.kind === 8 /* NumericLiteral */ ||
76573             ts.isKeyword(expression.kind) ||
76574             ts.isIdentifier(expression);
76575     }
76576     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
76577     /**
76578      * A simple inlinable expression is an expression which can be copied into multiple locations
76579      * without risk of repeating any sideeffects and whose value could not possibly change between
76580      * any such locations
76581      */
76582     function isSimpleInlineableExpression(expression) {
76583         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
76584             ts.isWellKnownSymbolSyntactically(expression);
76585     }
76586     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
76587     function isCompoundAssignment(kind) {
76588         return kind >= 63 /* FirstCompoundAssignment */
76589             && kind <= 74 /* LastCompoundAssignment */;
76590     }
76591     ts.isCompoundAssignment = isCompoundAssignment;
76592     function getNonAssignmentOperatorForCompoundAssignment(kind) {
76593         switch (kind) {
76594             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
76595             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
76596             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
76597             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
76598             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
76599             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
76600             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
76601             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
76602             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
76603             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
76604             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
76605             case 74 /* CaretEqualsToken */: return 52 /* CaretToken */;
76606         }
76607     }
76608     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
76609     /**
76610      * Adds super call and preceding prologue directives into the list of statements.
76611      *
76612      * @param ctor The constructor node.
76613      * @param result The list of statements.
76614      * @param visitor The visitor to apply to each node added to the result array.
76615      * @returns index of the statement that follows super call
76616      */
76617     function addPrologueDirectivesAndInitialSuperCall(ctor, result, visitor) {
76618         if (ctor.body) {
76619             var statements = ctor.body.statements;
76620             // add prologue directives to the list (if any)
76621             var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
76622             if (index === statements.length) {
76623                 // list contains nothing but prologue directives (or empty) - exit
76624                 return index;
76625             }
76626             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
76627             if (superIndex > -1) {
76628                 for (var i = index; i <= superIndex; i++) {
76629                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
76630                 }
76631                 return superIndex + 1;
76632             }
76633             return index;
76634         }
76635         return 0;
76636     }
76637     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
76638     /**
76639      * @param input Template string input strings
76640      * @param args Names which need to be made file-level unique
76641      */
76642     function helperString(input) {
76643         var args = [];
76644         for (var _i = 1; _i < arguments.length; _i++) {
76645             args[_i - 1] = arguments[_i];
76646         }
76647         return function (uniqueName) {
76648             var result = "";
76649             for (var i = 0; i < args.length; i++) {
76650                 result += input[i];
76651                 result += uniqueName(args[i]);
76652             }
76653             result += input[input.length - 1];
76654             return result;
76655         };
76656     }
76657     ts.helperString = helperString;
76658     /**
76659      * Gets all the static or all the instance property declarations of a class
76660      *
76661      * @param node The class node.
76662      * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
76663      */
76664     function getProperties(node, requireInitializer, isStatic) {
76665         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
76666     }
76667     ts.getProperties = getProperties;
76668     /**
76669      * Is a class element either a static or an instance property declaration with an initializer?
76670      *
76671      * @param member The class element node.
76672      * @param isStatic A value indicating whether the member should be a static or instance member.
76673      */
76674     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
76675         return ts.isPropertyDeclaration(member)
76676             && (!!member.initializer || !requireInitializer)
76677             && ts.hasStaticModifier(member) === isStatic;
76678     }
76679     /**
76680      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
76681      *
76682      * @param member The class element node.
76683      * @param isStatic A value indicating whether the member should be a static or instance member.
76684      */
76685     function isInitializedProperty(member) {
76686         return member.kind === 159 /* PropertyDeclaration */
76687             && member.initializer !== undefined;
76688     }
76689     ts.isInitializedProperty = isInitializedProperty;
76690 })(ts || (ts = {}));
76691 /*@internal*/
76692 var ts;
76693 (function (ts) {
76694     var FlattenLevel;
76695     (function (FlattenLevel) {
76696         FlattenLevel[FlattenLevel["All"] = 0] = "All";
76697         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
76698     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
76699     /**
76700      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
76701      *
76702      * @param node The node to flatten.
76703      * @param visitor An optional visitor used to visit initializers.
76704      * @param context The transformation context.
76705      * @param level Indicates the extent to which flattening should occur.
76706      * @param needsValue An optional value indicating whether the value from the right-hand-side of
76707      * the destructuring assignment is needed as part of a larger expression.
76708      * @param createAssignmentCallback An optional callback used to create the assignment expression.
76709      */
76710     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
76711         var location = node;
76712         var value;
76713         if (ts.isDestructuringAssignment(node)) {
76714             value = node.right;
76715             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
76716                 if (ts.isDestructuringAssignment(value)) {
76717                     location = node = value;
76718                     value = node.right;
76719                 }
76720                 else {
76721                     return ts.visitNode(value, visitor, ts.isExpression);
76722                 }
76723             }
76724         }
76725         var expressions;
76726         var flattenContext = {
76727             context: context,
76728             level: level,
76729             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76730             hoistTempVariables: true,
76731             emitExpression: emitExpression,
76732             emitBindingOrAssignment: emitBindingOrAssignment,
76733             createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
76734             createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
76735             createArrayBindingOrAssignmentElement: makeAssignmentElement,
76736             visitor: visitor
76737         };
76738         if (value) {
76739             value = ts.visitNode(value, visitor, ts.isExpression);
76740             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
76741                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
76742                 // If the right-hand value of the assignment is also an assignment target then
76743                 // we need to cache the right-hand value.
76744                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
76745             }
76746             else if (needsValue) {
76747                 // If the right-hand value of the destructuring assignment needs to be preserved (as
76748                 // is the case when the destructuring assignment is part of a larger expression),
76749                 // then we need to cache the right-hand value.
76750                 //
76751                 // The source map location for the assignment should point to the entire binary
76752                 // expression.
76753                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
76754             }
76755             else if (ts.nodeIsSynthesized(node)) {
76756                 // Generally, the source map location for a destructuring assignment is the root
76757                 // expression.
76758                 //
76759                 // However, if the root expression is synthesized (as in the case
76760                 // of the initializer when transforming a ForOfStatement), then the source map
76761                 // location should point to the right-hand value of the expression.
76762                 location = value;
76763             }
76764         }
76765         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
76766         if (value && needsValue) {
76767             if (!ts.some(expressions)) {
76768                 return value;
76769             }
76770             expressions.push(value);
76771         }
76772         return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
76773         function emitExpression(expression) {
76774             ts.aggregateTransformFlags(expression);
76775             expressions = ts.append(expressions, expression);
76776         }
76777         function emitBindingOrAssignment(target, value, location, original) {
76778             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
76779             var expression = createAssignmentCallback
76780                 ? createAssignmentCallback(target, value, location)
76781                 : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
76782             expression.original = original;
76783             emitExpression(expression);
76784         }
76785     }
76786     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
76787     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
76788         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76789         if (ts.isBindingOrAssignmentPattern(target)) {
76790             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
76791         }
76792         else if (ts.isIdentifier(target)) {
76793             return target.escapedText === escapedName;
76794         }
76795         return false;
76796     }
76797     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
76798         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76799         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
76800             var element = elements_3[_i];
76801             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
76802                 return true;
76803             }
76804         }
76805         return false;
76806     }
76807     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
76808         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
76809         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
76810             return true;
76811         }
76812         var target = ts.getTargetOfBindingOrAssignmentElement(element);
76813         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
76814     }
76815     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
76816         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
76817     }
76818     /**
76819      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
76820      *
76821      * @param node The node to flatten.
76822      * @param visitor An optional visitor used to visit initializers.
76823      * @param context The transformation context.
76824      * @param boundValue The value bound to the declaration.
76825      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
76826      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
76827      * @param level Indicates the extent to which flattening should occur.
76828      */
76829     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
76830         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
76831         var pendingExpressions;
76832         var pendingDeclarations = [];
76833         var declarations = [];
76834         var flattenContext = {
76835             context: context,
76836             level: level,
76837             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76838             hoistTempVariables: hoistTempVariables,
76839             emitExpression: emitExpression,
76840             emitBindingOrAssignment: emitBindingOrAssignment,
76841             createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
76842             createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
76843             createArrayBindingOrAssignmentElement: makeBindingElement,
76844             visitor: visitor
76845         };
76846         if (ts.isVariableDeclaration(node)) {
76847             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
76848             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
76849                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
76850                 // If the right-hand value of the assignment is also an assignment target then
76851                 // we need to cache the right-hand value.
76852                 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
76853                 node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
76854             }
76855         }
76856         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
76857         if (pendingExpressions) {
76858             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
76859             if (hoistTempVariables) {
76860                 var value = ts.inlineExpressions(pendingExpressions);
76861                 pendingExpressions = undefined;
76862                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
76863             }
76864             else {
76865                 context.hoistVariableDeclaration(temp);
76866                 var pendingDeclaration = ts.last(pendingDeclarations);
76867                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
76868                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
76869                 pendingDeclaration.value = temp;
76870             }
76871         }
76872         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
76873             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
76874             var variable = ts.createVariableDeclaration(name, 
76875             /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
76876             variable.original = original;
76877             ts.setTextRange(variable, location);
76878             ts.aggregateTransformFlags(variable);
76879             declarations.push(variable);
76880         }
76881         return declarations;
76882         function emitExpression(value) {
76883             pendingExpressions = ts.append(pendingExpressions, value);
76884         }
76885         function emitBindingOrAssignment(target, value, location, original) {
76886             ts.Debug.assertNode(target, ts.isBindingName);
76887             if (pendingExpressions) {
76888                 value = ts.inlineExpressions(ts.append(pendingExpressions, value));
76889                 pendingExpressions = undefined;
76890             }
76891             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
76892         }
76893     }
76894     ts.flattenDestructuringBinding = flattenDestructuringBinding;
76895     /**
76896      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
76897      *
76898      * @param flattenContext Options used to control flattening.
76899      * @param element The element to flatten.
76900      * @param value The current RHS value to assign to the element.
76901      * @param location The location to use for source maps and comments.
76902      * @param skipInitializer An optional value indicating whether to include the initializer
76903      * for the element.
76904      */
76905     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
76906         if (!skipInitializer) {
76907             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
76908             if (initializer) {
76909                 // Combine value and initializer
76910                 value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
76911             }
76912             else if (!value) {
76913                 // Use 'void 0' in absence of value and initializer
76914                 value = ts.createVoidZero();
76915             }
76916         }
76917         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76918         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
76919             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76920         }
76921         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
76922             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76923         }
76924         else {
76925             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
76926         }
76927     }
76928     /**
76929      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
76930      *
76931      * @param flattenContext Options used to control flattening.
76932      * @param parent The parent element of the pattern.
76933      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
76934      * @param value The current RHS value to assign to the element.
76935      * @param location The location to use for source maps and comments.
76936      */
76937     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76938         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76939         var numElements = elements.length;
76940         if (numElements !== 1) {
76941             // For anything other than a single-element destructuring we need to generate a temporary
76942             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
76943             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
76944             // so in that case, we'll intentionally create that temporary.
76945             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
76946             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
76947         }
76948         var bindingElements;
76949         var computedTempVariables;
76950         for (var i = 0; i < numElements; i++) {
76951             var element = elements[i];
76952             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
76953                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
76954                 if (flattenContext.level >= 1 /* ObjectRest */
76955                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76956                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76957                     && !ts.isComputedPropertyName(propertyName)) {
76958                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
76959                 }
76960                 else {
76961                     if (bindingElements) {
76962                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76963                         bindingElements = undefined;
76964                     }
76965                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
76966                     if (ts.isComputedPropertyName(propertyName)) {
76967                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
76968                     }
76969                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
76970                 }
76971             }
76972             else if (i === numElements - 1) {
76973                 if (bindingElements) {
76974                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76975                     bindingElements = undefined;
76976                 }
76977                 var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
76978                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
76979             }
76980         }
76981         if (bindingElements) {
76982             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76983         }
76984     }
76985     /**
76986      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
76987      *
76988      * @param flattenContext Options used to control flattening.
76989      * @param parent The parent element of the pattern.
76990      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
76991      * @param value The current RHS value to assign to the element.
76992      * @param location The location to use for source maps and comments.
76993      */
76994     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76995         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76996         var numElements = elements.length;
76997         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
76998             // Read the elements of the iterable into an array
76999             value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
77000                 ? undefined
77001                 : numElements, location), 
77002             /*reuseIdentifierExpressions*/ false, location);
77003         }
77004         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
77005             || ts.every(elements, ts.isOmittedExpression)) {
77006             // For anything other than a single-element destructuring we need to generate a temporary
77007             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
77008             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
77009             // so in that case, we'll intentionally create that temporary.
77010             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
77011             // then we will create temporary variable.
77012             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
77013             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
77014         }
77015         var bindingElements;
77016         var restContainingElements;
77017         for (var i = 0; i < numElements; i++) {
77018             var element = elements[i];
77019             if (flattenContext.level >= 1 /* ObjectRest */) {
77020                 // If an array pattern contains an ObjectRest, we must cache the result so that we
77021                 // can perform the ObjectRest destructuring in a different declaration
77022                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
77023                     var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77024                     if (flattenContext.hoistTempVariables) {
77025                         flattenContext.context.hoistVariableDeclaration(temp);
77026                     }
77027                     restContainingElements = ts.append(restContainingElements, [temp, element]);
77028                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
77029                 }
77030                 else {
77031                     bindingElements = ts.append(bindingElements, element);
77032                 }
77033             }
77034             else if (ts.isOmittedExpression(element)) {
77035                 continue;
77036             }
77037             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
77038                 var rhsValue = ts.createElementAccess(value, i);
77039                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77040             }
77041             else if (i === numElements - 1) {
77042                 var rhsValue = ts.createArraySlice(value, i);
77043                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77044             }
77045         }
77046         if (bindingElements) {
77047             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77048         }
77049         if (restContainingElements) {
77050             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
77051                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
77052                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
77053             }
77054         }
77055     }
77056     /**
77057      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
77058      *
77059      * @param flattenContext Options used to control flattening.
77060      * @param value The RHS value to test.
77061      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
77062      * @param location The location to use for source maps and comments.
77063      */
77064     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
77065         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
77066         return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
77067     }
77068     /**
77069      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
77070      * right-hand side of a transformed destructuring assignment.
77071      *
77072      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
77073      *
77074      * @param flattenContext Options used to control flattening.
77075      * @param value The RHS value that is the source of the property.
77076      * @param propertyName The destructuring property name.
77077      */
77078     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
77079         if (ts.isComputedPropertyName(propertyName)) {
77080             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
77081             return ts.createElementAccess(value, argumentExpression);
77082         }
77083         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
77084             var argumentExpression = ts.getSynthesizedClone(propertyName);
77085             argumentExpression.text = argumentExpression.text;
77086             return ts.createElementAccess(value, argumentExpression);
77087         }
77088         else {
77089             var name = ts.createIdentifier(ts.idText(propertyName));
77090             return ts.createPropertyAccess(value, name);
77091         }
77092     }
77093     /**
77094      * Ensures that there exists a declared identifier whose value holds the given expression.
77095      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
77096      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
77097      *
77098      * @param flattenContext Options used to control flattening.
77099      * @param value the expression whose value needs to be bound.
77100      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
77101      * false if it is necessary to always emit an identifier.
77102      * @param location The location to use for source maps and comments.
77103      */
77104     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
77105         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
77106             return value;
77107         }
77108         else {
77109             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77110             if (flattenContext.hoistTempVariables) {
77111                 flattenContext.context.hoistVariableDeclaration(temp);
77112                 flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
77113             }
77114             else {
77115                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
77116             }
77117             return temp;
77118         }
77119     }
77120     function makeArrayBindingPattern(elements) {
77121         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
77122         return ts.createArrayBindingPattern(elements);
77123     }
77124     function makeArrayAssignmentPattern(elements) {
77125         return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
77126     }
77127     function makeObjectBindingPattern(elements) {
77128         ts.Debug.assertEachNode(elements, ts.isBindingElement);
77129         return ts.createObjectBindingPattern(elements);
77130     }
77131     function makeObjectAssignmentPattern(elements) {
77132         return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
77133     }
77134     function makeBindingElement(name) {
77135         return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
77136     }
77137     function makeAssignmentElement(name) {
77138         return name;
77139     }
77140     ts.restHelper = {
77141         name: "typescript:rest",
77142         importName: "__rest",
77143         scoped: false,
77144         text: "\n            var __rest = (this && this.__rest) || function (s, e) {\n                var t = {};\n                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n                    t[p] = s[p];\n                if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n                    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n                        if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n                            t[p[i]] = s[p[i]];\n                    }\n                return t;\n            };"
77145     };
77146     /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
77147      * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
77148      */
77149     function createRestCall(context, value, elements, computedTempVariables, location) {
77150         context.requestEmitHelper(ts.restHelper);
77151         var propertyNames = [];
77152         var computedTempVariableOffset = 0;
77153         for (var i = 0; i < elements.length - 1; i++) {
77154             var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
77155             if (propertyName) {
77156                 if (ts.isComputedPropertyName(propertyName)) {
77157                     var temp = computedTempVariables[computedTempVariableOffset];
77158                     computedTempVariableOffset++;
77159                     // typeof _tmp === "symbol" ? _tmp : _tmp + ""
77160                     propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
77161                 }
77162                 else {
77163                     propertyNames.push(ts.createLiteral(propertyName));
77164                 }
77165             }
77166         }
77167         return ts.createCall(ts.getUnscopedHelperName("__rest"), 
77168         /*typeArguments*/ undefined, [
77169             value,
77170             ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
77171         ]);
77172     }
77173 })(ts || (ts = {}));
77174 /*@internal*/
77175 var ts;
77176 (function (ts) {
77177     var ProcessLevel;
77178     (function (ProcessLevel) {
77179         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
77180         ProcessLevel[ProcessLevel["All"] = 1] = "All";
77181     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
77182     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
77183         // Visit the tag expression
77184         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
77185         // Build up the template arguments and the raw and cooked strings for the template.
77186         // We start out with 'undefined' for the first argument and revisit later
77187         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
77188         var templateArguments = [undefined];
77189         var cookedStrings = [];
77190         var rawStrings = [];
77191         var template = node.template;
77192         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template))
77193             return node;
77194         if (ts.isNoSubstitutionTemplateLiteral(template)) {
77195             cookedStrings.push(createTemplateCooked(template));
77196             rawStrings.push(getRawLiteral(template, currentSourceFile));
77197         }
77198         else {
77199             cookedStrings.push(createTemplateCooked(template.head));
77200             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
77201             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
77202                 var templateSpan = _a[_i];
77203                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
77204                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
77205                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
77206             }
77207         }
77208         var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
77209         // Create a variable to cache the template object if we're in a module.
77210         // Do not do this in the global scope, as any variable we currently generate could conflict with
77211         // variables from outside of the current compilation. In the future, we can revisit this behavior.
77212         if (ts.isExternalModule(currentSourceFile)) {
77213             var tempVar = ts.createUniqueName("templateObject");
77214             recordTaggedTemplateString(tempVar);
77215             templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
77216         }
77217         else {
77218             templateArguments[0] = helperCall;
77219         }
77220         return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
77221     }
77222     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
77223     function createTemplateCooked(template) {
77224         return template.templateFlags ? ts.createIdentifier("undefined") : ts.createLiteral(template.text);
77225     }
77226     /**
77227      * Creates an ES5 compatible literal from an ES6 template literal.
77228      *
77229      * @param node The ES6 template literal.
77230      */
77231     function getRawLiteral(node, currentSourceFile) {
77232         // Find original source text, since we need to emit the raw strings of the tagged template.
77233         // The raw strings contain the (escaped) strings of what the user wrote.
77234         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
77235         var text = node.rawText;
77236         if (text === undefined) {
77237             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
77238             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
77239             // thus we need to remove those characters.
77240             // First template piece starts with "`", others with "}"
77241             // Last template piece ends with "`", others with "${"
77242             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
77243             text = text.substring(1, text.length - (isLast ? 1 : 2));
77244         }
77245         // Newline normalization:
77246         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
77247         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
77248         text = text.replace(/\r\n?/g, "\n");
77249         return ts.setTextRange(ts.createLiteral(text), node);
77250     }
77251     function createTemplateObjectHelper(context, cooked, raw) {
77252         context.requestEmitHelper(ts.templateObjectHelper);
77253         return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"), 
77254         /*typeArguments*/ undefined, [
77255             cooked,
77256             raw
77257         ]);
77258     }
77259     ts.templateObjectHelper = {
77260         name: "typescript:makeTemplateObject",
77261         importName: "__makeTemplateObject",
77262         scoped: false,
77263         priority: 0,
77264         text: "\n            var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n                if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n                return cooked;\n            };"
77265     };
77266 })(ts || (ts = {}));
77267 /*@internal*/
77268 var ts;
77269 (function (ts) {
77270     /**
77271      * Indicates whether to emit type metadata in the new format.
77272      */
77273     var USE_NEW_TYPE_METADATA_FORMAT = false;
77274     var TypeScriptSubstitutionFlags;
77275     (function (TypeScriptSubstitutionFlags) {
77276         /** Enables substitutions for decorated classes. */
77277         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
77278         /** Enables substitutions for namespace exports. */
77279         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
77280         /* Enables substitutions for unqualified enum members */
77281         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
77282     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
77283     var ClassFacts;
77284     (function (ClassFacts) {
77285         ClassFacts[ClassFacts["None"] = 0] = "None";
77286         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
77287         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
77288         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
77289         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
77290         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
77291         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
77292         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
77293         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
77294         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
77295         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
77296         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
77297         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
77298     })(ClassFacts || (ClassFacts = {}));
77299     function transformTypeScript(context) {
77300         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
77301         var resolver = context.getEmitResolver();
77302         var compilerOptions = context.getCompilerOptions();
77303         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
77304         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
77305         var moduleKind = ts.getEmitModuleKind(compilerOptions);
77306         // Save the previous transformation hooks.
77307         var previousOnEmitNode = context.onEmitNode;
77308         var previousOnSubstituteNode = context.onSubstituteNode;
77309         // Set new transformation hooks.
77310         context.onEmitNode = onEmitNode;
77311         context.onSubstituteNode = onSubstituteNode;
77312         // Enable substitution for property/element access to emit const enum values.
77313         context.enableSubstitution(194 /* PropertyAccessExpression */);
77314         context.enableSubstitution(195 /* ElementAccessExpression */);
77315         // These variables contain state that changes as we descend into the tree.
77316         var currentSourceFile;
77317         var currentNamespace;
77318         var currentNamespaceContainerName;
77319         var currentLexicalScope;
77320         var currentNameScope;
77321         var currentScopeFirstDeclarationsOfName;
77322         var currentClassHasParameterProperties;
77323         /**
77324          * Keeps track of whether expression substitution has been enabled for specific edge cases.
77325          * They are persisted between each SourceFile transformation and should not be reset.
77326          */
77327         var enabledSubstitutions;
77328         /**
77329          * A map that keeps track of aliases created for classes with decorators to avoid issues
77330          * with the double-binding behavior of classes.
77331          */
77332         var classAliases;
77333         /**
77334          * Keeps track of whether we are within any containing namespaces when performing
77335          * just-in-time substitution while printing an expression identifier.
77336          */
77337         var applicableSubstitutions;
77338         return transformSourceFileOrBundle;
77339         function transformSourceFileOrBundle(node) {
77340             if (node.kind === 291 /* Bundle */) {
77341                 return transformBundle(node);
77342             }
77343             return transformSourceFile(node);
77344         }
77345         function transformBundle(node) {
77346             return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
77347                 if (prepend.kind === 293 /* InputFiles */) {
77348                     return ts.createUnparsedSourceFile(prepend, "js");
77349                 }
77350                 return prepend;
77351             }));
77352         }
77353         /**
77354          * Transform TypeScript-specific syntax in a SourceFile.
77355          *
77356          * @param node A SourceFile node.
77357          */
77358         function transformSourceFile(node) {
77359             if (node.isDeclarationFile) {
77360                 return node;
77361             }
77362             currentSourceFile = node;
77363             var visited = saveStateAndInvoke(node, visitSourceFile);
77364             ts.addEmitHelpers(visited, context.readEmitHelpers());
77365             currentSourceFile = undefined;
77366             return visited;
77367         }
77368         /**
77369          * Visits a node, saving and restoring state variables on the stack.
77370          *
77371          * @param node The node to visit.
77372          */
77373         function saveStateAndInvoke(node, f) {
77374             // Save state
77375             var savedCurrentScope = currentLexicalScope;
77376             var savedCurrentNameScope = currentNameScope;
77377             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
77378             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
77379             // Handle state changes before visiting a node.
77380             onBeforeVisitNode(node);
77381             var visited = f(node);
77382             // Restore state
77383             if (currentLexicalScope !== savedCurrentScope) {
77384                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
77385             }
77386             currentLexicalScope = savedCurrentScope;
77387             currentNameScope = savedCurrentNameScope;
77388             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
77389             return visited;
77390         }
77391         /**
77392          * Performs actions that should always occur immediately before visiting a node.
77393          *
77394          * @param node The node to visit.
77395          */
77396         function onBeforeVisitNode(node) {
77397             switch (node.kind) {
77398                 case 290 /* SourceFile */:
77399                 case 251 /* CaseBlock */:
77400                 case 250 /* ModuleBlock */:
77401                 case 223 /* Block */:
77402                     currentLexicalScope = node;
77403                     currentNameScope = undefined;
77404                     currentScopeFirstDeclarationsOfName = undefined;
77405                     break;
77406                 case 245 /* ClassDeclaration */:
77407                 case 244 /* FunctionDeclaration */:
77408                     if (ts.hasModifier(node, 2 /* Ambient */)) {
77409                         break;
77410                     }
77411                     // Record these declarations provided that they have a name.
77412                     if (node.name) {
77413                         recordEmittedDeclarationInScope(node);
77414                     }
77415                     else {
77416                         // These nodes should always have names unless they are default-exports;
77417                         // however, class declaration parsing allows for undefined names, so syntactically invalid
77418                         // programs may also have an undefined name.
77419                         ts.Debug.assert(node.kind === 245 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
77420                     }
77421                     if (ts.isClassDeclaration(node)) {
77422                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
77423                         currentNameScope = node;
77424                     }
77425                     break;
77426             }
77427         }
77428         /**
77429          * General-purpose node visitor.
77430          *
77431          * @param node The node to visit.
77432          */
77433         function visitor(node) {
77434             return saveStateAndInvoke(node, visitorWorker);
77435         }
77436         /**
77437          * Visits and possibly transforms any node.
77438          *
77439          * @param node The node to visit.
77440          */
77441         function visitorWorker(node) {
77442             if (node.transformFlags & 1 /* ContainsTypeScript */) {
77443                 return visitTypeScript(node);
77444             }
77445             return node;
77446         }
77447         /**
77448          * Specialized visitor that visits the immediate children of a SourceFile.
77449          *
77450          * @param node The node to visit.
77451          */
77452         function sourceElementVisitor(node) {
77453             return saveStateAndInvoke(node, sourceElementVisitorWorker);
77454         }
77455         /**
77456          * Specialized visitor that visits the immediate children of a SourceFile.
77457          *
77458          * @param node The node to visit.
77459          */
77460         function sourceElementVisitorWorker(node) {
77461             switch (node.kind) {
77462                 case 254 /* ImportDeclaration */:
77463                 case 253 /* ImportEqualsDeclaration */:
77464                 case 259 /* ExportAssignment */:
77465                 case 260 /* ExportDeclaration */:
77466                     return visitEllidableStatement(node);
77467                 default:
77468                     return visitorWorker(node);
77469             }
77470         }
77471         function visitEllidableStatement(node) {
77472             var parsed = ts.getParseTreeNode(node);
77473             if (parsed !== node) {
77474                 // If the node has been transformed by a `before` transformer, perform no ellision on it
77475                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
77476                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
77477                 // and will trigger debug failures when debug verbosity is turned up
77478                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
77479                     // This node contains TypeScript, so we should visit its children.
77480                     return ts.visitEachChild(node, visitor, context);
77481                 }
77482                 // Otherwise, we can just return the node
77483                 return node;
77484             }
77485             switch (node.kind) {
77486                 case 254 /* ImportDeclaration */:
77487                     return visitImportDeclaration(node);
77488                 case 253 /* ImportEqualsDeclaration */:
77489                     return visitImportEqualsDeclaration(node);
77490                 case 259 /* ExportAssignment */:
77491                     return visitExportAssignment(node);
77492                 case 260 /* ExportDeclaration */:
77493                     return visitExportDeclaration(node);
77494                 default:
77495                     ts.Debug.fail("Unhandled ellided statement");
77496             }
77497         }
77498         /**
77499          * Specialized visitor that visits the immediate children of a namespace.
77500          *
77501          * @param node The node to visit.
77502          */
77503         function namespaceElementVisitor(node) {
77504             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
77505         }
77506         /**
77507          * Specialized visitor that visits the immediate children of a namespace.
77508          *
77509          * @param node The node to visit.
77510          */
77511         function namespaceElementVisitorWorker(node) {
77512             if (node.kind === 260 /* ExportDeclaration */ ||
77513                 node.kind === 254 /* ImportDeclaration */ ||
77514                 node.kind === 255 /* ImportClause */ ||
77515                 (node.kind === 253 /* ImportEqualsDeclaration */ &&
77516                     node.moduleReference.kind === 265 /* ExternalModuleReference */)) {
77517                 // do not emit ES6 imports and exports since they are illegal inside a namespace
77518                 return undefined;
77519             }
77520             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
77521                 return visitTypeScript(node);
77522             }
77523             return node;
77524         }
77525         /**
77526          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77527          *
77528          * @param node The node to visit.
77529          */
77530         function classElementVisitor(node) {
77531             return saveStateAndInvoke(node, classElementVisitorWorker);
77532         }
77533         /**
77534          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77535          *
77536          * @param node The node to visit.
77537          */
77538         function classElementVisitorWorker(node) {
77539             switch (node.kind) {
77540                 case 162 /* Constructor */:
77541                     return visitConstructor(node);
77542                 case 159 /* PropertyDeclaration */:
77543                     // Property declarations are not TypeScript syntax, but they must be visited
77544                     // for the decorator transformation.
77545                     return visitPropertyDeclaration(node);
77546                 case 167 /* IndexSignature */:
77547                 case 163 /* GetAccessor */:
77548                 case 164 /* SetAccessor */:
77549                 case 161 /* MethodDeclaration */:
77550                     // Fallback to the default visit behavior.
77551                     return visitorWorker(node);
77552                 case 222 /* SemicolonClassElement */:
77553                     return node;
77554                 default:
77555                     return ts.Debug.failBadSyntaxKind(node);
77556             }
77557         }
77558         function modifierVisitor(node) {
77559             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
77560                 return undefined;
77561             }
77562             else if (currentNamespace && node.kind === 89 /* ExportKeyword */) {
77563                 return undefined;
77564             }
77565             return node;
77566         }
77567         /**
77568          * Branching visitor, visits a TypeScript syntax node.
77569          *
77570          * @param node The node to visit.
77571          */
77572         function visitTypeScript(node) {
77573             if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
77574                 // TypeScript ambient declarations are elided, but some comments may be preserved.
77575                 // See the implementation of `getLeadingComments` in comments.ts for more details.
77576                 return ts.createNotEmittedStatement(node);
77577             }
77578             switch (node.kind) {
77579                 case 89 /* ExportKeyword */:
77580                 case 84 /* DefaultKeyword */:
77581                     // ES6 export and default modifiers are elided when inside a namespace.
77582                     return currentNamespace ? undefined : node;
77583                 case 119 /* PublicKeyword */:
77584                 case 117 /* PrivateKeyword */:
77585                 case 118 /* ProtectedKeyword */:
77586                 case 122 /* AbstractKeyword */:
77587                 case 81 /* ConstKeyword */:
77588                 case 130 /* DeclareKeyword */:
77589                 case 138 /* ReadonlyKeyword */:
77590                 // TypeScript accessibility and readonly modifiers are elided
77591                 // falls through
77592                 case 174 /* ArrayType */:
77593                 case 175 /* TupleType */:
77594                 case 176 /* OptionalType */:
77595                 case 177 /* RestType */:
77596                 case 173 /* TypeLiteral */:
77597                 case 168 /* TypePredicate */:
77598                 case 155 /* TypeParameter */:
77599                 case 125 /* AnyKeyword */:
77600                 case 148 /* UnknownKeyword */:
77601                 case 128 /* BooleanKeyword */:
77602                 case 143 /* StringKeyword */:
77603                 case 140 /* NumberKeyword */:
77604                 case 137 /* NeverKeyword */:
77605                 case 110 /* VoidKeyword */:
77606                 case 144 /* SymbolKeyword */:
77607                 case 171 /* ConstructorType */:
77608                 case 170 /* FunctionType */:
77609                 case 172 /* TypeQuery */:
77610                 case 169 /* TypeReference */:
77611                 case 178 /* UnionType */:
77612                 case 179 /* IntersectionType */:
77613                 case 180 /* ConditionalType */:
77614                 case 182 /* ParenthesizedType */:
77615                 case 183 /* ThisType */:
77616                 case 184 /* TypeOperator */:
77617                 case 185 /* IndexedAccessType */:
77618                 case 186 /* MappedType */:
77619                 case 187 /* LiteralType */:
77620                 // TypeScript type nodes are elided.
77621                 // falls through
77622                 case 167 /* IndexSignature */:
77623                 // TypeScript index signatures are elided.
77624                 // falls through
77625                 case 157 /* Decorator */:
77626                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
77627                 // falls through
77628                 case 247 /* TypeAliasDeclaration */:
77629                     // TypeScript type-only declarations are elided.
77630                     return undefined;
77631                 case 159 /* PropertyDeclaration */:
77632                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
77633                     return visitPropertyDeclaration(node);
77634                 case 252 /* NamespaceExportDeclaration */:
77635                     // TypeScript namespace export declarations are elided.
77636                     return undefined;
77637                 case 162 /* Constructor */:
77638                     return visitConstructor(node);
77639                 case 246 /* InterfaceDeclaration */:
77640                     // TypeScript interfaces are elided, but some comments may be preserved.
77641                     // See the implementation of `getLeadingComments` in comments.ts for more details.
77642                     return ts.createNotEmittedStatement(node);
77643                 case 245 /* ClassDeclaration */:
77644                     // This may be a class declaration with TypeScript syntax extensions.
77645                     //
77646                     // TypeScript class syntax extensions include:
77647                     // - decorators
77648                     // - optional `implements` heritage clause
77649                     // - parameter property assignments in the constructor
77650                     // - index signatures
77651                     // - method overload signatures
77652                     return visitClassDeclaration(node);
77653                 case 214 /* ClassExpression */:
77654                     // This may be a class expression with TypeScript syntax extensions.
77655                     //
77656                     // TypeScript class syntax extensions include:
77657                     // - decorators
77658                     // - optional `implements` heritage clause
77659                     // - parameter property assignments in the constructor
77660                     // - index signatures
77661                     // - method overload signatures
77662                     return visitClassExpression(node);
77663                 case 279 /* HeritageClause */:
77664                     // This may be a heritage clause with TypeScript syntax extensions.
77665                     //
77666                     // TypeScript heritage clause extensions include:
77667                     // - `implements` clause
77668                     return visitHeritageClause(node);
77669                 case 216 /* ExpressionWithTypeArguments */:
77670                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
77671                     return visitExpressionWithTypeArguments(node);
77672                 case 161 /* MethodDeclaration */:
77673                     // TypeScript method declarations may have decorators, modifiers
77674                     // or type annotations.
77675                     return visitMethodDeclaration(node);
77676                 case 163 /* GetAccessor */:
77677                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
77678                     return visitGetAccessor(node);
77679                 case 164 /* SetAccessor */:
77680                     // Set Accessors can have TypeScript modifiers and type annotations.
77681                     return visitSetAccessor(node);
77682                 case 244 /* FunctionDeclaration */:
77683                     // Typescript function declarations can have modifiers, decorators, and type annotations.
77684                     return visitFunctionDeclaration(node);
77685                 case 201 /* FunctionExpression */:
77686                     // TypeScript function expressions can have modifiers and type annotations.
77687                     return visitFunctionExpression(node);
77688                 case 202 /* ArrowFunction */:
77689                     // TypeScript arrow functions can have modifiers and type annotations.
77690                     return visitArrowFunction(node);
77691                 case 156 /* Parameter */:
77692                     // This may be a parameter declaration with TypeScript syntax extensions.
77693                     //
77694                     // TypeScript parameter declaration syntax extensions include:
77695                     // - decorators
77696                     // - accessibility modifiers
77697                     // - the question mark (?) token for optional parameters
77698                     // - type annotations
77699                     // - this parameters
77700                     return visitParameter(node);
77701                 case 200 /* ParenthesizedExpression */:
77702                     // ParenthesizedExpressions are TypeScript if their expression is a
77703                     // TypeAssertion or AsExpression
77704                     return visitParenthesizedExpression(node);
77705                 case 199 /* TypeAssertionExpression */:
77706                 case 217 /* AsExpression */:
77707                     // TypeScript type assertions are removed, but their subtrees are preserved.
77708                     return visitAssertionExpression(node);
77709                 case 196 /* CallExpression */:
77710                     return visitCallExpression(node);
77711                 case 197 /* NewExpression */:
77712                     return visitNewExpression(node);
77713                 case 198 /* TaggedTemplateExpression */:
77714                     return visitTaggedTemplateExpression(node);
77715                 case 218 /* NonNullExpression */:
77716                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
77717                     return visitNonNullExpression(node);
77718                 case 248 /* EnumDeclaration */:
77719                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
77720                     return visitEnumDeclaration(node);
77721                 case 225 /* VariableStatement */:
77722                     // TypeScript namespace exports for variable statements must be transformed.
77723                     return visitVariableStatement(node);
77724                 case 242 /* VariableDeclaration */:
77725                     return visitVariableDeclaration(node);
77726                 case 249 /* ModuleDeclaration */:
77727                     // TypeScript namespace declarations must be transformed.
77728                     return visitModuleDeclaration(node);
77729                 case 253 /* ImportEqualsDeclaration */:
77730                     // TypeScript namespace or external module import.
77731                     return visitImportEqualsDeclaration(node);
77732                 case 267 /* JsxSelfClosingElement */:
77733                     return visitJsxSelfClosingElement(node);
77734                 case 268 /* JsxOpeningElement */:
77735                     return visitJsxJsxOpeningElement(node);
77736                 default:
77737                     // node contains some other TypeScript syntax
77738                     return ts.visitEachChild(node, visitor, context);
77739             }
77740         }
77741         function visitSourceFile(node) {
77742             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
77743                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
77744                 !ts.isJsonSourceFile(node);
77745             return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
77746         }
77747         /**
77748          * Tests whether we should emit a __decorate call for a class declaration.
77749          */
77750         function shouldEmitDecorateCallForClass(node) {
77751             if (node.decorators && node.decorators.length > 0) {
77752                 return true;
77753             }
77754             var constructor = ts.getFirstConstructorWithBody(node);
77755             if (constructor) {
77756                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
77757             }
77758             return false;
77759         }
77760         /**
77761          * Tests whether we should emit a __decorate call for a parameter declaration.
77762          */
77763         function shouldEmitDecorateCallForParameter(parameter) {
77764             return parameter.decorators !== undefined && parameter.decorators.length > 0;
77765         }
77766         function getClassFacts(node, staticProperties) {
77767             var facts = 0 /* None */;
77768             if (ts.some(staticProperties))
77769                 facts |= 1 /* HasStaticInitializedProperties */;
77770             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
77771             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */)
77772                 facts |= 64 /* IsDerivedClass */;
77773             if (shouldEmitDecorateCallForClass(node))
77774                 facts |= 2 /* HasConstructorDecorators */;
77775             if (ts.childIsDecorated(node))
77776                 facts |= 4 /* HasMemberDecorators */;
77777             if (isExportOfNamespace(node))
77778                 facts |= 8 /* IsExportOfNamespace */;
77779             else if (isDefaultExternalModuleExport(node))
77780                 facts |= 32 /* IsDefaultExternalExport */;
77781             else if (isNamedExternalModuleExport(node))
77782                 facts |= 16 /* IsNamedExternalExport */;
77783             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
77784                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
77785             return facts;
77786         }
77787         function hasTypeScriptClassSyntax(node) {
77788             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
77789         }
77790         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
77791             return ts.some(node.decorators)
77792                 || ts.some(node.typeParameters)
77793                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
77794                 || ts.some(node.members, hasTypeScriptClassSyntax);
77795         }
77796         function visitClassDeclaration(node) {
77797             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
77798                 return ts.visitEachChild(node, visitor, context);
77799             }
77800             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
77801             var facts = getClassFacts(node, staticProperties);
77802             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77803                 context.startLexicalEnvironment();
77804             }
77805             var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
77806             var classStatement = facts & 2 /* HasConstructorDecorators */
77807                 ? createClassDeclarationHeadWithDecorators(node, name)
77808                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
77809             var statements = [classStatement];
77810             // Write any decorators of the node.
77811             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
77812             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
77813             addConstructorDecorationStatement(statements, node);
77814             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77815                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
77816                 // 'es2015' transformer can properly nest static initializers and decorators. The result
77817                 // looks something like:
77818                 //
77819                 //  var C = function () {
77820                 //      class C {
77821                 //      }
77822                 //      C.static_prop = 1;
77823                 //      return C;
77824                 //  }();
77825                 //
77826                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
77827                 var localName = ts.getInternalName(node);
77828                 // The following partially-emitted expression exists purely to align our sourcemap
77829                 // emit with the original emitter.
77830                 var outer = ts.createPartiallyEmittedExpression(localName);
77831                 outer.end = closingBraceLocation.end;
77832                 ts.setEmitFlags(outer, 1536 /* NoComments */);
77833                 var statement = ts.createReturn(outer);
77834                 statement.pos = closingBraceLocation.pos;
77835                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
77836                 statements.push(statement);
77837                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
77838                 var iife = ts.createImmediatelyInvokedArrowFunction(statements);
77839                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
77840                 var varStatement = ts.createVariableStatement(
77841                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
77842                     ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
77843                     /*type*/ undefined, iife)
77844                 ]));
77845                 ts.setOriginalNode(varStatement, node);
77846                 ts.setCommentRange(varStatement, node);
77847                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
77848                 ts.startOnNewLine(varStatement);
77849                 statements = [varStatement];
77850             }
77851             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
77852             // Otherwise, if the class was exported at the top level and was decorated, emit an export
77853             // declaration or export default for the class.
77854             if (facts & 8 /* IsExportOfNamespace */) {
77855                 addExportMemberAssignment(statements, node);
77856             }
77857             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
77858                 if (facts & 32 /* IsDefaultExternalExport */) {
77859                     statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77860                 }
77861                 else if (facts & 16 /* IsNamedExternalExport */) {
77862                     statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77863                 }
77864             }
77865             if (statements.length > 1) {
77866                 // Add a DeclarationMarker as a marker for the end of the declaration
77867                 statements.push(ts.createEndOfDeclarationMarker(node));
77868                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
77869             }
77870             return ts.singleOrMany(statements);
77871         }
77872         /**
77873          * Transforms a non-decorated class declaration and appends the resulting statements.
77874          *
77875          * @param node A ClassDeclaration node.
77876          * @param name The name of the class.
77877          * @param facts Precomputed facts about the class.
77878          */
77879         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
77880             //  ${modifiers} class ${name} ${heritageClauses} {
77881             //      ${members}
77882             //  }
77883             // we do not emit modifiers on the declaration if we are emitting an IIFE
77884             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
77885                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
77886                 : undefined;
77887             var classDeclaration = ts.createClassDeclaration(
77888             /*decorators*/ undefined, modifiers, name, 
77889             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
77890             // To better align with the old emitter, we should not emit a trailing source map
77891             // entry if the class has static properties.
77892             var emitFlags = ts.getEmitFlags(node);
77893             if (facts & 1 /* HasStaticInitializedProperties */) {
77894                 emitFlags |= 32 /* NoTrailingSourceMap */;
77895             }
77896             ts.aggregateTransformFlags(classDeclaration);
77897             ts.setTextRange(classDeclaration, node);
77898             ts.setOriginalNode(classDeclaration, node);
77899             ts.setEmitFlags(classDeclaration, emitFlags);
77900             return classDeclaration;
77901         }
77902         /**
77903          * Transforms a decorated class declaration and appends the resulting statements. If
77904          * the class requires an alias to avoid issues with double-binding, the alias is returned.
77905          */
77906         function createClassDeclarationHeadWithDecorators(node, name) {
77907             // When we emit an ES6 class that has a class decorator, we must tailor the
77908             // emit to certain specific cases.
77909             //
77910             // In the simplest case, we emit the class declaration as a let declaration, and
77911             // evaluate decorators after the close of the class body:
77912             //
77913             //  [Example 1]
77914             //  ---------------------------------------------------------------------
77915             //  TypeScript                      | Javascript
77916             //  ---------------------------------------------------------------------
77917             //  @dec                            | let C = class C {
77918             //  class C {                       | }
77919             //  }                               | C = __decorate([dec], C);
77920             //  ---------------------------------------------------------------------
77921             //  @dec                            | let C = class C {
77922             //  export class C {                | }
77923             //  }                               | C = __decorate([dec], C);
77924             //                                  | export { C };
77925             //  ---------------------------------------------------------------------
77926             //
77927             // If a class declaration contains a reference to itself *inside* of the class body,
77928             // this introduces two bindings to the class: One outside of the class body, and one
77929             // inside of the class body. If we apply decorators as in [Example 1] above, there
77930             // is the possibility that the decorator `dec` will return a new value for the
77931             // constructor, which would result in the binding inside of the class no longer
77932             // pointing to the same reference as the binding outside of the class.
77933             //
77934             // As a result, we must instead rewrite all references to the class *inside* of the
77935             // class body to instead point to a local temporary alias for the class:
77936             //
77937             //  [Example 2]
77938             //  ---------------------------------------------------------------------
77939             //  TypeScript                      | Javascript
77940             //  ---------------------------------------------------------------------
77941             //  @dec                            | let C = C_1 = class C {
77942             //  class C {                       |   static x() { return C_1.y; }
77943             //    static x() { return C.y; }    | }
77944             //    static y = 1;                 | C.y = 1;
77945             //  }                               | C = C_1 = __decorate([dec], C);
77946             //                                  | var C_1;
77947             //  ---------------------------------------------------------------------
77948             //  @dec                            | let C = class C {
77949             //  export class C {                |   static x() { return C_1.y; }
77950             //    static x() { return C.y; }    | }
77951             //    static y = 1;                 | C.y = 1;
77952             //  }                               | C = C_1 = __decorate([dec], C);
77953             //                                  | export { C };
77954             //                                  | var C_1;
77955             //  ---------------------------------------------------------------------
77956             //
77957             // If a class declaration is the default export of a module, we instead emit
77958             // the export after the decorated declaration:
77959             //
77960             //  [Example 3]
77961             //  ---------------------------------------------------------------------
77962             //  TypeScript                      | Javascript
77963             //  ---------------------------------------------------------------------
77964             //  @dec                            | let default_1 = class {
77965             //  export default class {          | }
77966             //  }                               | default_1 = __decorate([dec], default_1);
77967             //                                  | export default default_1;
77968             //  ---------------------------------------------------------------------
77969             //  @dec                            | let C = class C {
77970             //  export default class C {        | }
77971             //  }                               | C = __decorate([dec], C);
77972             //                                  | export default C;
77973             //  ---------------------------------------------------------------------
77974             //
77975             // If the class declaration is the default export and a reference to itself
77976             // inside of the class body, we must emit both an alias for the class *and*
77977             // move the export after the declaration:
77978             //
77979             //  [Example 4]
77980             //  ---------------------------------------------------------------------
77981             //  TypeScript                      | Javascript
77982             //  ---------------------------------------------------------------------
77983             //  @dec                            | let C = class C {
77984             //  export default class C {        |   static x() { return C_1.y; }
77985             //    static x() { return C.y; }    | }
77986             //    static y = 1;                 | C.y = 1;
77987             //  }                               | C = C_1 = __decorate([dec], C);
77988             //                                  | export default C;
77989             //                                  | var C_1;
77990             //  ---------------------------------------------------------------------
77991             //
77992             var location = ts.moveRangePastDecorators(node);
77993             var classAlias = getClassAliasIfNeeded(node);
77994             var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
77995             //  ... = class ${name} ${heritageClauses} {
77996             //      ${members}
77997             //  }
77998             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
77999             var members = transformClassMembers(node);
78000             var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
78001             ts.aggregateTransformFlags(classExpression);
78002             ts.setOriginalNode(classExpression, node);
78003             ts.setTextRange(classExpression, location);
78004             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
78005             //                                         or decoratedClassAlias if the class contain self-reference.
78006             var statement = ts.createVariableStatement(
78007             /*modifiers*/ undefined, ts.createVariableDeclarationList([
78008                 ts.createVariableDeclaration(declName, 
78009                 /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
78010             ], 1 /* Let */));
78011             ts.setOriginalNode(statement, node);
78012             ts.setTextRange(statement, location);
78013             ts.setCommentRange(statement, node);
78014             return statement;
78015         }
78016         function visitClassExpression(node) {
78017             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
78018                 return ts.visitEachChild(node, visitor, context);
78019             }
78020             var classExpression = ts.createClassExpression(
78021             /*modifiers*/ undefined, node.name, 
78022             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
78023             ts.aggregateTransformFlags(classExpression);
78024             ts.setOriginalNode(classExpression, node);
78025             ts.setTextRange(classExpression, node);
78026             return classExpression;
78027         }
78028         /**
78029          * Transforms the members of a class.
78030          *
78031          * @param node The current class.
78032          */
78033         function transformClassMembers(node) {
78034             var members = [];
78035             var constructor = ts.getFirstConstructorWithBody(node);
78036             var parametersWithPropertyAssignments = constructor &&
78037                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78038             if (parametersWithPropertyAssignments) {
78039                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
78040                     var parameter = parametersWithPropertyAssignments_1[_i];
78041                     if (ts.isIdentifier(parameter.name)) {
78042                         members.push(ts.setOriginalNode(ts.aggregateTransformFlags(ts.createProperty(
78043                         /*decorators*/ undefined, 
78044                         /*modifiers*/ undefined, parameter.name, 
78045                         /*questionOrExclamationToken*/ undefined, 
78046                         /*type*/ undefined, 
78047                         /*initializer*/ undefined)), parameter));
78048                     }
78049                 }
78050             }
78051             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
78052             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
78053         }
78054         /**
78055          * Gets either the static or instance members of a class that are decorated, or have
78056          * parameters that are decorated.
78057          *
78058          * @param node The class containing the member.
78059          * @param isStatic A value indicating whether to retrieve static or instance members of
78060          *                 the class.
78061          */
78062         function getDecoratedClassElements(node, isStatic) {
78063             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
78064         }
78065         /**
78066          * Determines whether a class member is a static member of a class that is decorated, or
78067          * has parameters that are decorated.
78068          *
78069          * @param member The class member.
78070          */
78071         function isStaticDecoratedClassElement(member, parent) {
78072             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
78073         }
78074         /**
78075          * Determines whether a class member is an instance member of a class that is decorated,
78076          * or has parameters that are decorated.
78077          *
78078          * @param member The class member.
78079          */
78080         function isInstanceDecoratedClassElement(member, parent) {
78081             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
78082         }
78083         /**
78084          * Determines whether a class member is either a static or an instance member of a class
78085          * that is decorated, or has parameters that are decorated.
78086          *
78087          * @param member The class member.
78088          */
78089         function isDecoratedClassElement(member, isStatic, parent) {
78090             return ts.nodeOrChildIsDecorated(member, parent)
78091                 && isStatic === ts.hasModifier(member, 32 /* Static */);
78092         }
78093         /**
78094          * Gets an array of arrays of decorators for the parameters of a function-like node.
78095          * The offset into the result array should correspond to the offset of the parameter.
78096          *
78097          * @param node The function-like node.
78098          */
78099         function getDecoratorsOfParameters(node) {
78100             var decorators;
78101             if (node) {
78102                 var parameters = node.parameters;
78103                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
78104                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
78105                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
78106                 for (var i = 0; i < numParameters; i++) {
78107                     var parameter = parameters[i + firstParameterOffset];
78108                     if (decorators || parameter.decorators) {
78109                         if (!decorators) {
78110                             decorators = new Array(numParameters);
78111                         }
78112                         decorators[i] = parameter.decorators;
78113                     }
78114                 }
78115             }
78116             return decorators;
78117         }
78118         /**
78119          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
78120          * parameters of the constructor of the class.
78121          *
78122          * @param node The class node.
78123          */
78124         function getAllDecoratorsOfConstructor(node) {
78125             var decorators = node.decorators;
78126             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
78127             if (!decorators && !parameters) {
78128                 return undefined;
78129             }
78130             return {
78131                 decorators: decorators,
78132                 parameters: parameters
78133             };
78134         }
78135         /**
78136          * Gets an AllDecorators object containing the decorators for the member and its parameters.
78137          *
78138          * @param node The class node that contains the member.
78139          * @param member The class member.
78140          */
78141         function getAllDecoratorsOfClassElement(node, member) {
78142             switch (member.kind) {
78143                 case 163 /* GetAccessor */:
78144                 case 164 /* SetAccessor */:
78145                     return getAllDecoratorsOfAccessors(node, member);
78146                 case 161 /* MethodDeclaration */:
78147                     return getAllDecoratorsOfMethod(member);
78148                 case 159 /* PropertyDeclaration */:
78149                     return getAllDecoratorsOfProperty(member);
78150                 default:
78151                     return undefined;
78152             }
78153         }
78154         /**
78155          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
78156          *
78157          * @param node The class node that contains the accessor.
78158          * @param accessor The class accessor member.
78159          */
78160         function getAllDecoratorsOfAccessors(node, accessor) {
78161             if (!accessor.body) {
78162                 return undefined;
78163             }
78164             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
78165             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
78166             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
78167                 return undefined;
78168             }
78169             var decorators = firstAccessorWithDecorators.decorators;
78170             var parameters = getDecoratorsOfParameters(setAccessor);
78171             if (!decorators && !parameters) {
78172                 return undefined;
78173             }
78174             return { decorators: decorators, parameters: parameters };
78175         }
78176         /**
78177          * Gets an AllDecorators object containing the decorators for the method and its parameters.
78178          *
78179          * @param method The class method member.
78180          */
78181         function getAllDecoratorsOfMethod(method) {
78182             if (!method.body) {
78183                 return undefined;
78184             }
78185             var decorators = method.decorators;
78186             var parameters = getDecoratorsOfParameters(method);
78187             if (!decorators && !parameters) {
78188                 return undefined;
78189             }
78190             return { decorators: decorators, parameters: parameters };
78191         }
78192         /**
78193          * Gets an AllDecorators object containing the decorators for the property.
78194          *
78195          * @param property The class property member.
78196          */
78197         function getAllDecoratorsOfProperty(property) {
78198             var decorators = property.decorators;
78199             if (!decorators) {
78200                 return undefined;
78201             }
78202             return { decorators: decorators };
78203         }
78204         /**
78205          * Transforms all of the decorators for a declaration into an array of expressions.
78206          *
78207          * @param node The declaration node.
78208          * @param allDecorators An object containing all of the decorators for the declaration.
78209          */
78210         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
78211             if (!allDecorators) {
78212                 return undefined;
78213             }
78214             var decoratorExpressions = [];
78215             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
78216             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
78217             addTypeMetadata(node, container, decoratorExpressions);
78218             return decoratorExpressions;
78219         }
78220         /**
78221          * Generates statements used to apply decorators to either the static or instance members
78222          * of a class.
78223          *
78224          * @param node The class node.
78225          * @param isStatic A value indicating whether to generate statements for static or
78226          *                 instance members.
78227          */
78228         function addClassElementDecorationStatements(statements, node, isStatic) {
78229             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
78230         }
78231         /**
78232          * Generates expressions used to apply decorators to either the static or instance members
78233          * of a class.
78234          *
78235          * @param node The class node.
78236          * @param isStatic A value indicating whether to generate expressions for static or
78237          *                 instance members.
78238          */
78239         function generateClassElementDecorationExpressions(node, isStatic) {
78240             var members = getDecoratedClassElements(node, isStatic);
78241             var expressions;
78242             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
78243                 var member = members_6[_i];
78244                 var expression = generateClassElementDecorationExpression(node, member);
78245                 if (expression) {
78246                     if (!expressions) {
78247                         expressions = [expression];
78248                     }
78249                     else {
78250                         expressions.push(expression);
78251                     }
78252                 }
78253             }
78254             return expressions;
78255         }
78256         /**
78257          * Generates an expression used to evaluate class element decorators at runtime.
78258          *
78259          * @param node The class node that contains the member.
78260          * @param member The class member.
78261          */
78262         function generateClassElementDecorationExpression(node, member) {
78263             var allDecorators = getAllDecoratorsOfClassElement(node, member);
78264             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
78265             if (!decoratorExpressions) {
78266                 return undefined;
78267             }
78268             // Emit the call to __decorate. Given the following:
78269             //
78270             //   class C {
78271             //     @dec method(@dec2 x) {}
78272             //     @dec get accessor() {}
78273             //     @dec prop;
78274             //   }
78275             //
78276             // The emit for a method is:
78277             //
78278             //   __decorate([
78279             //       dec,
78280             //       __param(0, dec2),
78281             //       __metadata("design:type", Function),
78282             //       __metadata("design:paramtypes", [Object]),
78283             //       __metadata("design:returntype", void 0)
78284             //   ], C.prototype, "method", null);
78285             //
78286             // The emit for an accessor is:
78287             //
78288             //   __decorate([
78289             //       dec
78290             //   ], C.prototype, "accessor", null);
78291             //
78292             // The emit for a property is:
78293             //
78294             //   __decorate([
78295             //       dec
78296             //   ], C.prototype, "prop");
78297             //
78298             var prefix = getClassMemberPrefix(node, member);
78299             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
78300             var descriptor = languageVersion > 0 /* ES3 */
78301                 ? member.kind === 159 /* PropertyDeclaration */
78302                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
78303                     // should not invoke `Object.getOwnPropertyDescriptor`.
78304                     ? ts.createVoidZero()
78305                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
78306                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
78307                     : ts.createNull()
78308                 : undefined;
78309             var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
78310             ts.setEmitFlags(helper, 1536 /* NoComments */);
78311             return helper;
78312         }
78313         /**
78314          * Generates a __decorate helper call for a class constructor.
78315          *
78316          * @param node The class node.
78317          */
78318         function addConstructorDecorationStatement(statements, node) {
78319             var expression = generateConstructorDecorationExpression(node);
78320             if (expression) {
78321                 statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
78322             }
78323         }
78324         /**
78325          * Generates a __decorate helper call for a class constructor.
78326          *
78327          * @param node The class node.
78328          */
78329         function generateConstructorDecorationExpression(node) {
78330             var allDecorators = getAllDecoratorsOfConstructor(node);
78331             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
78332             if (!decoratorExpressions) {
78333                 return undefined;
78334             }
78335             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
78336             var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
78337             var decorate = createDecorateHelper(context, decoratorExpressions, localName);
78338             var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
78339             ts.setEmitFlags(expression, 1536 /* NoComments */);
78340             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
78341             return expression;
78342         }
78343         /**
78344          * Transforms a decorator into an expression.
78345          *
78346          * @param decorator The decorator node.
78347          */
78348         function transformDecorator(decorator) {
78349             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
78350         }
78351         /**
78352          * Transforms the decorators of a parameter.
78353          *
78354          * @param decorators The decorators for the parameter at the provided offset.
78355          * @param parameterOffset The offset of the parameter.
78356          */
78357         function transformDecoratorsOfParameter(decorators, parameterOffset) {
78358             var expressions;
78359             if (decorators) {
78360                 expressions = [];
78361                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
78362                     var decorator = decorators_1[_i];
78363                     var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, 
78364                     /*location*/ decorator.expression);
78365                     ts.setEmitFlags(helper, 1536 /* NoComments */);
78366                     expressions.push(helper);
78367                 }
78368             }
78369             return expressions;
78370         }
78371         /**
78372          * Adds optional type metadata for a declaration.
78373          *
78374          * @param node The declaration node.
78375          * @param decoratorExpressions The destination array to which to add new decorator expressions.
78376          */
78377         function addTypeMetadata(node, container, decoratorExpressions) {
78378             if (USE_NEW_TYPE_METADATA_FORMAT) {
78379                 addNewTypeMetadata(node, container, decoratorExpressions);
78380             }
78381             else {
78382                 addOldTypeMetadata(node, container, decoratorExpressions);
78383             }
78384         }
78385         function addOldTypeMetadata(node, container, decoratorExpressions) {
78386             if (compilerOptions.emitDecoratorMetadata) {
78387                 if (shouldAddTypeMetadata(node)) {
78388                     decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
78389                 }
78390                 if (shouldAddParamTypesMetadata(node)) {
78391                     decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
78392                 }
78393                 if (shouldAddReturnTypeMetadata(node)) {
78394                     decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
78395                 }
78396             }
78397         }
78398         function addNewTypeMetadata(node, container, decoratorExpressions) {
78399             if (compilerOptions.emitDecoratorMetadata) {
78400                 var properties = void 0;
78401                 if (shouldAddTypeMetadata(node)) {
78402                     (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
78403                 }
78404                 if (shouldAddParamTypesMetadata(node)) {
78405                     (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
78406                 }
78407                 if (shouldAddReturnTypeMetadata(node)) {
78408                     (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
78409                 }
78410                 if (properties) {
78411                     decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
78412                 }
78413             }
78414         }
78415         /**
78416          * Determines whether to emit the "design:type" metadata based on the node's kind.
78417          * The caller should have already tested whether the node has decorators and whether the
78418          * emitDecoratorMetadata compiler option is set.
78419          *
78420          * @param node The node to test.
78421          */
78422         function shouldAddTypeMetadata(node) {
78423             var kind = node.kind;
78424             return kind === 161 /* MethodDeclaration */
78425                 || kind === 163 /* GetAccessor */
78426                 || kind === 164 /* SetAccessor */
78427                 || kind === 159 /* PropertyDeclaration */;
78428         }
78429         /**
78430          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
78431          * The caller should have already tested whether the node has decorators and whether the
78432          * emitDecoratorMetadata compiler option is set.
78433          *
78434          * @param node The node to test.
78435          */
78436         function shouldAddReturnTypeMetadata(node) {
78437             return node.kind === 161 /* MethodDeclaration */;
78438         }
78439         /**
78440          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
78441          * The caller should have already tested whether the node has decorators and whether the
78442          * emitDecoratorMetadata compiler option is set.
78443          *
78444          * @param node The node to test.
78445          */
78446         function shouldAddParamTypesMetadata(node) {
78447             switch (node.kind) {
78448                 case 245 /* ClassDeclaration */:
78449                 case 214 /* ClassExpression */:
78450                     return ts.getFirstConstructorWithBody(node) !== undefined;
78451                 case 161 /* MethodDeclaration */:
78452                 case 163 /* GetAccessor */:
78453                 case 164 /* SetAccessor */:
78454                     return true;
78455             }
78456             return false;
78457         }
78458         function getAccessorTypeNode(node) {
78459             var accessors = resolver.getAllAccessorDeclarations(node);
78460             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
78461                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
78462         }
78463         /**
78464          * Serializes the type of a node for use with decorator type metadata.
78465          *
78466          * @param node The node that should have its type serialized.
78467          */
78468         function serializeTypeOfNode(node) {
78469             switch (node.kind) {
78470                 case 159 /* PropertyDeclaration */:
78471                 case 156 /* Parameter */:
78472                     return serializeTypeNode(node.type);
78473                 case 164 /* SetAccessor */:
78474                 case 163 /* GetAccessor */:
78475                     return serializeTypeNode(getAccessorTypeNode(node));
78476                 case 245 /* ClassDeclaration */:
78477                 case 214 /* ClassExpression */:
78478                 case 161 /* MethodDeclaration */:
78479                     return ts.createIdentifier("Function");
78480                 default:
78481                     return ts.createVoidZero();
78482             }
78483         }
78484         /**
78485          * Serializes the types of the parameters of a node for use with decorator type metadata.
78486          *
78487          * @param node The node that should have its parameter types serialized.
78488          */
78489         function serializeParameterTypesOfNode(node, container) {
78490             var valueDeclaration = ts.isClassLike(node)
78491                 ? ts.getFirstConstructorWithBody(node)
78492                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
78493                     ? node
78494                     : undefined;
78495             var expressions = [];
78496             if (valueDeclaration) {
78497                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
78498                 var numParameters = parameters.length;
78499                 for (var i = 0; i < numParameters; i++) {
78500                     var parameter = parameters[i];
78501                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
78502                         continue;
78503                     }
78504                     if (parameter.dotDotDotToken) {
78505                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
78506                     }
78507                     else {
78508                         expressions.push(serializeTypeOfNode(parameter));
78509                     }
78510                 }
78511             }
78512             return ts.createArrayLiteral(expressions);
78513         }
78514         function getParametersOfDecoratedDeclaration(node, container) {
78515             if (container && node.kind === 163 /* GetAccessor */) {
78516                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
78517                 if (setAccessor) {
78518                     return setAccessor.parameters;
78519                 }
78520             }
78521             return node.parameters;
78522         }
78523         /**
78524          * Serializes the return type of a node for use with decorator type metadata.
78525          *
78526          * @param node The node that should have its return type serialized.
78527          */
78528         function serializeReturnTypeOfNode(node) {
78529             if (ts.isFunctionLike(node) && node.type) {
78530                 return serializeTypeNode(node.type);
78531             }
78532             else if (ts.isAsyncFunction(node)) {
78533                 return ts.createIdentifier("Promise");
78534             }
78535             return ts.createVoidZero();
78536         }
78537         /**
78538          * Serializes a type node for use with decorator type metadata.
78539          *
78540          * Types are serialized in the following fashion:
78541          * - Void types point to "undefined" (e.g. "void 0")
78542          * - Function and Constructor types point to the global "Function" constructor.
78543          * - Interface types with a call or construct signature types point to the global
78544          *   "Function" constructor.
78545          * - Array and Tuple types point to the global "Array" constructor.
78546          * - Type predicates and booleans point to the global "Boolean" constructor.
78547          * - String literal types and strings point to the global "String" constructor.
78548          * - Enum and number types point to the global "Number" constructor.
78549          * - Symbol types point to the global "Symbol" constructor.
78550          * - Type references to classes (or class-like variables) point to the constructor for the class.
78551          * - Anything else points to the global "Object" constructor.
78552          *
78553          * @param node The type node to serialize.
78554          */
78555         function serializeTypeNode(node) {
78556             if (node === undefined) {
78557                 return ts.createIdentifier("Object");
78558             }
78559             switch (node.kind) {
78560                 case 110 /* VoidKeyword */:
78561                 case 146 /* UndefinedKeyword */:
78562                 case 100 /* NullKeyword */:
78563                 case 137 /* NeverKeyword */:
78564                     return ts.createVoidZero();
78565                 case 182 /* ParenthesizedType */:
78566                     return serializeTypeNode(node.type);
78567                 case 170 /* FunctionType */:
78568                 case 171 /* ConstructorType */:
78569                     return ts.createIdentifier("Function");
78570                 case 174 /* ArrayType */:
78571                 case 175 /* TupleType */:
78572                     return ts.createIdentifier("Array");
78573                 case 168 /* TypePredicate */:
78574                 case 128 /* BooleanKeyword */:
78575                     return ts.createIdentifier("Boolean");
78576                 case 143 /* StringKeyword */:
78577                     return ts.createIdentifier("String");
78578                 case 141 /* ObjectKeyword */:
78579                     return ts.createIdentifier("Object");
78580                 case 187 /* LiteralType */:
78581                     switch (node.literal.kind) {
78582                         case 10 /* StringLiteral */:
78583                             return ts.createIdentifier("String");
78584                         case 207 /* PrefixUnaryExpression */:
78585                         case 8 /* NumericLiteral */:
78586                             return ts.createIdentifier("Number");
78587                         case 9 /* BigIntLiteral */:
78588                             return getGlobalBigIntNameWithFallback();
78589                         case 106 /* TrueKeyword */:
78590                         case 91 /* FalseKeyword */:
78591                             return ts.createIdentifier("Boolean");
78592                         default:
78593                             return ts.Debug.failBadSyntaxKind(node.literal);
78594                     }
78595                 case 140 /* NumberKeyword */:
78596                     return ts.createIdentifier("Number");
78597                 case 151 /* BigIntKeyword */:
78598                     return getGlobalBigIntNameWithFallback();
78599                 case 144 /* SymbolKeyword */:
78600                     return languageVersion < 2 /* ES2015 */
78601                         ? getGlobalSymbolNameWithFallback()
78602                         : ts.createIdentifier("Symbol");
78603                 case 169 /* TypeReference */:
78604                     return serializeTypeReferenceNode(node);
78605                 case 179 /* IntersectionType */:
78606                 case 178 /* UnionType */:
78607                     return serializeTypeList(node.types);
78608                 case 180 /* ConditionalType */:
78609                     return serializeTypeList([node.trueType, node.falseType]);
78610                 case 184 /* TypeOperator */:
78611                     if (node.operator === 138 /* ReadonlyKeyword */) {
78612                         return serializeTypeNode(node.type);
78613                     }
78614                     break;
78615                 case 172 /* TypeQuery */:
78616                 case 185 /* IndexedAccessType */:
78617                 case 186 /* MappedType */:
78618                 case 173 /* TypeLiteral */:
78619                 case 125 /* AnyKeyword */:
78620                 case 148 /* UnknownKeyword */:
78621                 case 183 /* ThisType */:
78622                 case 188 /* ImportType */:
78623                     break;
78624                 // handle JSDoc types from an invalid parse
78625                 case 295 /* JSDocAllType */:
78626                 case 296 /* JSDocUnknownType */:
78627                 case 300 /* JSDocFunctionType */:
78628                 case 301 /* JSDocVariadicType */:
78629                 case 302 /* JSDocNamepathType */:
78630                     break;
78631                 case 297 /* JSDocNullableType */:
78632                 case 298 /* JSDocNonNullableType */:
78633                 case 299 /* JSDocOptionalType */:
78634                     return serializeTypeNode(node.type);
78635                 default:
78636                     return ts.Debug.failBadSyntaxKind(node);
78637             }
78638             return ts.createIdentifier("Object");
78639         }
78640         function serializeTypeList(types) {
78641             // Note when updating logic here also update getEntityNameForDecoratorMetadata
78642             // so that aliases can be marked as referenced
78643             var serializedUnion;
78644             for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
78645                 var typeNode = types_21[_i];
78646                 while (typeNode.kind === 182 /* ParenthesizedType */) {
78647                     typeNode = typeNode.type; // Skip parens if need be
78648                 }
78649                 if (typeNode.kind === 137 /* NeverKeyword */) {
78650                     continue; // Always elide `never` from the union/intersection if possible
78651                 }
78652                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
78653                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
78654                 }
78655                 var serializedIndividual = serializeTypeNode(typeNode);
78656                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
78657                     // One of the individual is global object, return immediately
78658                     return serializedIndividual;
78659                 }
78660                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
78661                 // anything more complex and we will just default to Object
78662                 else if (serializedUnion) {
78663                     // Different types
78664                     if (!ts.isIdentifier(serializedUnion) ||
78665                         !ts.isIdentifier(serializedIndividual) ||
78666                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
78667                         return ts.createIdentifier("Object");
78668                     }
78669                 }
78670                 else {
78671                     // Initialize the union type
78672                     serializedUnion = serializedIndividual;
78673                 }
78674             }
78675             // If we were able to find common type, use it
78676             return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
78677         }
78678         /**
78679          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
78680          * decorator type metadata.
78681          *
78682          * @param node The type reference node.
78683          */
78684         function serializeTypeReferenceNode(node) {
78685             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
78686             switch (kind) {
78687                 case ts.TypeReferenceSerializationKind.Unknown:
78688                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
78689                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
78690                         return ts.createIdentifier("Object");
78691                     }
78692                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
78693                     var temp = ts.createTempVariable(hoistVariableDeclaration);
78694                     return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
78695                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
78696                     return serializeEntityNameAsExpression(node.typeName);
78697                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
78698                     return ts.createVoidZero();
78699                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
78700                     return getGlobalBigIntNameWithFallback();
78701                 case ts.TypeReferenceSerializationKind.BooleanType:
78702                     return ts.createIdentifier("Boolean");
78703                 case ts.TypeReferenceSerializationKind.NumberLikeType:
78704                     return ts.createIdentifier("Number");
78705                 case ts.TypeReferenceSerializationKind.StringLikeType:
78706                     return ts.createIdentifier("String");
78707                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
78708                     return ts.createIdentifier("Array");
78709                 case ts.TypeReferenceSerializationKind.ESSymbolType:
78710                     return languageVersion < 2 /* ES2015 */
78711                         ? getGlobalSymbolNameWithFallback()
78712                         : ts.createIdentifier("Symbol");
78713                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
78714                     return ts.createIdentifier("Function");
78715                 case ts.TypeReferenceSerializationKind.Promise:
78716                     return ts.createIdentifier("Promise");
78717                 case ts.TypeReferenceSerializationKind.ObjectType:
78718                     return ts.createIdentifier("Object");
78719                 default:
78720                     return ts.Debug.assertNever(kind);
78721             }
78722         }
78723         function createCheckedValue(left, right) {
78724             return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
78725         }
78726         /**
78727          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
78728          *
78729          * @param node The entity name to serialize.
78730          */
78731         function serializeEntityNameAsExpressionFallback(node) {
78732             if (node.kind === 75 /* Identifier */) {
78733                 // A -> typeof A !== undefined && A
78734                 var copied = serializeEntityNameAsExpression(node);
78735                 return createCheckedValue(copied, copied);
78736             }
78737             if (node.left.kind === 75 /* Identifier */) {
78738                 // A.B -> typeof A !== undefined && A.B
78739                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
78740             }
78741             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
78742             var left = serializeEntityNameAsExpressionFallback(node.left);
78743             var temp = ts.createTempVariable(hoistVariableDeclaration);
78744             return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
78745         }
78746         /**
78747          * Serializes an entity name as an expression for decorator type metadata.
78748          *
78749          * @param node The entity name to serialize.
78750          */
78751         function serializeEntityNameAsExpression(node) {
78752             switch (node.kind) {
78753                 case 75 /* Identifier */:
78754                     // Create a clone of the name with a new parent, and treat it as if it were
78755                     // a source tree node for the purposes of the checker.
78756                     var name = ts.getMutableClone(node);
78757                     name.flags &= ~8 /* Synthesized */;
78758                     name.original = undefined;
78759                     name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
78760                     return name;
78761                 case 153 /* QualifiedName */:
78762                     return serializeQualifiedNameAsExpression(node);
78763             }
78764         }
78765         /**
78766          * Serializes an qualified name as an expression for decorator type metadata.
78767          *
78768          * @param node The qualified name to serialize.
78769          * @param useFallback A value indicating whether to use logical operators to test for the
78770          *                    qualified name at runtime.
78771          */
78772         function serializeQualifiedNameAsExpression(node) {
78773             return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
78774         }
78775         /**
78776          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
78777          * available.
78778          */
78779         function getGlobalSymbolNameWithFallback() {
78780             return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
78781         }
78782         /**
78783          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
78784          * available.
78785          */
78786         function getGlobalBigIntNameWithFallback() {
78787             return languageVersion < 99 /* ESNext */
78788                 ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
78789                 : ts.createIdentifier("BigInt");
78790         }
78791         /**
78792          * Gets an expression that represents a property name (for decorated properties or enums).
78793          * For a computed property, a name is generated for the node.
78794          *
78795          * @param member The member whose name should be converted into an expression.
78796          */
78797         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
78798             var name = member.name;
78799             if (ts.isPrivateIdentifier(name)) {
78800                 return ts.createIdentifier("");
78801             }
78802             else if (ts.isComputedPropertyName(name)) {
78803                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
78804                     ? ts.getGeneratedNameForNode(name)
78805                     : name.expression;
78806             }
78807             else if (ts.isIdentifier(name)) {
78808                 return ts.createLiteral(ts.idText(name));
78809             }
78810             else {
78811                 return ts.getSynthesizedClone(name);
78812             }
78813         }
78814         /**
78815          * Visits the property name of a class element, for use when emitting property
78816          * initializers. For a computed property on a node with decorators, a temporary
78817          * value is stored for later use.
78818          *
78819          * @param member The member whose name should be visited.
78820          */
78821         function visitPropertyNameOfClassElement(member) {
78822             var name = member.name;
78823             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
78824             // The names are used more than once when:
78825             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
78826             //   - the property has a decorator.
78827             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
78828                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
78829                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
78830                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
78831                     var generatedName = ts.getGeneratedNameForNode(name);
78832                     hoistVariableDeclaration(generatedName);
78833                     return ts.updateComputedPropertyName(name, ts.createAssignment(generatedName, expression));
78834                 }
78835             }
78836             return ts.visitNode(name, visitor, ts.isPropertyName);
78837         }
78838         /**
78839          * Transforms a HeritageClause with TypeScript syntax.
78840          *
78841          * This function will only be called when one of the following conditions are met:
78842          * - The node is a non-`extends` heritage clause that should be elided.
78843          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
78844          *
78845          * @param node The HeritageClause to transform.
78846          */
78847         function visitHeritageClause(node) {
78848             if (node.token === 113 /* ImplementsKeyword */) {
78849                 // implements clauses are elided
78850                 return undefined;
78851             }
78852             return ts.visitEachChild(node, visitor, context);
78853         }
78854         /**
78855          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
78856          *
78857          * This function will only be called when one of the following conditions are met:
78858          * - The node contains type arguments that should be elided.
78859          *
78860          * @param node The ExpressionWithTypeArguments to transform.
78861          */
78862         function visitExpressionWithTypeArguments(node) {
78863             return ts.updateExpressionWithTypeArguments(node, 
78864             /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
78865         }
78866         /**
78867          * Determines whether to emit a function-like declaration. We should not emit the
78868          * declaration if it does not have a body.
78869          *
78870          * @param node The declaration node.
78871          */
78872         function shouldEmitFunctionLikeDeclaration(node) {
78873             return !ts.nodeIsMissing(node.body);
78874         }
78875         function visitPropertyDeclaration(node) {
78876             if (node.flags & 8388608 /* Ambient */) {
78877                 return undefined;
78878             }
78879             var updated = ts.updateProperty(node, 
78880             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
78881             /*questionOrExclamationToken*/ undefined, 
78882             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
78883             if (updated !== node) {
78884                 // While we emit the source map for the node after skipping decorators and modifiers,
78885                 // we need to emit the comments for the original range.
78886                 ts.setCommentRange(updated, node);
78887                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78888             }
78889             return updated;
78890         }
78891         function visitConstructor(node) {
78892             if (!shouldEmitFunctionLikeDeclaration(node)) {
78893                 return undefined;
78894             }
78895             return ts.updateConstructor(node, 
78896             /*decorators*/ undefined, 
78897             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
78898         }
78899         function transformConstructorBody(body, constructor) {
78900             var parametersWithPropertyAssignments = constructor &&
78901                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78902             if (!ts.some(parametersWithPropertyAssignments)) {
78903                 return ts.visitFunctionBody(body, visitor, context);
78904             }
78905             var statements = [];
78906             var indexOfFirstStatement = 0;
78907             resumeLexicalEnvironment();
78908             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
78909             // Add parameters with property assignments. Transforms this:
78910             //
78911             //  constructor (public x, public y) {
78912             //  }
78913             //
78914             // Into this:
78915             //
78916             //  constructor (x, y) {
78917             //      this.x = x;
78918             //      this.y = y;
78919             //  }
78920             //
78921             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
78922             // Add the existing statements, skipping the initial super call.
78923             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
78924             // End the lexical environment.
78925             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
78926             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), body.statements), /*multiLine*/ true);
78927             ts.setTextRange(block, /*location*/ body);
78928             ts.setOriginalNode(block, body);
78929             return block;
78930         }
78931         /**
78932          * Transforms a parameter into a property assignment statement.
78933          *
78934          * @param node The parameter declaration.
78935          */
78936         function transformParameterWithPropertyAssignment(node) {
78937             var name = node.name;
78938             if (!ts.isIdentifier(name)) {
78939                 return undefined;
78940             }
78941             var propertyName = ts.getMutableClone(name);
78942             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
78943             var localName = ts.getMutableClone(name);
78944             ts.setEmitFlags(localName, 1536 /* NoComments */);
78945             return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1))));
78946         }
78947         function visitMethodDeclaration(node) {
78948             if (!shouldEmitFunctionLikeDeclaration(node)) {
78949                 return undefined;
78950             }
78951             var updated = ts.updateMethod(node, 
78952             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
78953             /*questionToken*/ undefined, 
78954             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78955             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
78956             if (updated !== node) {
78957                 // While we emit the source map for the node after skipping decorators and modifiers,
78958                 // we need to emit the comments for the original range.
78959                 ts.setCommentRange(updated, node);
78960                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78961             }
78962             return updated;
78963         }
78964         /**
78965          * Determines whether to emit an accessor declaration. We should not emit the
78966          * declaration if it does not have a body and is abstract.
78967          *
78968          * @param node The declaration node.
78969          */
78970         function shouldEmitAccessorDeclaration(node) {
78971             return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
78972         }
78973         function visitGetAccessor(node) {
78974             if (!shouldEmitAccessorDeclaration(node)) {
78975                 return undefined;
78976             }
78977             var updated = ts.updateGetAccessor(node, 
78978             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
78979             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78980             if (updated !== node) {
78981                 // While we emit the source map for the node after skipping decorators and modifiers,
78982                 // we need to emit the comments for the original range.
78983                 ts.setCommentRange(updated, node);
78984                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78985             }
78986             return updated;
78987         }
78988         function visitSetAccessor(node) {
78989             if (!shouldEmitAccessorDeclaration(node)) {
78990                 return undefined;
78991             }
78992             var updated = ts.updateSetAccessor(node, 
78993             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78994             if (updated !== node) {
78995                 // While we emit the source map for the node after skipping decorators and modifiers,
78996                 // we need to emit the comments for the original range.
78997                 ts.setCommentRange(updated, node);
78998                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78999             }
79000             return updated;
79001         }
79002         function visitFunctionDeclaration(node) {
79003             if (!shouldEmitFunctionLikeDeclaration(node)) {
79004                 return ts.createNotEmittedStatement(node);
79005             }
79006             var updated = ts.updateFunctionDeclaration(node, 
79007             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
79008             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79009             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79010             if (isExportOfNamespace(node)) {
79011                 var statements = [updated];
79012                 addExportMemberAssignment(statements, node);
79013                 return statements;
79014             }
79015             return updated;
79016         }
79017         function visitFunctionExpression(node) {
79018             if (!shouldEmitFunctionLikeDeclaration(node)) {
79019                 return ts.createOmittedExpression();
79020             }
79021             var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
79022             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79023             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79024             return updated;
79025         }
79026         function visitArrowFunction(node) {
79027             var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
79028             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79029             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
79030             return updated;
79031         }
79032         function visitParameter(node) {
79033             if (ts.parameterIsThisKeyword(node)) {
79034                 return undefined;
79035             }
79036             var updated = ts.updateParameter(node, 
79037             /*decorators*/ undefined, 
79038             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
79039             /*questionToken*/ undefined, 
79040             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79041             if (updated !== node) {
79042                 // While we emit the source map for the node after skipping decorators and modifiers,
79043                 // we need to emit the comments for the original range.
79044                 ts.setCommentRange(updated, node);
79045                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
79046                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
79047                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
79048             }
79049             return updated;
79050         }
79051         function visitVariableStatement(node) {
79052             if (isExportOfNamespace(node)) {
79053                 var variables = ts.getInitializedVariables(node.declarationList);
79054                 if (variables.length === 0) {
79055                     // elide statement if there are no initialized variables.
79056                     return undefined;
79057                 }
79058                 return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
79059             }
79060             else {
79061                 return ts.visitEachChild(node, visitor, context);
79062             }
79063         }
79064         function transformInitializedVariable(node) {
79065             var name = node.name;
79066             if (ts.isBindingPattern(name)) {
79067                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
79068                 /*needsValue*/ false, createNamespaceExportExpression);
79069             }
79070             else {
79071                 return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
79072                 /*location*/ node);
79073             }
79074         }
79075         function visitVariableDeclaration(node) {
79076             return ts.updateTypeScriptVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
79077             /*exclaimationToken*/ undefined, 
79078             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79079         }
79080         function visitParenthesizedExpression(node) {
79081             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
79082             if (ts.isAssertionExpression(innerExpression)) {
79083                 // Make sure we consider all nested cast expressions, e.g.:
79084                 // (<any><number><any>-A).x;
79085                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79086                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
79087                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
79088                 // the parentheses, however, could cause change in the semantics of the generated
79089                 // code if the casted expression has a lower precedence than the rest of the
79090                 // expression.
79091                 //
79092                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
79093                 // preserve the position information of the original expression.
79094                 //
79095                 // Due to the auto-parenthesization rules used by the visitor and factory functions
79096                 // we can safely elide the parentheses here, as a new synthetic
79097                 // ParenthesizedExpression will be inserted if we remove parentheses too
79098                 // aggressively.
79099                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
79100                 // correctly for return and throw, we must keep the parenthesis
79101                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
79102                     return ts.updateParen(node, expression);
79103                 }
79104                 return ts.createPartiallyEmittedExpression(expression, node);
79105             }
79106             return ts.visitEachChild(node, visitor, context);
79107         }
79108         function visitAssertionExpression(node) {
79109             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79110             return ts.createPartiallyEmittedExpression(expression, node);
79111         }
79112         function visitNonNullExpression(node) {
79113             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
79114             return ts.createPartiallyEmittedExpression(expression, node);
79115         }
79116         function visitCallExpression(node) {
79117             return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79118             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79119         }
79120         function visitNewExpression(node) {
79121             return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79122             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79123         }
79124         function visitTaggedTemplateExpression(node) {
79125             return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
79126             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
79127         }
79128         function visitJsxSelfClosingElement(node) {
79129             return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79130             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79131         }
79132         function visitJsxJsxOpeningElement(node) {
79133             return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79134             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79135         }
79136         /**
79137          * Determines whether to emit an enum declaration.
79138          *
79139          * @param node The enum declaration node.
79140          */
79141         function shouldEmitEnumDeclaration(node) {
79142             return !ts.isEnumConst(node)
79143                 || compilerOptions.preserveConstEnums
79144                 || compilerOptions.isolatedModules;
79145         }
79146         /**
79147          * Visits an enum declaration.
79148          *
79149          * This function will be called any time a TypeScript enum is encountered.
79150          *
79151          * @param node The enum declaration node.
79152          */
79153         function visitEnumDeclaration(node) {
79154             if (!shouldEmitEnumDeclaration(node)) {
79155                 return ts.createNotEmittedStatement(node);
79156             }
79157             var statements = [];
79158             // We request to be advised when the printer is about to print this node. This allows
79159             // us to set up the correct state for later substitutions.
79160             var emitFlags = 2 /* AdviseOnEmitNode */;
79161             // If needed, we should emit a variable declaration for the enum. If we emit
79162             // a leading variable declaration, we should not emit leading comments for the
79163             // enum body.
79164             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79165             if (varAdded) {
79166                 // We should still emit the comments if we are emitting a system module.
79167                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79168                     emitFlags |= 512 /* NoLeadingComments */;
79169                 }
79170             }
79171             // `parameterName` is the declaration name used inside of the enum.
79172             var parameterName = getNamespaceParameterName(node);
79173             // `containerName` is the expression used inside of the enum for assignments.
79174             var containerName = getNamespaceContainerName(node);
79175             // `exportName` is the expression used within this node's container for any exported references.
79176             var exportName = ts.hasModifier(node, 1 /* Export */)
79177                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79178                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79179             //  x || (x = {})
79180             //  exports.x || (exports.x = {})
79181             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79182             if (hasNamespaceQualifiedExportName(node)) {
79183                 // `localName` is the expression used within this node's containing scope for any local references.
79184                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79185                 //  x = (exports.x || (exports.x = {}))
79186                 moduleArg = ts.createAssignment(localName, moduleArg);
79187             }
79188             //  (function (x) {
79189             //      x[x["y"] = 0] = "y";
79190             //      ...
79191             //  })(x || (x = {}));
79192             var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79193             /*modifiers*/ undefined, 
79194             /*asteriskToken*/ undefined, 
79195             /*name*/ undefined, 
79196             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79197             /*type*/ undefined, transformEnumBody(node, containerName)), 
79198             /*typeArguments*/ undefined, [moduleArg]));
79199             ts.setOriginalNode(enumStatement, node);
79200             if (varAdded) {
79201                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79202                 ts.setSyntheticLeadingComments(enumStatement, undefined);
79203                 ts.setSyntheticTrailingComments(enumStatement, undefined);
79204             }
79205             ts.setTextRange(enumStatement, node);
79206             ts.addEmitFlags(enumStatement, emitFlags);
79207             statements.push(enumStatement);
79208             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
79209             // the end of the declaration.
79210             statements.push(ts.createEndOfDeclarationMarker(node));
79211             return statements;
79212         }
79213         /**
79214          * Transforms the body of an enum declaration.
79215          *
79216          * @param node The enum declaration node.
79217          */
79218         function transformEnumBody(node, localName) {
79219             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
79220             currentNamespaceContainerName = localName;
79221             var statements = [];
79222             startLexicalEnvironment();
79223             var members = ts.map(node.members, transformEnumMember);
79224             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79225             ts.addRange(statements, members);
79226             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
79227             return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), 
79228             /*multiLine*/ true);
79229         }
79230         /**
79231          * Transforms an enum member into a statement.
79232          *
79233          * @param member The enum member node.
79234          */
79235         function transformEnumMember(member) {
79236             // enums don't support computed properties
79237             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
79238             // old emitter always generate 'expression' part of the name as-is.
79239             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
79240             var valueExpression = transformEnumMemberDeclarationValue(member);
79241             var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
79242             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
79243                 innerAssignment :
79244                 ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
79245             return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
79246         }
79247         /**
79248          * Transforms the value of an enum member.
79249          *
79250          * @param member The enum member node.
79251          */
79252         function transformEnumMemberDeclarationValue(member) {
79253             var value = resolver.getConstantValue(member);
79254             if (value !== undefined) {
79255                 return ts.createLiteral(value);
79256             }
79257             else {
79258                 enableSubstitutionForNonQualifiedEnumMembers();
79259                 if (member.initializer) {
79260                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
79261                 }
79262                 else {
79263                     return ts.createVoidZero();
79264                 }
79265             }
79266         }
79267         /**
79268          * Determines whether to elide a module declaration.
79269          *
79270          * @param node The module declaration node.
79271          */
79272         function shouldEmitModuleDeclaration(nodeIn) {
79273             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
79274             if (!node) {
79275                 // If we can't find a parse tree node, assume the node is instantiated.
79276                 return true;
79277             }
79278             return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
79279         }
79280         /**
79281          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
79282          * or `exports.x`).
79283          */
79284         function hasNamespaceQualifiedExportName(node) {
79285             return isExportOfNamespace(node)
79286                 || (isExternalModuleExport(node)
79287                     && moduleKind !== ts.ModuleKind.ES2015
79288                     && moduleKind !== ts.ModuleKind.ES2020
79289                     && moduleKind !== ts.ModuleKind.ESNext
79290                     && moduleKind !== ts.ModuleKind.System);
79291         }
79292         /**
79293          * Records that a declaration was emitted in the current scope, if it was the first
79294          * declaration for the provided symbol.
79295          */
79296         function recordEmittedDeclarationInScope(node) {
79297             if (!currentScopeFirstDeclarationsOfName) {
79298                 currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
79299             }
79300             var name = declaredNameInScope(node);
79301             if (!currentScopeFirstDeclarationsOfName.has(name)) {
79302                 currentScopeFirstDeclarationsOfName.set(name, node);
79303             }
79304         }
79305         /**
79306          * Determines whether a declaration is the first declaration with
79307          * the same name emitted in the current scope.
79308          */
79309         function isFirstEmittedDeclarationInScope(node) {
79310             if (currentScopeFirstDeclarationsOfName) {
79311                 var name = declaredNameInScope(node);
79312                 return currentScopeFirstDeclarationsOfName.get(name) === node;
79313             }
79314             return true;
79315         }
79316         function declaredNameInScope(node) {
79317             ts.Debug.assertNode(node.name, ts.isIdentifier);
79318             return node.name.escapedText;
79319         }
79320         /**
79321          * Adds a leading VariableStatement for a enum or module declaration.
79322          */
79323         function addVarForEnumOrModuleDeclaration(statements, node) {
79324             // Emit a variable statement for the module. We emit top-level enums as a `var`
79325             // declaration to avoid static errors in global scripts scripts due to redeclaration.
79326             // enums in any other scope are emitted as a `let` declaration.
79327             var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79328                 ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
79329             ], currentLexicalScope.kind === 290 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
79330             ts.setOriginalNode(statement, node);
79331             recordEmittedDeclarationInScope(node);
79332             if (isFirstEmittedDeclarationInScope(node)) {
79333                 // Adjust the source map emit to match the old emitter.
79334                 if (node.kind === 248 /* EnumDeclaration */) {
79335                     ts.setSourceMapRange(statement.declarationList, node);
79336                 }
79337                 else {
79338                     ts.setSourceMapRange(statement, node);
79339                 }
79340                 // Trailing comments for module declaration should be emitted after the function closure
79341                 // instead of the variable statement:
79342                 //
79343                 //     /** Module comment*/
79344                 //     module m1 {
79345                 //         function foo4Export() {
79346                 //         }
79347                 //     } // trailing comment module
79348                 //
79349                 // Should emit:
79350                 //
79351                 //     /** Module comment*/
79352                 //     var m1;
79353                 //     (function (m1) {
79354                 //         function foo4Export() {
79355                 //         }
79356                 //     })(m1 || (m1 = {})); // trailing comment module
79357                 //
79358                 ts.setCommentRange(statement, node);
79359                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79360                 statements.push(statement);
79361                 return true;
79362             }
79363             else {
79364                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
79365                 // declaration we do not emit a leading variable declaration. To preserve the
79366                 // begin/end semantics of the declararation and to properly handle exports
79367                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
79368                 var mergeMarker = ts.createMergeDeclarationMarker(statement);
79369                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79370                 statements.push(mergeMarker);
79371                 return false;
79372             }
79373         }
79374         /**
79375          * Visits a module declaration node.
79376          *
79377          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
79378          *
79379          * @param node The module declaration node.
79380          */
79381         function visitModuleDeclaration(node) {
79382             if (!shouldEmitModuleDeclaration(node)) {
79383                 return ts.createNotEmittedStatement(node);
79384             }
79385             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
79386             enableSubstitutionForNamespaceExports();
79387             var statements = [];
79388             // We request to be advised when the printer is about to print this node. This allows
79389             // us to set up the correct state for later substitutions.
79390             var emitFlags = 2 /* AdviseOnEmitNode */;
79391             // If needed, we should emit a variable declaration for the module. If we emit
79392             // a leading variable declaration, we should not emit leading comments for the
79393             // module body.
79394             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79395             if (varAdded) {
79396                 // We should still emit the comments if we are emitting a system module.
79397                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79398                     emitFlags |= 512 /* NoLeadingComments */;
79399                 }
79400             }
79401             // `parameterName` is the declaration name used inside of the namespace.
79402             var parameterName = getNamespaceParameterName(node);
79403             // `containerName` is the expression used inside of the namespace for exports.
79404             var containerName = getNamespaceContainerName(node);
79405             // `exportName` is the expression used within this node's container for any exported references.
79406             var exportName = ts.hasModifier(node, 1 /* Export */)
79407                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79408                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79409             //  x || (x = {})
79410             //  exports.x || (exports.x = {})
79411             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79412             if (hasNamespaceQualifiedExportName(node)) {
79413                 // `localName` is the expression used within this node's containing scope for any local references.
79414                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79415                 //  x = (exports.x || (exports.x = {}))
79416                 moduleArg = ts.createAssignment(localName, moduleArg);
79417             }
79418             //  (function (x_1) {
79419             //      x_1.y = ...;
79420             //  })(x || (x = {}));
79421             var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79422             /*modifiers*/ undefined, 
79423             /*asteriskToken*/ undefined, 
79424             /*name*/ undefined, 
79425             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79426             /*type*/ undefined, transformModuleBody(node, containerName)), 
79427             /*typeArguments*/ undefined, [moduleArg]));
79428             ts.setOriginalNode(moduleStatement, node);
79429             if (varAdded) {
79430                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79431                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
79432                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
79433             }
79434             ts.setTextRange(moduleStatement, node);
79435             ts.addEmitFlags(moduleStatement, emitFlags);
79436             statements.push(moduleStatement);
79437             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
79438             // the end of the declaration.
79439             statements.push(ts.createEndOfDeclarationMarker(node));
79440             return statements;
79441         }
79442         /**
79443          * Transforms the body of a module declaration.
79444          *
79445          * @param node The module declaration node.
79446          */
79447         function transformModuleBody(node, namespaceLocalName) {
79448             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
79449             var savedCurrentNamespace = currentNamespace;
79450             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
79451             currentNamespaceContainerName = namespaceLocalName;
79452             currentNamespace = node;
79453             currentScopeFirstDeclarationsOfName = undefined;
79454             var statements = [];
79455             startLexicalEnvironment();
79456             var statementsLocation;
79457             var blockLocation;
79458             if (node.body) {
79459                 if (node.body.kind === 250 /* ModuleBlock */) {
79460                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
79461                     statementsLocation = node.body.statements;
79462                     blockLocation = node.body;
79463                 }
79464                 else {
79465                     var result = visitModuleDeclaration(node.body);
79466                     if (result) {
79467                         if (ts.isArray(result)) {
79468                             ts.addRange(statements, result);
79469                         }
79470                         else {
79471                             statements.push(result);
79472                         }
79473                     }
79474                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
79475                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
79476                 }
79477             }
79478             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79479             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
79480             currentNamespace = savedCurrentNamespace;
79481             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
79482             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
79483             /*location*/ statementsLocation), 
79484             /*multiLine*/ true);
79485             ts.setTextRange(block, blockLocation);
79486             // namespace hello.hi.world {
79487             //      function foo() {}
79488             //
79489             //      // TODO, blah
79490             // }
79491             //
79492             // should be emitted as
79493             //
79494             // var hello;
79495             // (function (hello) {
79496             //     var hi;
79497             //     (function (hi) {
79498             //         var world;
79499             //         (function (world) {
79500             //             function foo() { }
79501             //             // TODO, blah
79502             //         })(world = hi.world || (hi.world = {}));
79503             //     })(hi = hello.hi || (hello.hi = {}));
79504             // })(hello || (hello = {}));
79505             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
79506             if (!node.body || node.body.kind !== 250 /* ModuleBlock */) {
79507                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
79508             }
79509             return block;
79510         }
79511         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
79512             if (moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
79513                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
79514                 return recursiveInnerModule || moduleDeclaration.body;
79515             }
79516         }
79517         /**
79518          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
79519          *
79520          * @param node The import declaration node.
79521          */
79522         function visitImportDeclaration(node) {
79523             if (!node.importClause) {
79524                 // Do not elide a side-effect only import declaration.
79525                 //  import "foo";
79526                 return node;
79527             }
79528             if (node.importClause.isTypeOnly) {
79529                 // Always elide type-only imports
79530                 return undefined;
79531             }
79532             // Elide the declaration if the import clause was elided.
79533             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
79534             return importClause ||
79535                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
79536                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
79537                 ? ts.updateImportDeclaration(node, 
79538                 /*decorators*/ undefined, 
79539                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
79540                 : undefined;
79541         }
79542         /**
79543          * Visits an import clause, eliding it if it is not referenced.
79544          *
79545          * @param node The import clause node.
79546          */
79547         function visitImportClause(node) {
79548             if (node.isTypeOnly) {
79549                 return undefined;
79550             }
79551             // Elide the import clause if we elide both its name and its named bindings.
79552             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
79553             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
79554             return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings, /*isTypeOnly*/ false) : undefined;
79555         }
79556         /**
79557          * Visits named import bindings, eliding it if it is not referenced.
79558          *
79559          * @param node The named import bindings node.
79560          */
79561         function visitNamedImportBindings(node) {
79562             if (node.kind === 256 /* NamespaceImport */) {
79563                 // Elide a namespace import if it is not referenced.
79564                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79565             }
79566             else {
79567                 // Elide named imports if all of its import specifiers are elided.
79568                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
79569                 return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
79570             }
79571         }
79572         /**
79573          * Visits an import specifier, eliding it if it is not referenced.
79574          *
79575          * @param node The import specifier node.
79576          */
79577         function visitImportSpecifier(node) {
79578             // Elide an import specifier if it is not referenced.
79579             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79580         }
79581         /**
79582          * Visits an export assignment, eliding it if it does not contain a clause that resolves
79583          * to a value.
79584          *
79585          * @param node The export assignment node.
79586          */
79587         function visitExportAssignment(node) {
79588             // Elide the export assignment if it does not reference a value.
79589             return resolver.isValueAliasDeclaration(node)
79590                 ? ts.visitEachChild(node, visitor, context)
79591                 : undefined;
79592         }
79593         /**
79594          * Visits an export declaration, eliding it if it does not contain a clause that resolves
79595          * to a value.
79596          *
79597          * @param node The export declaration node.
79598          */
79599         function visitExportDeclaration(node) {
79600             if (node.isTypeOnly) {
79601                 return undefined;
79602             }
79603             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
79604                 // never elide `export <whatever> from <whereever>` declarations -
79605                 // they should be kept for sideffects/untyped exports, even when the
79606                 // type checker doesn't know about any exports
79607                 return node;
79608             }
79609             if (!resolver.isValueAliasDeclaration(node)) {
79610                 // Elide the export declaration if it does not export a value.
79611                 return undefined;
79612             }
79613             // Elide the export declaration if all of its named exports are elided.
79614             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
79615             return exportClause
79616                 ? ts.updateExportDeclaration(node, 
79617                 /*decorators*/ undefined, 
79618                 /*modifiers*/ undefined, exportClause, node.moduleSpecifier, node.isTypeOnly)
79619                 : undefined;
79620         }
79621         /**
79622          * Visits named exports, eliding it if it does not contain an export specifier that
79623          * resolves to a value.
79624          *
79625          * @param node The named exports node.
79626          */
79627         function visitNamedExports(node) {
79628             // Elide the named exports if all of its export specifiers were elided.
79629             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
79630             return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
79631         }
79632         function visitNamespaceExports(node) {
79633             return ts.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
79634         }
79635         function visitNamedExportBindings(node) {
79636             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
79637         }
79638         /**
79639          * Visits an export specifier, eliding it if it does not resolve to a value.
79640          *
79641          * @param node The export specifier node.
79642          */
79643         function visitExportSpecifier(node) {
79644             // Elide an export specifier if it does not reference a value.
79645             return resolver.isValueAliasDeclaration(node) ? node : undefined;
79646         }
79647         /**
79648          * Determines whether to emit an import equals declaration.
79649          *
79650          * @param node The import equals declaration node.
79651          */
79652         function shouldEmitImportEqualsDeclaration(node) {
79653             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
79654             // - current file is not external module
79655             // - import declaration is top level and target is value imported by entity name
79656             return resolver.isReferencedAliasDeclaration(node)
79657                 || (!ts.isExternalModule(currentSourceFile)
79658                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
79659         }
79660         /**
79661          * Visits an import equals declaration.
79662          *
79663          * @param node The import equals declaration node.
79664          */
79665         function visitImportEqualsDeclaration(node) {
79666             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
79667                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
79668                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
79669                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
79670                     return ts.setOriginalNode(ts.setTextRange(ts.createImportDeclaration(
79671                     /*decorators*/ undefined, 
79672                     /*modifiers*/ undefined, 
79673                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
79674                 }
79675                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
79676             }
79677             if (!shouldEmitImportEqualsDeclaration(node)) {
79678                 return undefined;
79679             }
79680             var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
79681             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
79682             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
79683                 //  export var ${name} = ${moduleReference};
79684                 //  var ${name} = ${moduleReference};
79685                 return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79686                     ts.setOriginalNode(ts.createVariableDeclaration(node.name, 
79687                     /*type*/ undefined, moduleReference), node)
79688                 ])), node), node);
79689             }
79690             else {
79691                 // exports.${name} = ${moduleReference};
79692                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
79693             }
79694         }
79695         /**
79696          * Gets a value indicating whether the node is exported from a namespace.
79697          *
79698          * @param node The node to test.
79699          */
79700         function isExportOfNamespace(node) {
79701             return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
79702         }
79703         /**
79704          * Gets a value indicating whether the node is exported from an external module.
79705          *
79706          * @param node The node to test.
79707          */
79708         function isExternalModuleExport(node) {
79709             return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
79710         }
79711         /**
79712          * Gets a value indicating whether the node is a named export from an external module.
79713          *
79714          * @param node The node to test.
79715          */
79716         function isNamedExternalModuleExport(node) {
79717             return isExternalModuleExport(node)
79718                 && !ts.hasModifier(node, 512 /* Default */);
79719         }
79720         /**
79721          * Gets a value indicating whether the node is the default export of an external module.
79722          *
79723          * @param node The node to test.
79724          */
79725         function isDefaultExternalModuleExport(node) {
79726             return isExternalModuleExport(node)
79727                 && ts.hasModifier(node, 512 /* Default */);
79728         }
79729         /**
79730          * Creates a statement for the provided expression. This is used in calls to `map`.
79731          */
79732         function expressionToStatement(expression) {
79733             return ts.createExpressionStatement(expression);
79734         }
79735         function addExportMemberAssignment(statements, node) {
79736             var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
79737             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
79738             var statement = ts.createExpressionStatement(expression);
79739             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
79740             statements.push(statement);
79741         }
79742         function createNamespaceExport(exportName, exportValue, location) {
79743             return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
79744         }
79745         function createNamespaceExportExpression(exportName, exportValue, location) {
79746             return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
79747         }
79748         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
79749             return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
79750         }
79751         /**
79752          * Gets the declaration name used inside of a namespace or enum.
79753          */
79754         function getNamespaceParameterName(node) {
79755             var name = ts.getGeneratedNameForNode(node);
79756             ts.setSourceMapRange(name, node.name);
79757             return name;
79758         }
79759         /**
79760          * Gets the expression used to refer to a namespace or enum within the body
79761          * of its declaration.
79762          */
79763         function getNamespaceContainerName(node) {
79764             return ts.getGeneratedNameForNode(node);
79765         }
79766         /**
79767          * Gets a local alias for a class declaration if it is a decorated class with an internal
79768          * reference to the static side of the class. This is necessary to avoid issues with
79769          * double-binding semantics for the class name.
79770          */
79771         function getClassAliasIfNeeded(node) {
79772             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
79773                 enableSubstitutionForClassAliases();
79774                 var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
79775                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
79776                 hoistVariableDeclaration(classAlias);
79777                 return classAlias;
79778             }
79779         }
79780         function getClassPrototype(node) {
79781             return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
79782         }
79783         function getClassMemberPrefix(node, member) {
79784             return ts.hasModifier(member, 32 /* Static */)
79785                 ? ts.getDeclarationName(node)
79786                 : getClassPrototype(node);
79787         }
79788         function enableSubstitutionForNonQualifiedEnumMembers() {
79789             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
79790                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79791                 context.enableSubstitution(75 /* Identifier */);
79792             }
79793         }
79794         function enableSubstitutionForClassAliases() {
79795             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
79796                 enabledSubstitutions |= 1 /* ClassAliases */;
79797                 // We need to enable substitutions for identifiers. This allows us to
79798                 // substitute class names inside of a class declaration.
79799                 context.enableSubstitution(75 /* Identifier */);
79800                 // Keep track of class aliases.
79801                 classAliases = [];
79802             }
79803         }
79804         function enableSubstitutionForNamespaceExports() {
79805             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
79806                 enabledSubstitutions |= 2 /* NamespaceExports */;
79807                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
79808                 // substitute the names of exported members of a namespace.
79809                 context.enableSubstitution(75 /* Identifier */);
79810                 context.enableSubstitution(282 /* ShorthandPropertyAssignment */);
79811                 // We need to be notified when entering and exiting namespaces.
79812                 context.enableEmitNotification(249 /* ModuleDeclaration */);
79813             }
79814         }
79815         function isTransformedModuleDeclaration(node) {
79816             return ts.getOriginalNode(node).kind === 249 /* ModuleDeclaration */;
79817         }
79818         function isTransformedEnumDeclaration(node) {
79819             return ts.getOriginalNode(node).kind === 248 /* EnumDeclaration */;
79820         }
79821         /**
79822          * Hook for node emit.
79823          *
79824          * @param hint A hint as to the intended usage of the node.
79825          * @param node The node to emit.
79826          * @param emit A callback used to emit the node in the printer.
79827          */
79828         function onEmitNode(hint, node, emitCallback) {
79829             var savedApplicableSubstitutions = applicableSubstitutions;
79830             var savedCurrentSourceFile = currentSourceFile;
79831             if (ts.isSourceFile(node)) {
79832                 currentSourceFile = node;
79833             }
79834             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
79835                 applicableSubstitutions |= 2 /* NamespaceExports */;
79836             }
79837             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
79838                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79839             }
79840             previousOnEmitNode(hint, node, emitCallback);
79841             applicableSubstitutions = savedApplicableSubstitutions;
79842             currentSourceFile = savedCurrentSourceFile;
79843         }
79844         /**
79845          * Hooks node substitutions.
79846          *
79847          * @param hint A hint as to the intended usage of the node.
79848          * @param node The node to substitute.
79849          */
79850         function onSubstituteNode(hint, node) {
79851             node = previousOnSubstituteNode(hint, node);
79852             if (hint === 1 /* Expression */) {
79853                 return substituteExpression(node);
79854             }
79855             else if (ts.isShorthandPropertyAssignment(node)) {
79856                 return substituteShorthandPropertyAssignment(node);
79857             }
79858             return node;
79859         }
79860         function substituteShorthandPropertyAssignment(node) {
79861             if (enabledSubstitutions & 2 /* NamespaceExports */) {
79862                 var name = node.name;
79863                 var exportedName = trySubstituteNamespaceExportedName(name);
79864                 if (exportedName) {
79865                     // A shorthand property with an assignment initializer is probably part of a
79866                     // destructuring assignment
79867                     if (node.objectAssignmentInitializer) {
79868                         var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
79869                         return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
79870                     }
79871                     return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
79872                 }
79873             }
79874             return node;
79875         }
79876         function substituteExpression(node) {
79877             switch (node.kind) {
79878                 case 75 /* Identifier */:
79879                     return substituteExpressionIdentifier(node);
79880                 case 194 /* PropertyAccessExpression */:
79881                     return substitutePropertyAccessExpression(node);
79882                 case 195 /* ElementAccessExpression */:
79883                     return substituteElementAccessExpression(node);
79884             }
79885             return node;
79886         }
79887         function substituteExpressionIdentifier(node) {
79888             return trySubstituteClassAlias(node)
79889                 || trySubstituteNamespaceExportedName(node)
79890                 || node;
79891         }
79892         function trySubstituteClassAlias(node) {
79893             if (enabledSubstitutions & 1 /* ClassAliases */) {
79894                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
79895                     // Due to the emit for class decorators, any reference to the class from inside of the class body
79896                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
79897                     // behavior of class names in ES6.
79898                     // Also, when emitting statics for class expressions, we must substitute a class alias for
79899                     // constructor references in static property initializers.
79900                     var declaration = resolver.getReferencedValueDeclaration(node);
79901                     if (declaration) {
79902                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
79903                         if (classAlias) {
79904                             var clone_1 = ts.getSynthesizedClone(classAlias);
79905                             ts.setSourceMapRange(clone_1, node);
79906                             ts.setCommentRange(clone_1, node);
79907                             return clone_1;
79908                         }
79909                     }
79910                 }
79911             }
79912             return undefined;
79913         }
79914         function trySubstituteNamespaceExportedName(node) {
79915             // If this is explicitly a local name, do not substitute.
79916             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
79917                 // If we are nested within a namespace declaration, we may need to qualifiy
79918                 // an identifier that is exported from a merged namespace.
79919                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
79920                 if (container && container.kind !== 290 /* SourceFile */) {
79921                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 249 /* ModuleDeclaration */) ||
79922                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 248 /* EnumDeclaration */);
79923                     if (substitute) {
79924                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), 
79925                         /*location*/ node);
79926                     }
79927                 }
79928             }
79929             return undefined;
79930         }
79931         function substitutePropertyAccessExpression(node) {
79932             return substituteConstantValue(node);
79933         }
79934         function substituteElementAccessExpression(node) {
79935             return substituteConstantValue(node);
79936         }
79937         function substituteConstantValue(node) {
79938             var constantValue = tryGetConstEnumValue(node);
79939             if (constantValue !== undefined) {
79940                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
79941                 ts.setConstantValue(node, constantValue);
79942                 var substitute = ts.createLiteral(constantValue);
79943                 if (!compilerOptions.removeComments) {
79944                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
79945                     var propertyName = ts.isPropertyAccessExpression(originalNode)
79946                         ? ts.declarationNameToString(originalNode.name)
79947                         : ts.getTextOfNode(originalNode.argumentExpression);
79948                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
79949                 }
79950                 return substitute;
79951             }
79952             return node;
79953         }
79954         function tryGetConstEnumValue(node) {
79955             if (compilerOptions.isolatedModules) {
79956                 return undefined;
79957             }
79958             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
79959         }
79960     }
79961     ts.transformTypeScript = transformTypeScript;
79962     function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
79963         var argumentsArray = [];
79964         argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
79965         argumentsArray.push(target);
79966         if (memberName) {
79967             argumentsArray.push(memberName);
79968             if (descriptor) {
79969                 argumentsArray.push(descriptor);
79970             }
79971         }
79972         context.requestEmitHelper(ts.decorateHelper);
79973         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__decorate"), 
79974         /*typeArguments*/ undefined, argumentsArray), location);
79975     }
79976     ts.decorateHelper = {
79977         name: "typescript:decorate",
79978         importName: "__decorate",
79979         scoped: false,
79980         priority: 2,
79981         text: "\n            var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n                var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n                if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n                else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n                return c > 3 && r && Object.defineProperty(target, key, r), r;\n            };"
79982     };
79983     function createMetadataHelper(context, metadataKey, metadataValue) {
79984         context.requestEmitHelper(ts.metadataHelper);
79985         return ts.createCall(ts.getUnscopedHelperName("__metadata"), 
79986         /*typeArguments*/ undefined, [
79987             ts.createLiteral(metadataKey),
79988             metadataValue
79989         ]);
79990     }
79991     ts.metadataHelper = {
79992         name: "typescript:metadata",
79993         importName: "__metadata",
79994         scoped: false,
79995         priority: 3,
79996         text: "\n            var __metadata = (this && this.__metadata) || function (k, v) {\n                if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n            };"
79997     };
79998     function createParamHelper(context, expression, parameterOffset, location) {
79999         context.requestEmitHelper(ts.paramHelper);
80000         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__param"), 
80001         /*typeArguments*/ undefined, [
80002             ts.createLiteral(parameterOffset),
80003             expression
80004         ]), location);
80005     }
80006     ts.paramHelper = {
80007         name: "typescript:param",
80008         importName: "__param",
80009         scoped: false,
80010         priority: 4,
80011         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
80012     };
80013 })(ts || (ts = {}));
80014 /*@internal*/
80015 var ts;
80016 (function (ts) {
80017     var ClassPropertySubstitutionFlags;
80018     (function (ClassPropertySubstitutionFlags) {
80019         /**
80020          * Enables substitutions for class expressions with static fields
80021          * which have initializers that reference the class name.
80022          */
80023         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
80024     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
80025     var PrivateIdentifierPlacement;
80026     (function (PrivateIdentifierPlacement) {
80027         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
80028     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
80029     /**
80030      * Transforms ECMAScript Class Syntax.
80031      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
80032      * For now, this transforms public field declarations using TypeScript class semantics,
80033      * where declarations are elided and initializers are transformed as assignments in the constructor.
80034      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
80035      */
80036     function transformClassFields(context) {
80037         var hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
80038         var resolver = context.getEmitResolver();
80039         var compilerOptions = context.getCompilerOptions();
80040         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80041         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
80042         var previousOnSubstituteNode = context.onSubstituteNode;
80043         context.onSubstituteNode = onSubstituteNode;
80044         var enabledSubstitutions;
80045         var classAliases;
80046         /**
80047          * Tracks what computed name expressions originating from elided names must be inlined
80048          * at the next execution site, in document order
80049          */
80050         var pendingExpressions;
80051         /**
80052          * Tracks what computed name expression statements and static property initializers must be
80053          * emitted at the next execution site, in document order (for decorated classes).
80054          */
80055         var pendingStatements;
80056         var privateIdentifierEnvironmentStack = [];
80057         var currentPrivateIdentifierEnvironment;
80058         return ts.chainBundle(transformSourceFile);
80059         function transformSourceFile(node) {
80060             var options = context.getCompilerOptions();
80061             if (node.isDeclarationFile
80062                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
80063                 return node;
80064             }
80065             var visited = ts.visitEachChild(node, visitor, context);
80066             ts.addEmitHelpers(visited, context.readEmitHelpers());
80067             return visited;
80068         }
80069         function visitor(node) {
80070             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
80071                 return node;
80072             switch (node.kind) {
80073                 case 214 /* ClassExpression */:
80074                 case 245 /* ClassDeclaration */:
80075                     return visitClassLike(node);
80076                 case 159 /* PropertyDeclaration */:
80077                     return visitPropertyDeclaration(node);
80078                 case 225 /* VariableStatement */:
80079                     return visitVariableStatement(node);
80080                 case 154 /* ComputedPropertyName */:
80081                     return visitComputedPropertyName(node);
80082                 case 194 /* PropertyAccessExpression */:
80083                     return visitPropertyAccessExpression(node);
80084                 case 207 /* PrefixUnaryExpression */:
80085                     return visitPrefixUnaryExpression(node);
80086                 case 208 /* PostfixUnaryExpression */:
80087                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
80088                 case 196 /* CallExpression */:
80089                     return visitCallExpression(node);
80090                 case 209 /* BinaryExpression */:
80091                     return visitBinaryExpression(node);
80092                 case 76 /* PrivateIdentifier */:
80093                     return visitPrivateIdentifier(node);
80094                 case 226 /* ExpressionStatement */:
80095                     return visitExpressionStatement(node);
80096                 case 230 /* ForStatement */:
80097                     return visitForStatement(node);
80098                 case 198 /* TaggedTemplateExpression */:
80099                     return visitTaggedTemplateExpression(node);
80100             }
80101             return ts.visitEachChild(node, visitor, context);
80102         }
80103         function visitorDestructuringTarget(node) {
80104             switch (node.kind) {
80105                 case 193 /* ObjectLiteralExpression */:
80106                 case 192 /* ArrayLiteralExpression */:
80107                     return visitAssignmentPattern(node);
80108                 default:
80109                     return visitor(node);
80110             }
80111         }
80112         /**
80113          * If we visit a private name, this means it is an undeclared private name.
80114          * Replace it with an empty identifier to indicate a problem with the code.
80115          */
80116         function visitPrivateIdentifier(node) {
80117             if (!shouldTransformPrivateFields) {
80118                 return node;
80119             }
80120             return ts.setOriginalNode(ts.createIdentifier(""), node);
80121         }
80122         /**
80123          * Visits the members of a class that has fields.
80124          *
80125          * @param node The node to visit.
80126          */
80127         function classElementVisitor(node) {
80128             switch (node.kind) {
80129                 case 162 /* Constructor */:
80130                     // Constructors for classes using class fields are transformed in
80131                     // `visitClassDeclaration` or `visitClassExpression`.
80132                     return undefined;
80133                 case 163 /* GetAccessor */:
80134                 case 164 /* SetAccessor */:
80135                 case 161 /* MethodDeclaration */:
80136                     // Visit the name of the member (if it's a computed property name).
80137                     return ts.visitEachChild(node, classElementVisitor, context);
80138                 case 159 /* PropertyDeclaration */:
80139                     return visitPropertyDeclaration(node);
80140                 case 154 /* ComputedPropertyName */:
80141                     return visitComputedPropertyName(node);
80142                 case 222 /* SemicolonClassElement */:
80143                     return node;
80144                 default:
80145                     return visitor(node);
80146             }
80147         }
80148         function visitVariableStatement(node) {
80149             var savedPendingStatements = pendingStatements;
80150             pendingStatements = [];
80151             var visitedNode = ts.visitEachChild(node, visitor, context);
80152             var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
80153                 visitedNode;
80154             pendingStatements = savedPendingStatements;
80155             return statement;
80156         }
80157         function visitComputedPropertyName(name) {
80158             var node = ts.visitEachChild(name, visitor, context);
80159             if (ts.some(pendingExpressions)) {
80160                 var expressions = pendingExpressions;
80161                 expressions.push(name.expression);
80162                 pendingExpressions = [];
80163                 node = ts.updateComputedPropertyName(node, ts.inlineExpressions(expressions));
80164             }
80165             return node;
80166         }
80167         function visitPropertyDeclaration(node) {
80168             ts.Debug.assert(!ts.some(node.decorators));
80169             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80170                 // Initializer is elided as the field is initialized in transformConstructor.
80171                 return ts.updateProperty(node, 
80172                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
80173                 /*questionOrExclamationToken*/ undefined, 
80174                 /*type*/ undefined, 
80175                 /*initializer*/ undefined);
80176             }
80177             // Create a temporary variable to store a computed property name (if necessary).
80178             // If it's not inlineable, then we emit an expression after the class which assigns
80179             // the property name to the temporary variable.
80180             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
80181             if (expr && !ts.isSimpleInlineableExpression(expr)) {
80182                 (pendingExpressions || (pendingExpressions = [])).push(expr);
80183             }
80184             return undefined;
80185         }
80186         function createPrivateIdentifierAccess(info, receiver) {
80187             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80188             switch (info.placement) {
80189                 case 0 /* InstanceField */:
80190                     return createClassPrivateFieldGetHelper(context, ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver), info.weakMapName);
80191                 default: return ts.Debug.fail("Unexpected private identifier placement");
80192             }
80193         }
80194         function visitPropertyAccessExpression(node) {
80195             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80196                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
80197                 if (privateIdentifierInfo) {
80198                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
80199                 }
80200             }
80201             return ts.visitEachChild(node, visitor, context);
80202         }
80203         function visitPrefixUnaryExpression(node) {
80204             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80205                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80206                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80207                     40 /* MinusToken */ : undefined;
80208                 var info = void 0;
80209                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80210                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80211                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80212                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80213                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */), node);
80214                 }
80215             }
80216             return ts.visitEachChild(node, visitor, context);
80217         }
80218         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
80219             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80220                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80221                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80222                     40 /* MinusToken */ : undefined;
80223                 var info = void 0;
80224                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80225                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80226                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80227                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80228                     // Create a temporary variable to store the value returned by the expression.
80229                     var returnValue = valueIsDiscarded ? undefined : ts.createTempVariable(hoistVariableDeclaration);
80230                     return ts.setOriginalNode(ts.inlineExpressions(ts.compact([
80231                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(returnValue ? ts.createAssignment(returnValue, existingValue) : existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */),
80232                         returnValue
80233                     ])), node);
80234                 }
80235             }
80236             return ts.visitEachChild(node, visitor, context);
80237         }
80238         function visitForStatement(node) {
80239             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
80240                 return ts.updateFor(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement));
80241             }
80242             return ts.visitEachChild(node, visitor, context);
80243         }
80244         function visitExpressionStatement(node) {
80245             if (ts.isPostfixUnaryExpression(node.expression)) {
80246                 return ts.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
80247             }
80248             return ts.visitEachChild(node, visitor, context);
80249         }
80250         function createCopiableReceiverExpr(receiver) {
80251             var clone = ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver);
80252             if (ts.isSimpleInlineableExpression(receiver)) {
80253                 return { readExpression: clone, initializeExpression: undefined };
80254             }
80255             var readExpression = ts.createTempVariable(hoistVariableDeclaration);
80256             var initializeExpression = ts.createAssignment(readExpression, clone);
80257             return { readExpression: readExpression, initializeExpression: initializeExpression };
80258         }
80259         function visitCallExpression(node) {
80260             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
80261                 // Transform call expressions of private names to properly bind the `this` parameter.
80262                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80263                 return ts.updateCall(node, ts.createPropertyAccess(ts.visitNode(target, visitor), "call"), 
80264                 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
80265             }
80266             return ts.visitEachChild(node, visitor, context);
80267         }
80268         function visitTaggedTemplateExpression(node) {
80269             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
80270                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
80271                 var _a = ts.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80272                 return ts.updateTaggedTemplate(node, ts.createCall(ts.createPropertyAccess(ts.visitNode(target, visitor), "bind"), 
80273                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
80274             }
80275             return ts.visitEachChild(node, visitor, context);
80276         }
80277         function visitBinaryExpression(node) {
80278             if (shouldTransformPrivateFields) {
80279                 if (ts.isDestructuringAssignment(node)) {
80280                     var savedPendingExpressions = pendingExpressions;
80281                     pendingExpressions = undefined;
80282                     node = ts.updateBinary(node, ts.visitNode(node.left, visitorDestructuringTarget), ts.visitNode(node.right, visitor), node.operatorToken);
80283                     var expr = ts.some(pendingExpressions) ?
80284                         ts.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
80285                         node;
80286                     pendingExpressions = savedPendingExpressions;
80287                     return expr;
80288                 }
80289                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
80290                     var info = accessPrivateIdentifier(node.left.name);
80291                     if (info) {
80292                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
80293                     }
80294                 }
80295             }
80296             return ts.visitEachChild(node, visitor, context);
80297         }
80298         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
80299             switch (info.placement) {
80300                 case 0 /* InstanceField */: {
80301                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
80302                 }
80303                 default: return ts.Debug.fail("Unexpected private identifier placement");
80304             }
80305         }
80306         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
80307             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80308             right = ts.visitNode(right, visitor, ts.isExpression);
80309             if (ts.isCompoundAssignment(operator)) {
80310                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80311                 return createClassPrivateFieldSetHelper(context, initializeExpression || readExpression, info.weakMapName, ts.createBinary(createClassPrivateFieldGetHelper(context, readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
80312             }
80313             else {
80314                 return createClassPrivateFieldSetHelper(context, receiver, info.weakMapName, right);
80315             }
80316         }
80317         /**
80318          * Set up the environment for a class.
80319          */
80320         function visitClassLike(node) {
80321             var savedPendingExpressions = pendingExpressions;
80322             pendingExpressions = undefined;
80323             if (shouldTransformPrivateFields) {
80324                 startPrivateIdentifierEnvironment();
80325             }
80326             var result = ts.isClassDeclaration(node) ?
80327                 visitClassDeclaration(node) :
80328                 visitClassExpression(node);
80329             if (shouldTransformPrivateFields) {
80330                 endPrivateIdentifierEnvironment();
80331             }
80332             pendingExpressions = savedPendingExpressions;
80333             return result;
80334         }
80335         function doesClassElementNeedTransform(node) {
80336             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
80337         }
80338         function visitClassDeclaration(node) {
80339             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80340                 return ts.visitEachChild(node, visitor, context);
80341             }
80342             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80343             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80344             var statements = [
80345                 ts.updateClassDeclaration(node, 
80346                 /*decorators*/ undefined, node.modifiers, node.name, 
80347                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
80348             ];
80349             // Write any pending expressions from elided or moved computed property names
80350             if (ts.some(pendingExpressions)) {
80351                 statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80352             }
80353             // Emit static property assignment. Because classDeclaration is lexically evaluated,
80354             // it is safe to emit static property assignment after classDeclaration
80355             // From ES6 specification:
80356             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
80357             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
80358             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80359             if (ts.some(staticProperties)) {
80360                 addPropertyStatements(statements, staticProperties, ts.getInternalName(node));
80361             }
80362             return statements;
80363         }
80364         function visitClassExpression(node) {
80365             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80366                 return ts.visitEachChild(node, visitor, context);
80367             }
80368             // If this class expression is a transformation of a decorated class declaration,
80369             // then we want to output the pendingExpressions as statements, not as inlined
80370             // expressions with the class statement.
80371             //
80372             // In this case, we use pendingStatements to produce the same output as the
80373             // class declaration transformation. The VariableStatement visitor will insert
80374             // these statements after the class expression variable statement.
80375             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
80376             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80377             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80378             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80379             var classExpression = ts.updateClassExpression(node, node.modifiers, node.name, 
80380             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
80381             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
80382                 if (isDecoratedClassDeclaration) {
80383                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
80384                     // Write any pending expressions from elided or moved computed property names
80385                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
80386                         pendingStatements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80387                     }
80388                     if (pendingStatements && ts.some(staticProperties)) {
80389                         addPropertyStatements(pendingStatements, staticProperties, ts.getInternalName(node));
80390                     }
80391                     return classExpression;
80392                 }
80393                 else {
80394                     var expressions = [];
80395                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
80396                     var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
80397                     if (isClassWithConstructorReference) {
80398                         // record an alias as the class name is not in scope for statics.
80399                         enableSubstitutionForClassAliases();
80400                         var alias = ts.getSynthesizedClone(temp);
80401                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
80402                         classAliases[ts.getOriginalNodeId(node)] = alias;
80403                     }
80404                     // To preserve the behavior of the old emitter, we explicitly indent
80405                     // the body of a class with static initializers.
80406                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
80407                     expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
80408                     // Add any pending expressions leftover from elided or relocated computed property names
80409                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
80410                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
80411                     expressions.push(ts.startOnNewLine(temp));
80412                     return ts.inlineExpressions(expressions);
80413                 }
80414             }
80415             return classExpression;
80416         }
80417         function transformClassMembers(node, isDerivedClass) {
80418             if (shouldTransformPrivateFields) {
80419                 // Declare private names.
80420                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
80421                     var member = _a[_i];
80422                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
80423                         addPrivateIdentifierToEnvironment(member.name);
80424                     }
80425                 }
80426             }
80427             var members = [];
80428             var constructor = transformConstructor(node, isDerivedClass);
80429             if (constructor) {
80430                 members.push(constructor);
80431             }
80432             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
80433             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
80434         }
80435         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
80436             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
80437                 return false;
80438             }
80439             if (context.getCompilerOptions().useDefineForClassFields) {
80440                 // If we are using define semantics and targeting ESNext or higher,
80441                 // then we don't need to transform any class properties.
80442                 return languageVersion < 99 /* ESNext */;
80443             }
80444             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
80445         }
80446         function transformConstructor(node, isDerivedClass) {
80447             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
80448             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
80449             if (!ts.some(properties)) {
80450                 return constructor;
80451             }
80452             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
80453             var body = transformConstructorBody(node, constructor, isDerivedClass);
80454             if (!body) {
80455                 return undefined;
80456             }
80457             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
80458             /*decorators*/ undefined, 
80459             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
80460         }
80461         function transformConstructorBody(node, constructor, isDerivedClass) {
80462             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
80463             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
80464             if (!useDefineForClassFields) {
80465                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
80466             }
80467             // Only generate synthetic constructor when there are property initializers to move.
80468             if (!constructor && !ts.some(properties)) {
80469                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
80470             }
80471             resumeLexicalEnvironment();
80472             var indexOfFirstStatement = 0;
80473             var statements = [];
80474             if (!constructor && isDerivedClass) {
80475                 // Add a synthetic `super` call:
80476                 //
80477                 //  super(...arguments);
80478                 //
80479                 statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), 
80480                 /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
80481             }
80482             if (constructor) {
80483                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
80484             }
80485             // Add the property initializers. Transforms this:
80486             //
80487             //  public x = 1;
80488             //
80489             // Into this:
80490             //
80491             //  constructor() {
80492             //      this.x = 1;
80493             //  }
80494             //
80495             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
80496                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
80497                 if (afterParameterProperties === -1) {
80498                     afterParameterProperties = constructor.body.statements.length;
80499                 }
80500                 if (afterParameterProperties > indexOfFirstStatement) {
80501                     if (!useDefineForClassFields) {
80502                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
80503                     }
80504                     indexOfFirstStatement = afterParameterProperties;
80505                 }
80506             }
80507             addPropertyStatements(statements, properties, ts.createThis());
80508             // Add existing statements, skipping the initial super call.
80509             if (constructor) {
80510                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
80511             }
80512             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
80513             return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
80514             /*location*/ constructor ? constructor.body.statements : node.members), 
80515             /*multiLine*/ true), 
80516             /*location*/ constructor ? constructor.body : undefined);
80517         }
80518         /**
80519          * Generates assignment statements for property initializers.
80520          *
80521          * @param properties An array of property declarations to transform.
80522          * @param receiver The receiver on which each property should be assigned.
80523          */
80524         function addPropertyStatements(statements, properties, receiver) {
80525             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
80526                 var property = properties_8[_i];
80527                 var expression = transformProperty(property, receiver);
80528                 if (!expression) {
80529                     continue;
80530                 }
80531                 var statement = ts.createExpressionStatement(expression);
80532                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
80533                 ts.setCommentRange(statement, property);
80534                 ts.setOriginalNode(statement, property);
80535                 statements.push(statement);
80536             }
80537         }
80538         /**
80539          * Generates assignment expressions for property initializers.
80540          *
80541          * @param properties An array of property declarations to transform.
80542          * @param receiver The receiver on which each property should be assigned.
80543          */
80544         function generateInitializedPropertyExpressions(properties, receiver) {
80545             var expressions = [];
80546             for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
80547                 var property = properties_9[_i];
80548                 var expression = transformProperty(property, receiver);
80549                 if (!expression) {
80550                     continue;
80551                 }
80552                 ts.startOnNewLine(expression);
80553                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
80554                 ts.setCommentRange(expression, property);
80555                 ts.setOriginalNode(expression, property);
80556                 expressions.push(expression);
80557             }
80558             return expressions;
80559         }
80560         /**
80561          * Transforms a property initializer into an assignment statement.
80562          *
80563          * @param property The property declaration.
80564          * @param receiver The object receiving the property assignment.
80565          */
80566         function transformProperty(property, receiver) {
80567             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
80568             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
80569             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
80570                 ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
80571                 : property.name;
80572             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
80573                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
80574                 if (privateIdentifierInfo) {
80575                     switch (privateIdentifierInfo.placement) {
80576                         case 0 /* InstanceField */: {
80577                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
80578                         }
80579                     }
80580                 }
80581                 else {
80582                     ts.Debug.fail("Undeclared private name for property declaration.");
80583                 }
80584             }
80585             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80586                 return undefined;
80587             }
80588             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80589                 return undefined;
80590             }
80591             var propertyOriginalNode = ts.getOriginalNode(property);
80592             var initializer = property.initializer || emitAssignment ? ts.visitNode(property.initializer, visitor, ts.isExpression)
80593                 : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
80594                     : ts.createVoidZero();
80595             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
80596                 var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
80597                 return ts.createAssignment(memberAccess, initializer);
80598             }
80599             else {
80600                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
80601                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
80602                         : propertyName;
80603                 var descriptor = ts.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
80604                 return ts.createObjectDefinePropertyCall(receiver, name, descriptor);
80605             }
80606         }
80607         function enableSubstitutionForClassAliases() {
80608             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
80609                 enabledSubstitutions |= 1 /* ClassAliases */;
80610                 // We need to enable substitutions for identifiers. This allows us to
80611                 // substitute class names inside of a class declaration.
80612                 context.enableSubstitution(75 /* Identifier */);
80613                 // Keep track of class aliases.
80614                 classAliases = [];
80615             }
80616         }
80617         /**
80618          * Hooks node substitutions.
80619          *
80620          * @param hint The context for the emitter.
80621          * @param node The node to substitute.
80622          */
80623         function onSubstituteNode(hint, node) {
80624             node = previousOnSubstituteNode(hint, node);
80625             if (hint === 1 /* Expression */) {
80626                 return substituteExpression(node);
80627             }
80628             return node;
80629         }
80630         function substituteExpression(node) {
80631             switch (node.kind) {
80632                 case 75 /* Identifier */:
80633                     return substituteExpressionIdentifier(node);
80634             }
80635             return node;
80636         }
80637         function substituteExpressionIdentifier(node) {
80638             return trySubstituteClassAlias(node) || node;
80639         }
80640         function trySubstituteClassAlias(node) {
80641             if (enabledSubstitutions & 1 /* ClassAliases */) {
80642                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
80643                     // Due to the emit for class decorators, any reference to the class from inside of the class body
80644                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
80645                     // behavior of class names in ES6.
80646                     // Also, when emitting statics for class expressions, we must substitute a class alias for
80647                     // constructor references in static property initializers.
80648                     var declaration = resolver.getReferencedValueDeclaration(node);
80649                     if (declaration) {
80650                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
80651                         if (classAlias) {
80652                             var clone_2 = ts.getSynthesizedClone(classAlias);
80653                             ts.setSourceMapRange(clone_2, node);
80654                             ts.setCommentRange(clone_2, node);
80655                             return clone_2;
80656                         }
80657                     }
80658                 }
80659             }
80660             return undefined;
80661         }
80662         /**
80663          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
80664          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
80665          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
80666          */
80667         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
80668             if (ts.isComputedPropertyName(name)) {
80669                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
80670                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
80671                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
80672                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
80673                 if (!alreadyTransformed && !inlinable && shouldHoist) {
80674                     var generatedName = ts.getGeneratedNameForNode(name);
80675                     hoistVariableDeclaration(generatedName);
80676                     return ts.createAssignment(generatedName, expression);
80677                 }
80678                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
80679             }
80680         }
80681         function startPrivateIdentifierEnvironment() {
80682             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
80683             currentPrivateIdentifierEnvironment = undefined;
80684         }
80685         function endPrivateIdentifierEnvironment() {
80686             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
80687         }
80688         function addPrivateIdentifierToEnvironment(name) {
80689             var text = ts.getTextOfPropertyName(name);
80690             var weakMapName = ts.createOptimisticUniqueName("_" + text.substring(1));
80691             weakMapName.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80692             hoistVariableDeclaration(weakMapName);
80693             (currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = ts.createUnderscoreEscapedMap()))
80694                 .set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
80695             (pendingExpressions || (pendingExpressions = [])).push(ts.createAssignment(weakMapName, ts.createNew(ts.createIdentifier("WeakMap"), 
80696             /*typeArguments*/ undefined, [])));
80697         }
80698         function accessPrivateIdentifier(name) {
80699             if (currentPrivateIdentifierEnvironment) {
80700                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
80701                 if (info) {
80702                     return info;
80703                 }
80704             }
80705             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
80706                 var env = privateIdentifierEnvironmentStack[i];
80707                 if (!env) {
80708                     continue;
80709                 }
80710                 var info = env.get(name.escapedText);
80711                 if (info) {
80712                     return info;
80713                 }
80714             }
80715             return undefined;
80716         }
80717         function wrapPrivateIdentifierForDestructuringTarget(node) {
80718             var parameter = ts.getGeneratedNameForNode(node);
80719             var info = accessPrivateIdentifier(node.name);
80720             if (!info) {
80721                 return ts.visitEachChild(node, visitor, context);
80722             }
80723             var receiver = node.expression;
80724             // We cannot copy `this` or `super` into the function because they will be bound
80725             // differently inside the function.
80726             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
80727                 receiver = ts.createTempVariable(hoistVariableDeclaration);
80728                 receiver.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80729                 (pendingExpressions || (pendingExpressions = [])).push(ts.createBinary(receiver, 62 /* EqualsToken */, node.expression));
80730             }
80731             return ts.createPropertyAccess(
80732             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
80733             ts.createParen(ts.createObjectLiteral([
80734                 ts.createSetAccessor(
80735                 /*decorators*/ undefined, 
80736                 /*modifiers*/ undefined, "value", [ts.createParameter(
80737                     /*decorators*/ undefined, 
80738                     /*modifiers*/ undefined, 
80739                     /*dotDotDotToken*/ undefined, parameter, 
80740                     /*questionToken*/ undefined, 
80741                     /*type*/ undefined, 
80742                     /*initializer*/ undefined)], ts.createBlock([ts.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
80743             ])), "value");
80744         }
80745         function visitArrayAssignmentTarget(node) {
80746             var target = ts.getTargetOfBindingOrAssignmentElement(node);
80747             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80748                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80749                 if (ts.isAssignmentExpression(node)) {
80750                     return ts.updateBinary(node, wrapped, ts.visitNode(node.right, visitor, ts.isExpression), node.operatorToken);
80751                 }
80752                 else if (ts.isSpreadElement(node)) {
80753                     return ts.updateSpread(node, wrapped);
80754                 }
80755                 else {
80756                     return wrapped;
80757                 }
80758             }
80759             return ts.visitNode(node, visitorDestructuringTarget);
80760         }
80761         function visitObjectAssignmentTarget(node) {
80762             if (ts.isPropertyAssignment(node)) {
80763                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
80764                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80765                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
80766                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80767                     return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? ts.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
80768                 }
80769                 return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
80770             }
80771             return ts.visitNode(node, visitor);
80772         }
80773         function visitAssignmentPattern(node) {
80774             if (ts.isArrayLiteralExpression(node)) {
80775                 // Transforms private names in destructuring assignment array bindings.
80776                 //
80777                 // Source:
80778                 // ([ this.#myProp ] = [ "hello" ]);
80779                 //
80780                 // Transformation:
80781                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
80782                 return ts.updateArrayLiteral(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
80783             }
80784             else {
80785                 // Transforms private names in destructuring assignment object bindings.
80786                 //
80787                 // Source:
80788                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
80789                 //
80790                 // Transformation:
80791                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
80792                 return ts.updateObjectLiteral(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
80793             }
80794         }
80795     }
80796     ts.transformClassFields = transformClassFields;
80797     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
80798         return ts.createCall(ts.createPropertyAccess(weakMapName, "set"), 
80799         /*typeArguments*/ undefined, [receiver, initializer || ts.createVoidZero()]);
80800     }
80801     ts.classPrivateFieldGetHelper = {
80802         name: "typescript:classPrivateFieldGet",
80803         scoped: false,
80804         text: "\n            var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n                if (!privateMap.has(receiver)) {\n                    throw new TypeError(\"attempted to get private field on non-instance\");\n                }\n                return privateMap.get(receiver);\n            };"
80805     };
80806     function createClassPrivateFieldGetHelper(context, receiver, privateField) {
80807         context.requestEmitHelper(ts.classPrivateFieldGetHelper);
80808         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldGet"), /* typeArguments */ undefined, [receiver, privateField]);
80809     }
80810     ts.classPrivateFieldSetHelper = {
80811         name: "typescript:classPrivateFieldSet",
80812         scoped: false,
80813         text: "\n            var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n                if (!privateMap.has(receiver)) {\n                    throw new TypeError(\"attempted to set private field on non-instance\");\n                }\n                privateMap.set(receiver, value);\n                return value;\n            };"
80814     };
80815     function createClassPrivateFieldSetHelper(context, receiver, privateField, value) {
80816         context.requestEmitHelper(ts.classPrivateFieldSetHelper);
80817         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldSet"), /* typeArguments */ undefined, [receiver, privateField, value]);
80818     }
80819 })(ts || (ts = {}));
80820 /*@internal*/
80821 var ts;
80822 (function (ts) {
80823     var ES2017SubstitutionFlags;
80824     (function (ES2017SubstitutionFlags) {
80825         /** Enables substitutions for async methods with `super` calls. */
80826         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
80827     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
80828     var ContextFlags;
80829     (function (ContextFlags) {
80830         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
80831         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
80832     })(ContextFlags || (ContextFlags = {}));
80833     function transformES2017(context) {
80834         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
80835         var resolver = context.getEmitResolver();
80836         var compilerOptions = context.getCompilerOptions();
80837         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80838         /**
80839          * Keeps track of whether expression substitution has been enabled for specific edge cases.
80840          * They are persisted between each SourceFile transformation and should not be reset.
80841          */
80842         var enabledSubstitutions;
80843         /**
80844          * This keeps track of containers where `super` is valid, for use with
80845          * just-in-time substitution for `super` expressions inside of async methods.
80846          */
80847         var enclosingSuperContainerFlags = 0;
80848         var enclosingFunctionParameterNames;
80849         /**
80850          * Keeps track of property names accessed on super (`super.x`) within async functions.
80851          */
80852         var capturedSuperProperties;
80853         /** Whether the async function contains an element access on super (`super[x]`). */
80854         var hasSuperElementAccess;
80855         /** A set of node IDs for generated super accessors (variable statements). */
80856         var substitutedSuperAccessors = [];
80857         var contextFlags = 0;
80858         // Save the previous transformation hooks.
80859         var previousOnEmitNode = context.onEmitNode;
80860         var previousOnSubstituteNode = context.onSubstituteNode;
80861         // Set new transformation hooks.
80862         context.onEmitNode = onEmitNode;
80863         context.onSubstituteNode = onSubstituteNode;
80864         return ts.chainBundle(transformSourceFile);
80865         function transformSourceFile(node) {
80866             if (node.isDeclarationFile) {
80867                 return node;
80868             }
80869             setContextFlag(1 /* NonTopLevel */, false);
80870             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
80871             var visited = ts.visitEachChild(node, visitor, context);
80872             ts.addEmitHelpers(visited, context.readEmitHelpers());
80873             return visited;
80874         }
80875         function setContextFlag(flag, val) {
80876             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
80877         }
80878         function inContext(flags) {
80879             return (contextFlags & flags) !== 0;
80880         }
80881         function inTopLevelContext() {
80882             return !inContext(1 /* NonTopLevel */);
80883         }
80884         function inHasLexicalThisContext() {
80885             return inContext(2 /* HasLexicalThis */);
80886         }
80887         function doWithContext(flags, cb, value) {
80888             var contextFlagsToSet = flags & ~contextFlags;
80889             if (contextFlagsToSet) {
80890                 setContextFlag(contextFlagsToSet, /*val*/ true);
80891                 var result = cb(value);
80892                 setContextFlag(contextFlagsToSet, /*val*/ false);
80893                 return result;
80894             }
80895             return cb(value);
80896         }
80897         function visitDefault(node) {
80898             return ts.visitEachChild(node, visitor, context);
80899         }
80900         function visitor(node) {
80901             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
80902                 return node;
80903             }
80904             switch (node.kind) {
80905                 case 126 /* AsyncKeyword */:
80906                     // ES2017 async modifier should be elided for targets < ES2017
80907                     return undefined;
80908                 case 206 /* AwaitExpression */:
80909                     return visitAwaitExpression(node);
80910                 case 161 /* MethodDeclaration */:
80911                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
80912                 case 244 /* FunctionDeclaration */:
80913                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
80914                 case 201 /* FunctionExpression */:
80915                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
80916                 case 202 /* ArrowFunction */:
80917                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
80918                 case 194 /* PropertyAccessExpression */:
80919                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
80920                         capturedSuperProperties.set(node.name.escapedText, true);
80921                     }
80922                     return ts.visitEachChild(node, visitor, context);
80923                 case 195 /* ElementAccessExpression */:
80924                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
80925                         hasSuperElementAccess = true;
80926                     }
80927                     return ts.visitEachChild(node, visitor, context);
80928                 case 163 /* GetAccessor */:
80929                 case 164 /* SetAccessor */:
80930                 case 162 /* Constructor */:
80931                 case 245 /* ClassDeclaration */:
80932                 case 214 /* ClassExpression */:
80933                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
80934                 default:
80935                     return ts.visitEachChild(node, visitor, context);
80936             }
80937         }
80938         function asyncBodyVisitor(node) {
80939             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
80940                 switch (node.kind) {
80941                     case 225 /* VariableStatement */:
80942                         return visitVariableStatementInAsyncBody(node);
80943                     case 230 /* ForStatement */:
80944                         return visitForStatementInAsyncBody(node);
80945                     case 231 /* ForInStatement */:
80946                         return visitForInStatementInAsyncBody(node);
80947                     case 232 /* ForOfStatement */:
80948                         return visitForOfStatementInAsyncBody(node);
80949                     case 280 /* CatchClause */:
80950                         return visitCatchClauseInAsyncBody(node);
80951                     case 223 /* Block */:
80952                     case 237 /* SwitchStatement */:
80953                     case 251 /* CaseBlock */:
80954                     case 277 /* CaseClause */:
80955                     case 278 /* DefaultClause */:
80956                     case 240 /* TryStatement */:
80957                     case 228 /* DoStatement */:
80958                     case 229 /* WhileStatement */:
80959                     case 227 /* IfStatement */:
80960                     case 236 /* WithStatement */:
80961                     case 238 /* LabeledStatement */:
80962                         return ts.visitEachChild(node, asyncBodyVisitor, context);
80963                     default:
80964                         return ts.Debug.assertNever(node, "Unhandled node.");
80965                 }
80966             }
80967             return visitor(node);
80968         }
80969         function visitCatchClauseInAsyncBody(node) {
80970             var catchClauseNames = ts.createUnderscoreEscapedMap();
80971             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
80972             // names declared in a catch variable are block scoped
80973             var catchClauseUnshadowedNames;
80974             catchClauseNames.forEach(function (_, escapedName) {
80975                 if (enclosingFunctionParameterNames.has(escapedName)) {
80976                     if (!catchClauseUnshadowedNames) {
80977                         catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
80978                     }
80979                     catchClauseUnshadowedNames.delete(escapedName);
80980                 }
80981             });
80982             if (catchClauseUnshadowedNames) {
80983                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
80984                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
80985                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
80986                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
80987                 return result;
80988             }
80989             else {
80990                 return ts.visitEachChild(node, asyncBodyVisitor, context);
80991             }
80992         }
80993         function visitVariableStatementInAsyncBody(node) {
80994             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
80995                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
80996                 return expression ? ts.createExpressionStatement(expression) : undefined;
80997             }
80998             return ts.visitEachChild(node, visitor, context);
80999         }
81000         function visitForInStatementInAsyncBody(node) {
81001             return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
81002                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
81003                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81004         }
81005         function visitForOfStatementInAsyncBody(node) {
81006             return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
81007                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
81008                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81009         }
81010         function visitForStatementInAsyncBody(node) {
81011             var initializer = node.initializer; // TODO: GH#18217
81012             return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
81013                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
81014                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81015         }
81016         /**
81017          * Visits an AwaitExpression node.
81018          *
81019          * This function will be called any time a ES2017 await expression is encountered.
81020          *
81021          * @param node The node to visit.
81022          */
81023         function visitAwaitExpression(node) {
81024             // do not downlevel a top-level await as it is module syntax...
81025             if (inTopLevelContext()) {
81026                 return ts.visitEachChild(node, visitor, context);
81027             }
81028             return ts.setOriginalNode(ts.setTextRange(ts.createYield(
81029             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
81030         }
81031         /**
81032          * Visits a MethodDeclaration node.
81033          *
81034          * This function will be called when one of the following conditions are met:
81035          * - The node is marked as async
81036          *
81037          * @param node The node to visit.
81038          */
81039         function visitMethodDeclaration(node) {
81040             return ts.updateMethod(node, 
81041             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81042             /*questionToken*/ undefined, 
81043             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81044             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81045                 ? transformAsyncFunctionBody(node)
81046                 : ts.visitFunctionBody(node.body, visitor, context));
81047         }
81048         /**
81049          * Visits a FunctionDeclaration node.
81050          *
81051          * This function will be called when one of the following conditions are met:
81052          * - The node is marked async
81053          *
81054          * @param node The node to visit.
81055          */
81056         function visitFunctionDeclaration(node) {
81057             return ts.updateFunctionDeclaration(node, 
81058             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81059             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81060             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81061                 ? transformAsyncFunctionBody(node)
81062                 : ts.visitFunctionBody(node.body, visitor, context));
81063         }
81064         /**
81065          * Visits a FunctionExpression node.
81066          *
81067          * This function will be called when one of the following conditions are met:
81068          * - The node is marked async
81069          *
81070          * @param node The node to visit.
81071          */
81072         function visitFunctionExpression(node) {
81073             return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81074             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81075             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81076                 ? transformAsyncFunctionBody(node)
81077                 : ts.visitFunctionBody(node.body, visitor, context));
81078         }
81079         /**
81080          * Visits an ArrowFunction.
81081          *
81082          * This function will be called when one of the following conditions are met:
81083          * - The node is marked async
81084          *
81085          * @param node The node to visit.
81086          */
81087         function visitArrowFunction(node) {
81088             return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
81089             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81090             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
81091                 ? transformAsyncFunctionBody(node)
81092                 : ts.visitFunctionBody(node.body, visitor, context));
81093         }
81094         function recordDeclarationName(_a, names) {
81095             var name = _a.name;
81096             if (ts.isIdentifier(name)) {
81097                 names.set(name.escapedText, true);
81098             }
81099             else {
81100                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81101                     var element = _b[_i];
81102                     if (!ts.isOmittedExpression(element)) {
81103                         recordDeclarationName(element, names);
81104                     }
81105                 }
81106             }
81107         }
81108         function isVariableDeclarationListWithCollidingName(node) {
81109             return !!node
81110                 && ts.isVariableDeclarationList(node)
81111                 && !(node.flags & 3 /* BlockScoped */)
81112                 && node.declarations.some(collidesWithParameterName);
81113         }
81114         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
81115             hoistVariableDeclarationList(node);
81116             var variables = ts.getInitializedVariables(node);
81117             if (variables.length === 0) {
81118                 if (hasReceiver) {
81119                     return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
81120                 }
81121                 return undefined;
81122             }
81123             return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
81124         }
81125         function hoistVariableDeclarationList(node) {
81126             ts.forEach(node.declarations, hoistVariable);
81127         }
81128         function hoistVariable(_a) {
81129             var name = _a.name;
81130             if (ts.isIdentifier(name)) {
81131                 hoistVariableDeclaration(name);
81132             }
81133             else {
81134                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81135                     var element = _b[_i];
81136                     if (!ts.isOmittedExpression(element)) {
81137                         hoistVariable(element);
81138                     }
81139                 }
81140             }
81141         }
81142         function transformInitializedVariable(node) {
81143             var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
81144             return ts.visitNode(converted, visitor, ts.isExpression);
81145         }
81146         function collidesWithParameterName(_a) {
81147             var name = _a.name;
81148             if (ts.isIdentifier(name)) {
81149                 return enclosingFunctionParameterNames.has(name.escapedText);
81150             }
81151             else {
81152                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81153                     var element = _b[_i];
81154                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
81155                         return true;
81156                     }
81157                 }
81158             }
81159             return false;
81160         }
81161         function transformAsyncFunctionBody(node) {
81162             resumeLexicalEnvironment();
81163             var original = ts.getOriginalNode(node, ts.isFunctionLike);
81164             var nodeType = original.type;
81165             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
81166             var isArrowFunction = node.kind === 202 /* ArrowFunction */;
81167             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
81168             // An async function is emit as an outer function that calls an inner
81169             // generator function. To preserve lexical bindings, we pass the current
81170             // `this` and `arguments` objects to `__awaiter`. The generator function
81171             // passed to `__awaiter` is executed inside of the callback to the
81172             // promise constructor.
81173             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
81174             enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
81175             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
81176                 var parameter = _a[_i];
81177                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
81178             }
81179             var savedCapturedSuperProperties = capturedSuperProperties;
81180             var savedHasSuperElementAccess = hasSuperElementAccess;
81181             if (!isArrowFunction) {
81182                 capturedSuperProperties = ts.createUnderscoreEscapedMap();
81183                 hasSuperElementAccess = false;
81184             }
81185             var result;
81186             if (!isArrowFunction) {
81187                 var statements = [];
81188                 var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
81189                 statements.push(ts.createReturn(createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
81190                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
81191                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
81192                 // This step isn't needed if we eventually transform this to ES5.
81193                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
81194                 if (emitSuperHelpers) {
81195                     enableSubstitutionForAsyncMethodsWithSuper();
81196                     if (ts.hasEntries(capturedSuperProperties)) {
81197                         var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
81198                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
81199                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
81200                     }
81201                 }
81202                 var block = ts.createBlock(statements, /*multiLine*/ true);
81203                 ts.setTextRange(block, node.body);
81204                 if (emitSuperHelpers && hasSuperElementAccess) {
81205                     // Emit helpers for super element access expressions (`super[x]`).
81206                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
81207                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
81208                     }
81209                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
81210                         ts.addEmitHelper(block, ts.asyncSuperHelper);
81211                     }
81212                 }
81213                 result = block;
81214             }
81215             else {
81216                 var expression = createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
81217                 var declarations = endLexicalEnvironment();
81218                 if (ts.some(declarations)) {
81219                     var block = ts.convertToFunctionBody(expression);
81220                     result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
81221                 }
81222                 else {
81223                     result = expression;
81224                 }
81225             }
81226             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
81227             if (!isArrowFunction) {
81228                 capturedSuperProperties = savedCapturedSuperProperties;
81229                 hasSuperElementAccess = savedHasSuperElementAccess;
81230             }
81231             return result;
81232         }
81233         function transformAsyncFunctionBodyWorker(body, start) {
81234             if (ts.isBlock(body)) {
81235                 return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
81236             }
81237             else {
81238                 return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
81239             }
81240         }
81241         function getPromiseConstructor(type) {
81242             var typeName = type && ts.getEntityNameFromTypeNode(type);
81243             if (typeName && ts.isEntityName(typeName)) {
81244                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
81245                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
81246                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
81247                     return typeName;
81248                 }
81249             }
81250             return undefined;
81251         }
81252         function enableSubstitutionForAsyncMethodsWithSuper() {
81253             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
81254                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
81255                 // We need to enable substitutions for call, property access, and element access
81256                 // if we need to rewrite super calls.
81257                 context.enableSubstitution(196 /* CallExpression */);
81258                 context.enableSubstitution(194 /* PropertyAccessExpression */);
81259                 context.enableSubstitution(195 /* ElementAccessExpression */);
81260                 // We need to be notified when entering and exiting declarations that bind super.
81261                 context.enableEmitNotification(245 /* ClassDeclaration */);
81262                 context.enableEmitNotification(161 /* MethodDeclaration */);
81263                 context.enableEmitNotification(163 /* GetAccessor */);
81264                 context.enableEmitNotification(164 /* SetAccessor */);
81265                 context.enableEmitNotification(162 /* Constructor */);
81266                 // We need to be notified when entering the generated accessor arrow functions.
81267                 context.enableEmitNotification(225 /* VariableStatement */);
81268             }
81269         }
81270         /**
81271          * Hook for node emit.
81272          *
81273          * @param hint A hint as to the intended usage of the node.
81274          * @param node The node to emit.
81275          * @param emit A callback used to emit the node in the printer.
81276          */
81277         function onEmitNode(hint, node, emitCallback) {
81278             // If we need to support substitutions for `super` in an async method,
81279             // we should track it here.
81280             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
81281                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
81282                 if (superContainerFlags !== enclosingSuperContainerFlags) {
81283                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81284                     enclosingSuperContainerFlags = superContainerFlags;
81285                     previousOnEmitNode(hint, node, emitCallback);
81286                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81287                     return;
81288                 }
81289             }
81290             // Disable substitution in the generated super accessor itself.
81291             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
81292                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81293                 enclosingSuperContainerFlags = 0;
81294                 previousOnEmitNode(hint, node, emitCallback);
81295                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81296                 return;
81297             }
81298             previousOnEmitNode(hint, node, emitCallback);
81299         }
81300         /**
81301          * Hooks node substitutions.
81302          *
81303          * @param hint A hint as to the intended usage of the node.
81304          * @param node The node to substitute.
81305          */
81306         function onSubstituteNode(hint, node) {
81307             node = previousOnSubstituteNode(hint, node);
81308             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
81309                 return substituteExpression(node);
81310             }
81311             return node;
81312         }
81313         function substituteExpression(node) {
81314             switch (node.kind) {
81315                 case 194 /* PropertyAccessExpression */:
81316                     return substitutePropertyAccessExpression(node);
81317                 case 195 /* ElementAccessExpression */:
81318                     return substituteElementAccessExpression(node);
81319                 case 196 /* CallExpression */:
81320                     return substituteCallExpression(node);
81321             }
81322             return node;
81323         }
81324         function substitutePropertyAccessExpression(node) {
81325             if (node.expression.kind === 102 /* SuperKeyword */) {
81326                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
81327             }
81328             return node;
81329         }
81330         function substituteElementAccessExpression(node) {
81331             if (node.expression.kind === 102 /* SuperKeyword */) {
81332                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
81333             }
81334             return node;
81335         }
81336         function substituteCallExpression(node) {
81337             var expression = node.expression;
81338             if (ts.isSuperProperty(expression)) {
81339                 var argumentExpression = ts.isPropertyAccessExpression(expression)
81340                     ? substitutePropertyAccessExpression(expression)
81341                     : substituteElementAccessExpression(expression);
81342                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
81343                 /*typeArguments*/ undefined, __spreadArrays([
81344                     ts.createThis()
81345                 ], node.arguments));
81346             }
81347             return node;
81348         }
81349         function isSuperContainer(node) {
81350             var kind = node.kind;
81351             return kind === 245 /* ClassDeclaration */
81352                 || kind === 162 /* Constructor */
81353                 || kind === 161 /* MethodDeclaration */
81354                 || kind === 163 /* GetAccessor */
81355                 || kind === 164 /* SetAccessor */;
81356         }
81357         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
81358             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
81359                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81360                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
81361             }
81362             else {
81363                 return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81364                 /*typeArguments*/ undefined, [argumentExpression]), location);
81365             }
81366         }
81367     }
81368     ts.transformES2017 = transformES2017;
81369     /** Creates a variable named `_super` with accessor properties for the given property names. */
81370     function createSuperAccessVariableStatement(resolver, node, names) {
81371         // Create a variable declaration with a getter/setter (if binding) definition for each name:
81372         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
81373         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
81374         var accessors = [];
81375         names.forEach(function (_, key) {
81376             var name = ts.unescapeLeadingUnderscores(key);
81377             var getterAndSetter = [];
81378             getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(
81379             /* modifiers */ undefined, 
81380             /* typeParameters */ undefined, 
81381             /* parameters */ [], 
81382             /* type */ undefined, 
81383             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
81384             if (hasBinding) {
81385                 getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
81386                 /* modifiers */ undefined, 
81387                 /* typeParameters */ undefined, 
81388                 /* parameters */ [
81389                     ts.createParameter(
81390                     /* decorators */ undefined, 
81391                     /* modifiers */ undefined, 
81392                     /* dotDotDotToken */ undefined, "v", 
81393                     /* questionToken */ undefined, 
81394                     /* type */ undefined, 
81395                     /* initializer */ undefined)
81396                 ], 
81397                 /* type */ undefined, 
81398                 /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
81399             }
81400             accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
81401         });
81402         return ts.createVariableStatement(
81403         /* modifiers */ undefined, ts.createVariableDeclarationList([
81404             ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), 
81405             /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), 
81406             /* typeArguments */ undefined, [
81407                 ts.createNull(),
81408                 ts.createObjectLiteral(accessors, /* multiline */ true)
81409             ]))
81410         ], 2 /* Const */));
81411     }
81412     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
81413     ts.awaiterHelper = {
81414         name: "typescript:awaiter",
81415         importName: "__awaiter",
81416         scoped: false,
81417         priority: 5,
81418         text: "\n            var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n                function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n                return new (P || (P = Promise))(function (resolve, reject) {\n                    function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n                    function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n                    function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n                    step((generator = generator.apply(thisArg, _arguments || [])).next());\n                });\n            };"
81419     };
81420     function createAwaiterHelper(context, hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
81421         context.requestEmitHelper(ts.awaiterHelper);
81422         var generatorFunc = ts.createFunctionExpression(
81423         /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), 
81424         /*name*/ undefined, 
81425         /*typeParameters*/ undefined, 
81426         /*parameters*/ [], 
81427         /*type*/ undefined, body);
81428         // Mark this node as originally an async function
81429         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
81430         return ts.createCall(ts.getUnscopedHelperName("__awaiter"), 
81431         /*typeArguments*/ undefined, [
81432             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
81433             hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
81434             promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
81435             generatorFunc
81436         ]);
81437     }
81438     ts.asyncSuperHelper = {
81439         name: "typescript:async-super",
81440         scoped: true,
81441         text: ts.helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
81442     };
81443     ts.advancedAsyncSuperHelper = {
81444         name: "typescript:advanced-async-super",
81445         scoped: true,
81446         text: ts.helperString(__makeTemplateObject(["\n            const ", " = (function (geti, seti) {\n                const cache = Object.create(null);\n                return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n            })(name => super[name], (name, value) => super[name] = value);"], ["\n            const ", " = (function (geti, seti) {\n                const cache = Object.create(null);\n                return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n            })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex")
81447     };
81448 })(ts || (ts = {}));
81449 /*@internal*/
81450 var ts;
81451 (function (ts) {
81452     var ESNextSubstitutionFlags;
81453     (function (ESNextSubstitutionFlags) {
81454         /** Enables substitutions for async methods with `super` calls. */
81455         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
81456     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
81457     // Facts we track as we traverse the tree
81458     var HierarchyFacts;
81459     (function (HierarchyFacts) {
81460         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
81461         //
81462         // Ancestor facts
81463         //
81464         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
81465         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
81466         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
81467         //
81468         // Ancestor masks
81469         //
81470         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
81471         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
81472         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
81473         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
81474         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
81475         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
81476         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
81477         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
81478         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
81479         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
81480     })(HierarchyFacts || (HierarchyFacts = {}));
81481     function transformES2018(context) {
81482         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
81483         var resolver = context.getEmitResolver();
81484         var compilerOptions = context.getCompilerOptions();
81485         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
81486         var previousOnEmitNode = context.onEmitNode;
81487         context.onEmitNode = onEmitNode;
81488         var previousOnSubstituteNode = context.onSubstituteNode;
81489         context.onSubstituteNode = onSubstituteNode;
81490         var exportedVariableStatement = false;
81491         var enabledSubstitutions;
81492         var enclosingFunctionFlags;
81493         var enclosingSuperContainerFlags = 0;
81494         var hierarchyFacts = 0;
81495         var currentSourceFile;
81496         var taggedTemplateStringDeclarations;
81497         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
81498         var capturedSuperProperties;
81499         /** Whether the async function contains an element access on super (`super[x]`). */
81500         var hasSuperElementAccess;
81501         /** A set of node IDs for generated super accessors. */
81502         var substitutedSuperAccessors = [];
81503         return ts.chainBundle(transformSourceFile);
81504         function affectsSubtree(excludeFacts, includeFacts) {
81505             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
81506         }
81507         /**
81508          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
81509          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
81510          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
81511          */
81512         function enterSubtree(excludeFacts, includeFacts) {
81513             var ancestorFacts = hierarchyFacts;
81514             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
81515             return ancestorFacts;
81516         }
81517         /**
81518          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
81519          * subtree.
81520          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
81521          */
81522         function exitSubtree(ancestorFacts) {
81523             hierarchyFacts = ancestorFacts;
81524         }
81525         function recordTaggedTemplateString(temp) {
81526             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
81527         }
81528         function transformSourceFile(node) {
81529             if (node.isDeclarationFile) {
81530                 return node;
81531             }
81532             currentSourceFile = node;
81533             var visited = visitSourceFile(node);
81534             ts.addEmitHelpers(visited, context.readEmitHelpers());
81535             currentSourceFile = undefined;
81536             taggedTemplateStringDeclarations = undefined;
81537             return visited;
81538         }
81539         function visitor(node) {
81540             return visitorWorker(node, /*noDestructuringValue*/ false);
81541         }
81542         function visitorNoDestructuringValue(node) {
81543             return visitorWorker(node, /*noDestructuringValue*/ true);
81544         }
81545         function visitorNoAsyncModifier(node) {
81546             if (node.kind === 126 /* AsyncKeyword */) {
81547                 return undefined;
81548             }
81549             return node;
81550         }
81551         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
81552             if (affectsSubtree(excludeFacts, includeFacts)) {
81553                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
81554                 var result = cb(value);
81555                 exitSubtree(ancestorFacts);
81556                 return result;
81557             }
81558             return cb(value);
81559         }
81560         function visitDefault(node) {
81561             return ts.visitEachChild(node, visitor, context);
81562         }
81563         function visitorWorker(node, noDestructuringValue) {
81564             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
81565                 return node;
81566             }
81567             switch (node.kind) {
81568                 case 206 /* AwaitExpression */:
81569                     return visitAwaitExpression(node);
81570                 case 212 /* YieldExpression */:
81571                     return visitYieldExpression(node);
81572                 case 235 /* ReturnStatement */:
81573                     return visitReturnStatement(node);
81574                 case 238 /* LabeledStatement */:
81575                     return visitLabeledStatement(node);
81576                 case 193 /* ObjectLiteralExpression */:
81577                     return visitObjectLiteralExpression(node);
81578                 case 209 /* BinaryExpression */:
81579                     return visitBinaryExpression(node, noDestructuringValue);
81580                 case 280 /* CatchClause */:
81581                     return visitCatchClause(node);
81582                 case 225 /* VariableStatement */:
81583                     return visitVariableStatement(node);
81584                 case 242 /* VariableDeclaration */:
81585                     return visitVariableDeclaration(node);
81586                 case 228 /* DoStatement */:
81587                 case 229 /* WhileStatement */:
81588                 case 231 /* ForInStatement */:
81589                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81590                 case 232 /* ForOfStatement */:
81591                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
81592                 case 230 /* ForStatement */:
81593                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81594                 case 205 /* VoidExpression */:
81595                     return visitVoidExpression(node);
81596                 case 162 /* Constructor */:
81597                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81598                 case 161 /* MethodDeclaration */:
81599                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81600                 case 163 /* GetAccessor */:
81601                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81602                 case 164 /* SetAccessor */:
81603                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81604                 case 244 /* FunctionDeclaration */:
81605                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81606                 case 201 /* FunctionExpression */:
81607                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81608                 case 202 /* ArrowFunction */:
81609                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
81610                 case 156 /* Parameter */:
81611                     return visitParameter(node);
81612                 case 226 /* ExpressionStatement */:
81613                     return visitExpressionStatement(node);
81614                 case 200 /* ParenthesizedExpression */:
81615                     return visitParenthesizedExpression(node, noDestructuringValue);
81616                 case 198 /* TaggedTemplateExpression */:
81617                     return visitTaggedTemplateExpression(node);
81618                 case 194 /* PropertyAccessExpression */:
81619                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
81620                         capturedSuperProperties.set(node.name.escapedText, true);
81621                     }
81622                     return ts.visitEachChild(node, visitor, context);
81623                 case 195 /* ElementAccessExpression */:
81624                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
81625                         hasSuperElementAccess = true;
81626                     }
81627                     return ts.visitEachChild(node, visitor, context);
81628                 case 245 /* ClassDeclaration */:
81629                 case 214 /* ClassExpression */:
81630                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81631                 default:
81632                     return ts.visitEachChild(node, visitor, context);
81633             }
81634         }
81635         function visitAwaitExpression(node) {
81636             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81637                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), 
81638                 /*location*/ node), node);
81639             }
81640             return ts.visitEachChild(node, visitor, context);
81641         }
81642         function visitYieldExpression(node) {
81643             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81644                 if (node.asteriskToken) {
81645                     var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81646                     return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
81647                 }
81648                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
81649                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
81650                     : ts.createVoidZero())), node), node);
81651             }
81652             return ts.visitEachChild(node, visitor, context);
81653         }
81654         function visitReturnStatement(node) {
81655             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81656                 return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
81657             }
81658             return ts.visitEachChild(node, visitor, context);
81659         }
81660         function visitLabeledStatement(node) {
81661             if (enclosingFunctionFlags & 2 /* Async */) {
81662                 var statement = ts.unwrapInnermostStatementOfLabel(node);
81663                 if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) {
81664                     return visitForOfStatement(statement, node);
81665                 }
81666                 return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node);
81667             }
81668             return ts.visitEachChild(node, visitor, context);
81669         }
81670         function chunkObjectLiteralElements(elements) {
81671             var chunkObject;
81672             var objects = [];
81673             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
81674                 var e = elements_4[_i];
81675                 if (e.kind === 283 /* SpreadAssignment */) {
81676                     if (chunkObject) {
81677                         objects.push(ts.createObjectLiteral(chunkObject));
81678                         chunkObject = undefined;
81679                     }
81680                     var target = e.expression;
81681                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
81682                 }
81683                 else {
81684                     chunkObject = ts.append(chunkObject, e.kind === 281 /* PropertyAssignment */
81685                         ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
81686                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
81687                 }
81688             }
81689             if (chunkObject) {
81690                 objects.push(ts.createObjectLiteral(chunkObject));
81691             }
81692             return objects;
81693         }
81694         function visitObjectLiteralExpression(node) {
81695             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81696                 // spread elements emit like so:
81697                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
81698                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
81699                 // If the first element is a spread element, then the first argument to __assign is {}:
81700                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
81701                 //
81702                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
81703                 // example:
81704                 //      var k = { a: 1, b: 2 };
81705                 //      var o = { a: 3, ...k, b: k.a++ };
81706                 //      // expected: { a: 1, b: 1 }
81707                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
81708                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
81709                 //
81710                 // This also occurs for spread elements, not just property assignments:
81711                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
81712                 //      var l = { c: 3 };
81713                 //      var o = { ...k, ...l };
81714                 //      // expected: { a: 1, b: 2, z: 9 }
81715                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
81716                 // end up with `{ a: 1, b: 2, c: 3 }`
81717                 var objects = chunkObjectLiteralElements(node.properties);
81718                 if (objects.length && objects[0].kind !== 193 /* ObjectLiteralExpression */) {
81719                     objects.unshift(ts.createObjectLiteral());
81720                 }
81721                 var expression = objects[0];
81722                 if (objects.length > 1) {
81723                     for (var i = 1; i < objects.length; i++) {
81724                         expression = createAssignHelper(context, [expression, objects[i]]);
81725                     }
81726                     return expression;
81727                 }
81728                 else {
81729                     return createAssignHelper(context, objects);
81730                 }
81731             }
81732             return ts.visitEachChild(node, visitor, context);
81733         }
81734         function visitExpressionStatement(node) {
81735             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81736         }
81737         function visitParenthesizedExpression(node, noDestructuringValue) {
81738             return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
81739         }
81740         function visitSourceFile(node) {
81741             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
81742                 0 /* StrictModeSourceFileIncludes */ :
81743                 1 /* SourceFileIncludes */);
81744             exportedVariableStatement = false;
81745             var visited = ts.visitEachChild(node, visitor, context);
81746             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
81747                 ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))
81748             ]);
81749             var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements));
81750             exitSubtree(ancestorFacts);
81751             return result;
81752         }
81753         function visitTaggedTemplateExpression(node) {
81754             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
81755         }
81756         /**
81757          * Visits a BinaryExpression that contains a destructuring assignment.
81758          *
81759          * @param node A BinaryExpression node.
81760          */
81761         function visitBinaryExpression(node, noDestructuringValue) {
81762             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81763                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
81764             }
81765             else if (node.operatorToken.kind === 27 /* CommaToken */) {
81766                 return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
81767             }
81768             return ts.visitEachChild(node, visitor, context);
81769         }
81770         function visitCatchClause(node) {
81771             if (node.variableDeclaration &&
81772                 ts.isBindingPattern(node.variableDeclaration.name) &&
81773                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81774                 var name = ts.getGeneratedNameForNode(node.variableDeclaration.name);
81775                 var updatedDecl = ts.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
81776                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
81777                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
81778                 if (ts.some(visitedBindings)) {
81779                     block = ts.updateBlock(block, __spreadArrays([
81780                         ts.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
81781                     ], block.statements));
81782                 }
81783                 return ts.updateCatchClause(node, ts.updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined), block);
81784             }
81785             return ts.visitEachChild(node, visitor, context);
81786         }
81787         function visitVariableStatement(node) {
81788             if (ts.hasModifier(node, 1 /* Export */)) {
81789                 var savedExportedVariableStatement = exportedVariableStatement;
81790                 exportedVariableStatement = true;
81791                 var visited = ts.visitEachChild(node, visitor, context);
81792                 exportedVariableStatement = savedExportedVariableStatement;
81793                 return visited;
81794             }
81795             return ts.visitEachChild(node, visitor, context);
81796         }
81797         /**
81798          * Visits a VariableDeclaration node with a binding pattern.
81799          *
81800          * @param node A VariableDeclaration node.
81801          */
81802         function visitVariableDeclaration(node) {
81803             if (exportedVariableStatement) {
81804                 var savedExportedVariableStatement = exportedVariableStatement;
81805                 exportedVariableStatement = false;
81806                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
81807                 exportedVariableStatement = savedExportedVariableStatement;
81808                 return visited;
81809             }
81810             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
81811         }
81812         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
81813             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
81814             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81815                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
81816                 /*rval*/ undefined, exportedVariableStatement);
81817             }
81818             return ts.visitEachChild(node, visitor, context);
81819         }
81820         function visitForStatement(node) {
81821             return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement));
81822         }
81823         function visitVoidExpression(node) {
81824             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81825         }
81826         /**
81827          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
81828          *
81829          * @param node A ForOfStatement.
81830          */
81831         function visitForOfStatement(node, outermostLabeledStatement) {
81832             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81833             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81834                 node = transformForOfStatementWithObjectRest(node);
81835             }
81836             var result = node.awaitModifier ?
81837                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
81838                 ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
81839             exitSubtree(ancestorFacts);
81840             return result;
81841         }
81842         function transformForOfStatementWithObjectRest(node) {
81843             var initializerWithoutParens = ts.skipParentheses(node.initializer);
81844             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
81845                 var bodyLocation = void 0;
81846                 var statementsLocation = void 0;
81847                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
81848                 var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
81849                 if (ts.isBlock(node.statement)) {
81850                     ts.addRange(statements, node.statement.statements);
81851                     bodyLocation = node.statement;
81852                     statementsLocation = node.statement.statements;
81853                 }
81854                 else if (node.statement) {
81855                     ts.append(statements, node.statement);
81856                     bodyLocation = node.statement;
81857                     statementsLocation = node.statement;
81858                 }
81859                 return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
81860                     ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
81861                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81862                 /*multiLine*/ true), bodyLocation));
81863             }
81864             return node;
81865         }
81866         function convertForOfStatementHead(node, boundValue) {
81867             var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
81868             var bodyLocation;
81869             var statementsLocation;
81870             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
81871             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
81872             if (ts.isBlock(statement)) {
81873                 ts.addRange(statements, statement.statements);
81874                 bodyLocation = statement;
81875                 statementsLocation = statement.statements;
81876             }
81877             else {
81878                 statements.push(statement);
81879             }
81880             return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81881             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
81882         }
81883         function createDownlevelAwait(expression) {
81884             return enclosingFunctionFlags & 1 /* Generator */
81885                 ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
81886                 : ts.createAwait(expression);
81887         }
81888         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
81889             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81890             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81891             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81892             var errorRecord = ts.createUniqueName("e");
81893             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
81894             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
81895             var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
81896             var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
81897             var getDone = ts.createPropertyAccess(result, "done");
81898             var getValue = ts.createPropertyAccess(result, "value");
81899             var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
81900             hoistVariableDeclaration(errorRecord);
81901             hoistVariableDeclaration(returnMethod);
81902             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
81903             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
81904                 ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) :
81905                 callValues;
81906             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
81907             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
81908                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
81909                 ts.createVariableDeclaration(result)
81910             ]), node.expression), 2097152 /* NoHoisting */), 
81911             /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), 
81912             /*incrementor*/ undefined, 
81913             /*statement*/ convertForOfStatementHead(node, getValue)), 
81914             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
81915             return ts.createTry(ts.createBlock([
81916                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
81917             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
81918                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
81919                     ts.createPropertyAssignment("error", catchVariable)
81920                 ])))
81921             ]), 1 /* SingleLine */)), ts.createBlock([
81922                 ts.createTry(
81923                 /*tryBlock*/ ts.createBlock([
81924                     ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */)
81925                 ]), 
81926                 /*catchClause*/ undefined, 
81927                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
81928                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
81929                 ]), 1 /* SingleLine */))
81930             ]));
81931         }
81932         function visitParameter(node) {
81933             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81934                 // Binding patterns are converted into a generated name and are
81935                 // evaluated inside the function body.
81936                 return ts.updateParameter(node, 
81937                 /*decorators*/ undefined, 
81938                 /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), 
81939                 /*questionToken*/ undefined, 
81940                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
81941             }
81942             return ts.visitEachChild(node, visitor, context);
81943         }
81944         function visitConstructorDeclaration(node) {
81945             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81946             enclosingFunctionFlags = 0 /* Normal */;
81947             var updated = ts.updateConstructor(node, 
81948             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81949             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81950             return updated;
81951         }
81952         function visitGetAccessorDeclaration(node) {
81953             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81954             enclosingFunctionFlags = 0 /* Normal */;
81955             var updated = ts.updateGetAccessor(node, 
81956             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
81957             /*type*/ undefined, transformFunctionBody(node));
81958             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81959             return updated;
81960         }
81961         function visitSetAccessorDeclaration(node) {
81962             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81963             enclosingFunctionFlags = 0 /* Normal */;
81964             var updated = ts.updateSetAccessor(node, 
81965             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81966             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81967             return updated;
81968         }
81969         function visitMethodDeclaration(node) {
81970             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81971             enclosingFunctionFlags = ts.getFunctionFlags(node);
81972             var updated = ts.updateMethod(node, 
81973             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81974                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81975                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81976                 ? undefined
81977                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
81978             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81979             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81980                 ? transformAsyncGeneratorFunctionBody(node)
81981                 : transformFunctionBody(node));
81982             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81983             return updated;
81984         }
81985         function visitFunctionDeclaration(node) {
81986             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81987             enclosingFunctionFlags = ts.getFunctionFlags(node);
81988             var updated = ts.updateFunctionDeclaration(node, 
81989             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81990                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81991                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81992                 ? undefined
81993                 : node.asteriskToken, node.name, 
81994             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81995             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81996                 ? transformAsyncGeneratorFunctionBody(node)
81997                 : transformFunctionBody(node));
81998             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81999             return updated;
82000         }
82001         function visitArrowFunction(node) {
82002             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82003             enclosingFunctionFlags = ts.getFunctionFlags(node);
82004             var updated = ts.updateArrowFunction(node, node.modifiers, 
82005             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82006             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
82007             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82008             return updated;
82009         }
82010         function visitFunctionExpression(node) {
82011             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82012             enclosingFunctionFlags = ts.getFunctionFlags(node);
82013             var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
82014                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
82015                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
82016                 ? undefined
82017                 : node.asteriskToken, node.name, 
82018             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82019             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
82020                 ? transformAsyncGeneratorFunctionBody(node)
82021                 : transformFunctionBody(node));
82022             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82023             return updated;
82024         }
82025         function transformAsyncGeneratorFunctionBody(node) {
82026             resumeLexicalEnvironment();
82027             var statements = [];
82028             var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
82029             appendObjectRestAssignmentsIfNeeded(statements, node);
82030             var savedCapturedSuperProperties = capturedSuperProperties;
82031             var savedHasSuperElementAccess = hasSuperElementAccess;
82032             capturedSuperProperties = ts.createUnderscoreEscapedMap();
82033             hasSuperElementAccess = false;
82034             var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
82035             /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), 
82036             /*typeParameters*/ undefined, 
82037             /*parameters*/ [], 
82038             /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
82039             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
82040             // This step isn't needed if we eventually transform this to ES5.
82041             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
82042             if (emitSuperHelpers) {
82043                 enableSubstitutionForAsyncMethodsWithSuper();
82044                 var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
82045                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
82046                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
82047             }
82048             statements.push(returnStatement);
82049             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
82050             var block = ts.updateBlock(node.body, statements);
82051             if (emitSuperHelpers && hasSuperElementAccess) {
82052                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
82053                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
82054                 }
82055                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
82056                     ts.addEmitHelper(block, ts.asyncSuperHelper);
82057                 }
82058             }
82059             capturedSuperProperties = savedCapturedSuperProperties;
82060             hasSuperElementAccess = savedHasSuperElementAccess;
82061             return block;
82062         }
82063         function transformFunctionBody(node) {
82064             resumeLexicalEnvironment();
82065             var statementOffset = 0;
82066             var statements = [];
82067             var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
82068             if (ts.isBlock(body)) {
82069                 statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
82070             }
82071             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
82072             var leadingStatements = endLexicalEnvironment();
82073             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
82074                 var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
82075                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
82076                 ts.addRange(statements, block.statements.slice(statementOffset));
82077                 return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
82078             }
82079             return body;
82080         }
82081         function appendObjectRestAssignmentsIfNeeded(statements, node) {
82082             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
82083                 var parameter = _a[_i];
82084                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
82085                     var temp = ts.getGeneratedNameForNode(parameter);
82086                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
82087                     /*doNotRecordTempVariablesInLine*/ false, 
82088                     /*skipInitializer*/ true);
82089                     if (ts.some(declarations)) {
82090                         var statement = ts.createVariableStatement(
82091                         /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
82092                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
82093                         statements = ts.append(statements, statement);
82094                     }
82095                 }
82096             }
82097             return statements;
82098         }
82099         function enableSubstitutionForAsyncMethodsWithSuper() {
82100             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
82101                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
82102                 // We need to enable substitutions for call, property access, and element access
82103                 // if we need to rewrite super calls.
82104                 context.enableSubstitution(196 /* CallExpression */);
82105                 context.enableSubstitution(194 /* PropertyAccessExpression */);
82106                 context.enableSubstitution(195 /* ElementAccessExpression */);
82107                 // We need to be notified when entering and exiting declarations that bind super.
82108                 context.enableEmitNotification(245 /* ClassDeclaration */);
82109                 context.enableEmitNotification(161 /* MethodDeclaration */);
82110                 context.enableEmitNotification(163 /* GetAccessor */);
82111                 context.enableEmitNotification(164 /* SetAccessor */);
82112                 context.enableEmitNotification(162 /* Constructor */);
82113                 // We need to be notified when entering the generated accessor arrow functions.
82114                 context.enableEmitNotification(225 /* VariableStatement */);
82115             }
82116         }
82117         /**
82118          * Called by the printer just before a node is printed.
82119          *
82120          * @param hint A hint as to the intended usage of the node.
82121          * @param node The node to be printed.
82122          * @param emitCallback The callback used to emit the node.
82123          */
82124         function onEmitNode(hint, node, emitCallback) {
82125             // If we need to support substitutions for `super` in an async method,
82126             // we should track it here.
82127             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
82128                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
82129                 if (superContainerFlags !== enclosingSuperContainerFlags) {
82130                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82131                     enclosingSuperContainerFlags = superContainerFlags;
82132                     previousOnEmitNode(hint, node, emitCallback);
82133                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82134                     return;
82135                 }
82136             }
82137             // Disable substitution in the generated super accessor itself.
82138             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
82139                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82140                 enclosingSuperContainerFlags = 0;
82141                 previousOnEmitNode(hint, node, emitCallback);
82142                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82143                 return;
82144             }
82145             previousOnEmitNode(hint, node, emitCallback);
82146         }
82147         /**
82148          * Hooks node substitutions.
82149          *
82150          * @param hint The context for the emitter.
82151          * @param node The node to substitute.
82152          */
82153         function onSubstituteNode(hint, node) {
82154             node = previousOnSubstituteNode(hint, node);
82155             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
82156                 return substituteExpression(node);
82157             }
82158             return node;
82159         }
82160         function substituteExpression(node) {
82161             switch (node.kind) {
82162                 case 194 /* PropertyAccessExpression */:
82163                     return substitutePropertyAccessExpression(node);
82164                 case 195 /* ElementAccessExpression */:
82165                     return substituteElementAccessExpression(node);
82166                 case 196 /* CallExpression */:
82167                     return substituteCallExpression(node);
82168             }
82169             return node;
82170         }
82171         function substitutePropertyAccessExpression(node) {
82172             if (node.expression.kind === 102 /* SuperKeyword */) {
82173                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
82174             }
82175             return node;
82176         }
82177         function substituteElementAccessExpression(node) {
82178             if (node.expression.kind === 102 /* SuperKeyword */) {
82179                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
82180             }
82181             return node;
82182         }
82183         function substituteCallExpression(node) {
82184             var expression = node.expression;
82185             if (ts.isSuperProperty(expression)) {
82186                 var argumentExpression = ts.isPropertyAccessExpression(expression)
82187                     ? substitutePropertyAccessExpression(expression)
82188                     : substituteElementAccessExpression(expression);
82189                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
82190                 /*typeArguments*/ undefined, __spreadArrays([
82191                     ts.createThis()
82192                 ], node.arguments));
82193             }
82194             return node;
82195         }
82196         function isSuperContainer(node) {
82197             var kind = node.kind;
82198             return kind === 245 /* ClassDeclaration */
82199                 || kind === 162 /* Constructor */
82200                 || kind === 161 /* MethodDeclaration */
82201                 || kind === 163 /* GetAccessor */
82202                 || kind === 164 /* SetAccessor */;
82203         }
82204         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
82205             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
82206                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), 
82207                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
82208             }
82209             else {
82210                 return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), 
82211                 /*typeArguments*/ undefined, [argumentExpression]), location);
82212             }
82213         }
82214     }
82215     ts.transformES2018 = transformES2018;
82216     ts.assignHelper = {
82217         name: "typescript:assign",
82218         importName: "__assign",
82219         scoped: false,
82220         priority: 1,
82221         text: "\n            var __assign = (this && this.__assign) || function () {\n                __assign = Object.assign || function(t) {\n                    for (var s, i = 1, n = arguments.length; i < n; i++) {\n                        s = arguments[i];\n                        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n                            t[p] = s[p];\n                    }\n                    return t;\n                };\n                return __assign.apply(this, arguments);\n            };"
82222     };
82223     function createAssignHelper(context, attributesSegments) {
82224         if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
82225             return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments);
82226         }
82227         context.requestEmitHelper(ts.assignHelper);
82228         return ts.createCall(ts.getUnscopedHelperName("__assign"), 
82229         /*typeArguments*/ undefined, attributesSegments);
82230     }
82231     ts.createAssignHelper = createAssignHelper;
82232     ts.awaitHelper = {
82233         name: "typescript:await",
82234         importName: "__await",
82235         scoped: false,
82236         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
82237     };
82238     function createAwaitHelper(context, expression) {
82239         context.requestEmitHelper(ts.awaitHelper);
82240         return ts.createCall(ts.getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
82241     }
82242     ts.asyncGeneratorHelper = {
82243         name: "typescript:asyncGenerator",
82244         importName: "__asyncGenerator",
82245         scoped: false,
82246         dependencies: [ts.awaitHelper],
82247         text: "\n            var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n                if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n                var g = generator.apply(thisArg, _arguments || []), i, q = [];\n                return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n                function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n                function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n                function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n                function fulfill(value) { resume(\"next\", value); }\n                function reject(value) { resume(\"throw\", value); }\n                function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n            };"
82248     };
82249     function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) {
82250         context.requestEmitHelper(ts.asyncGeneratorHelper);
82251         // Mark this node as originally an async function
82252         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
82253         return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), 
82254         /*typeArguments*/ undefined, [
82255             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
82256             ts.createIdentifier("arguments"),
82257             generatorFunc
82258         ]);
82259     }
82260     ts.asyncDelegator = {
82261         name: "typescript:asyncDelegator",
82262         importName: "__asyncDelegator",
82263         scoped: false,
82264         dependencies: [ts.awaitHelper],
82265         text: "\n            var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n                var i, p;\n                return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n                function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n            };"
82266     };
82267     function createAsyncDelegatorHelper(context, expression, location) {
82268         context.requestEmitHelper(ts.asyncDelegator);
82269         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncDelegator"), 
82270         /*typeArguments*/ undefined, [expression]), location);
82271     }
82272     ts.asyncValues = {
82273         name: "typescript:asyncValues",
82274         importName: "__asyncValues",
82275         scoped: false,
82276         text: "\n            var __asyncValues = (this && this.__asyncValues) || function (o) {\n                if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n                var m = o[Symbol.asyncIterator], i;\n                return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n                function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n                function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n            };"
82277     };
82278     function createAsyncValuesHelper(context, expression, location) {
82279         context.requestEmitHelper(ts.asyncValues);
82280         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncValues"), 
82281         /*typeArguments*/ undefined, [expression]), location);
82282     }
82283 })(ts || (ts = {}));
82284 /*@internal*/
82285 var ts;
82286 (function (ts) {
82287     function transformES2019(context) {
82288         return ts.chainBundle(transformSourceFile);
82289         function transformSourceFile(node) {
82290             if (node.isDeclarationFile) {
82291                 return node;
82292             }
82293             return ts.visitEachChild(node, visitor, context);
82294         }
82295         function visitor(node) {
82296             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
82297                 return node;
82298             }
82299             switch (node.kind) {
82300                 case 280 /* CatchClause */:
82301                     return visitCatchClause(node);
82302                 default:
82303                     return ts.visitEachChild(node, visitor, context);
82304             }
82305         }
82306         function visitCatchClause(node) {
82307             if (!node.variableDeclaration) {
82308                 return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
82309             }
82310             return ts.visitEachChild(node, visitor, context);
82311         }
82312     }
82313     ts.transformES2019 = transformES2019;
82314 })(ts || (ts = {}));
82315 /*@internal*/
82316 var ts;
82317 (function (ts) {
82318     function transformES2020(context) {
82319         var hoistVariableDeclaration = context.hoistVariableDeclaration;
82320         return ts.chainBundle(transformSourceFile);
82321         function transformSourceFile(node) {
82322             if (node.isDeclarationFile) {
82323                 return node;
82324             }
82325             return ts.visitEachChild(node, visitor, context);
82326         }
82327         function visitor(node) {
82328             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
82329                 return node;
82330             }
82331             switch (node.kind) {
82332                 case 194 /* PropertyAccessExpression */:
82333                 case 195 /* ElementAccessExpression */:
82334                 case 196 /* CallExpression */:
82335                     if (node.flags & 32 /* OptionalChain */) {
82336                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
82337                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
82338                         return updated;
82339                     }
82340                     return ts.visitEachChild(node, visitor, context);
82341                 case 209 /* BinaryExpression */:
82342                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
82343                         return transformNullishCoalescingExpression(node);
82344                     }
82345                     return ts.visitEachChild(node, visitor, context);
82346                 case 203 /* DeleteExpression */:
82347                     return visitDeleteExpression(node);
82348                 default:
82349                     return ts.visitEachChild(node, visitor, context);
82350             }
82351         }
82352         function flattenChain(chain) {
82353             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82354             var links = [chain];
82355             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
82356                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
82357                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82358                 links.unshift(chain);
82359             }
82360             return { expression: chain.expression, chain: links };
82361         }
82362         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
82363             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
82364             if (ts.isSyntheticReference(expression)) {
82365                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
82366                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
82367                 return ts.createSyntheticReferenceExpression(ts.updateParen(node, expression.expression), expression.thisArg);
82368             }
82369             return ts.updateParen(node, expression);
82370         }
82371         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
82372             if (ts.isOptionalChain(node)) {
82373                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82374                 return visitOptionalExpression(node, captureThisArg, isDelete);
82375             }
82376             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
82377             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
82378             var thisArg;
82379             if (captureThisArg) {
82380                 if (shouldCaptureInTempVariable(expression)) {
82381                     thisArg = ts.createTempVariable(hoistVariableDeclaration);
82382                     expression = ts.createAssignment(thisArg, expression);
82383                     // if (inParameterInitializer) tempVariableInParameter = true;
82384                 }
82385                 else {
82386                     thisArg = expression;
82387                 }
82388             }
82389             expression = node.kind === 194 /* PropertyAccessExpression */
82390                 ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
82391                 : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
82392             return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression;
82393         }
82394         function visitNonOptionalCallExpression(node, captureThisArg) {
82395             if (ts.isOptionalChain(node)) {
82396                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82397                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
82398             }
82399             return ts.visitEachChild(node, visitor, context);
82400         }
82401         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
82402             switch (node.kind) {
82403                 case 200 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
82404                 case 194 /* PropertyAccessExpression */:
82405                 case 195 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
82406                 case 196 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
82407                 default: return ts.visitNode(node, visitor, ts.isExpression);
82408             }
82409         }
82410         function visitOptionalExpression(node, captureThisArg, isDelete) {
82411             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
82412             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
82413             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
82414             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
82415             var capturedLeft = leftExpression;
82416             if (shouldCaptureInTempVariable(leftExpression)) {
82417                 capturedLeft = ts.createTempVariable(hoistVariableDeclaration);
82418                 leftExpression = ts.createAssignment(capturedLeft, leftExpression);
82419                 // if (inParameterInitializer) tempVariableInParameter = true;
82420             }
82421             var rightExpression = capturedLeft;
82422             var thisArg;
82423             for (var i = 0; i < chain.length; i++) {
82424                 var segment = chain[i];
82425                 switch (segment.kind) {
82426                     case 194 /* PropertyAccessExpression */:
82427                     case 195 /* ElementAccessExpression */:
82428                         if (i === chain.length - 1 && captureThisArg) {
82429                             if (shouldCaptureInTempVariable(rightExpression)) {
82430                                 thisArg = ts.createTempVariable(hoistVariableDeclaration);
82431                                 rightExpression = ts.createAssignment(thisArg, rightExpression);
82432                                 // if (inParameterInitializer) tempVariableInParameter = true;
82433                             }
82434                             else {
82435                                 thisArg = rightExpression;
82436                             }
82437                         }
82438                         rightExpression = segment.kind === 194 /* PropertyAccessExpression */
82439                             ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
82440                             : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
82441                         break;
82442                     case 196 /* CallExpression */:
82443                         if (i === 0 && leftThisArg) {
82444                             rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 102 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82445                         }
82446                         else {
82447                             rightExpression = ts.createCall(rightExpression, 
82448                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82449                         }
82450                         break;
82451                 }
82452                 ts.setOriginalNode(rightExpression, segment);
82453             }
82454             var target = isDelete
82455                 ? ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createTrue(), ts.createDelete(rightExpression))
82456                 : ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression);
82457             return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target;
82458         }
82459         function createNotNullCondition(left, right, invert) {
82460             return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), ts.createBinary(right, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero()));
82461         }
82462         function transformNullishCoalescingExpression(node) {
82463             var left = ts.visitNode(node.left, visitor, ts.isExpression);
82464             var right = left;
82465             if (shouldCaptureInTempVariable(left)) {
82466                 right = ts.createTempVariable(hoistVariableDeclaration);
82467                 left = ts.createAssignment(right, left);
82468                 // if (inParameterInitializer) tempVariableInParameter = true;
82469             }
82470             return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression));
82471         }
82472         function shouldCaptureInTempVariable(expression) {
82473             // don't capture identifiers and `this` in a temporary variable
82474             // `super` cannot be captured as it's no real variable
82475             return !ts.isIdentifier(expression) &&
82476                 expression.kind !== 104 /* ThisKeyword */ &&
82477                 expression.kind !== 102 /* SuperKeyword */;
82478         }
82479         function visitDeleteExpression(node) {
82480             return ts.isOptionalChain(ts.skipParentheses(node.expression))
82481                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
82482                 : ts.updateDelete(node, ts.visitNode(node.expression, visitor, ts.isExpression));
82483         }
82484     }
82485     ts.transformES2020 = transformES2020;
82486 })(ts || (ts = {}));
82487 /*@internal*/
82488 var ts;
82489 (function (ts) {
82490     function transformESNext(context) {
82491         return ts.chainBundle(transformSourceFile);
82492         function transformSourceFile(node) {
82493             if (node.isDeclarationFile) {
82494                 return node;
82495             }
82496             return ts.visitEachChild(node, visitor, context);
82497         }
82498         function visitor(node) {
82499             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
82500                 return node;
82501             }
82502             switch (node.kind) {
82503                 default:
82504                     return ts.visitEachChild(node, visitor, context);
82505             }
82506         }
82507     }
82508     ts.transformESNext = transformESNext;
82509 })(ts || (ts = {}));
82510 /*@internal*/
82511 var ts;
82512 (function (ts) {
82513     function transformJsx(context) {
82514         var compilerOptions = context.getCompilerOptions();
82515         var currentSourceFile;
82516         return ts.chainBundle(transformSourceFile);
82517         /**
82518          * Transform JSX-specific syntax in a SourceFile.
82519          *
82520          * @param node A SourceFile node.
82521          */
82522         function transformSourceFile(node) {
82523             if (node.isDeclarationFile) {
82524                 return node;
82525             }
82526             currentSourceFile = node;
82527             var visited = ts.visitEachChild(node, visitor, context);
82528             ts.addEmitHelpers(visited, context.readEmitHelpers());
82529             return visited;
82530         }
82531         function visitor(node) {
82532             if (node.transformFlags & 2 /* ContainsJsx */) {
82533                 return visitorWorker(node);
82534             }
82535             else {
82536                 return node;
82537             }
82538         }
82539         function visitorWorker(node) {
82540             switch (node.kind) {
82541                 case 266 /* JsxElement */:
82542                     return visitJsxElement(node, /*isChild*/ false);
82543                 case 267 /* JsxSelfClosingElement */:
82544                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
82545                 case 270 /* JsxFragment */:
82546                     return visitJsxFragment(node, /*isChild*/ false);
82547                 case 276 /* JsxExpression */:
82548                     return visitJsxExpression(node);
82549                 default:
82550                     return ts.visitEachChild(node, visitor, context);
82551             }
82552         }
82553         function transformJsxChildToExpression(node) {
82554             switch (node.kind) {
82555                 case 11 /* JsxText */:
82556                     return visitJsxText(node);
82557                 case 276 /* JsxExpression */:
82558                     return visitJsxExpression(node);
82559                 case 266 /* JsxElement */:
82560                     return visitJsxElement(node, /*isChild*/ true);
82561                 case 267 /* JsxSelfClosingElement */:
82562                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
82563                 case 270 /* JsxFragment */:
82564                     return visitJsxFragment(node, /*isChild*/ true);
82565                 default:
82566                     return ts.Debug.failBadSyntaxKind(node);
82567             }
82568         }
82569         function visitJsxElement(node, isChild) {
82570             return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
82571         }
82572         function visitJsxSelfClosingElement(node, isChild) {
82573             return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
82574         }
82575         function visitJsxFragment(node, isChild) {
82576             return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
82577         }
82578         function visitJsxOpeningLikeElement(node, children, isChild, location) {
82579             var tagName = getTagName(node);
82580             var objectProperties;
82581             var attrs = node.attributes.properties;
82582             if (attrs.length === 0) {
82583                 // When there are no attributes, React wants "null"
82584                 objectProperties = ts.createNull();
82585             }
82586             else {
82587                 // Map spans of JsxAttribute nodes into object literals and spans
82588                 // of JsxSpreadAttribute nodes into expressions.
82589                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
82590                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
82591                     : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
82592                 if (ts.isJsxSpreadAttribute(attrs[0])) {
82593                     // We must always emit at least one object literal before a spread
82594                     // argument.
82595                     segments.unshift(ts.createObjectLiteral());
82596                 }
82597                 // Either emit one big object literal (no spread attribs), or
82598                 // a call to the __assign helper.
82599                 objectProperties = ts.singleOrUndefined(segments);
82600                 if (!objectProperties) {
82601                     objectProperties = ts.createAssignHelper(context, segments);
82602                 }
82603             }
82604             var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82605             tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
82606             if (isChild) {
82607                 ts.startOnNewLine(element);
82608             }
82609             return element;
82610         }
82611         function visitJsxOpeningFragment(node, children, isChild, location) {
82612             var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82613             ts.mapDefined(children, transformJsxChildToExpression), node, location);
82614             if (isChild) {
82615                 ts.startOnNewLine(element);
82616             }
82617             return element;
82618         }
82619         function transformJsxSpreadAttributeToExpression(node) {
82620             return ts.visitNode(node.expression, visitor, ts.isExpression);
82621         }
82622         function transformJsxAttributeToObjectLiteralElement(node) {
82623             var name = getAttributeName(node);
82624             var expression = transformJsxAttributeInitializer(node.initializer);
82625             return ts.createPropertyAssignment(name, expression);
82626         }
82627         function transformJsxAttributeInitializer(node) {
82628             if (node === undefined) {
82629                 return ts.createTrue();
82630             }
82631             else if (node.kind === 10 /* StringLiteral */) {
82632                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
82633                 // Need to be escaped to be handled correctly in a normal string
82634                 var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
82635                 literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
82636                 return ts.setTextRange(literal, node);
82637             }
82638             else if (node.kind === 276 /* JsxExpression */) {
82639                 if (node.expression === undefined) {
82640                     return ts.createTrue();
82641                 }
82642                 return visitJsxExpression(node);
82643             }
82644             else {
82645                 return ts.Debug.failBadSyntaxKind(node);
82646             }
82647         }
82648         function visitJsxText(node) {
82649             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
82650             return fixed === undefined ? undefined : ts.createLiteral(fixed);
82651         }
82652         /**
82653          * JSX trims whitespace at the end and beginning of lines, except that the
82654          * start/end of a tag is considered a start/end of a line only if that line is
82655          * on the same line as the closing tag. See examples in
82656          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
82657          * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model
82658          *
82659          * An equivalent algorithm would be:
82660          * - If there is only one line, return it.
82661          * - If there is only whitespace (but multiple lines), return `undefined`.
82662          * - Split the text into lines.
82663          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
82664          * - Decode entities on each line (individually).
82665          * - Remove empty lines and join the rest with " ".
82666          */
82667         function fixupWhitespaceAndDecodeEntities(text) {
82668             var acc;
82669             // First non-whitespace character on this line.
82670             var firstNonWhitespace = 0;
82671             // Last non-whitespace character on this line.
82672             var lastNonWhitespace = -1;
82673             // These initial values are special because the first line is:
82674             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
82675             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
82676             for (var i = 0; i < text.length; i++) {
82677                 var c = text.charCodeAt(i);
82678                 if (ts.isLineBreak(c)) {
82679                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
82680                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
82681                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
82682                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
82683                     }
82684                     // Reset firstNonWhitespace for the next line.
82685                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
82686                     firstNonWhitespace = -1;
82687                 }
82688                 else if (!ts.isWhiteSpaceSingleLine(c)) {
82689                     lastNonWhitespace = i;
82690                     if (firstNonWhitespace === -1) {
82691                         firstNonWhitespace = i;
82692                     }
82693                 }
82694             }
82695             return firstNonWhitespace !== -1
82696                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
82697                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
82698                 // Last line was all whitespace, so ignore it
82699                 : acc;
82700         }
82701         function addLineOfJsxText(acc, trimmedLine) {
82702             // We do not escape the string here as that is handled by the printer
82703             // when it emits the literal. We do, however, need to decode JSX entities.
82704             var decoded = decodeEntities(trimmedLine);
82705             return acc === undefined ? decoded : acc + " " + decoded;
82706         }
82707         /**
82708          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
82709          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
82710          */
82711         function decodeEntities(text) {
82712             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
82713                 if (decimal) {
82714                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
82715                 }
82716                 else if (hex) {
82717                     return ts.utf16EncodeAsString(parseInt(hex, 16));
82718                 }
82719                 else {
82720                     var ch = entities.get(word);
82721                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
82722                     return ch ? ts.utf16EncodeAsString(ch) : match;
82723                 }
82724             });
82725         }
82726         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
82727         function tryDecodeEntities(text) {
82728             var decoded = decodeEntities(text);
82729             return decoded === text ? undefined : decoded;
82730         }
82731         function getTagName(node) {
82732             if (node.kind === 266 /* JsxElement */) {
82733                 return getTagName(node.openingElement);
82734             }
82735             else {
82736                 var name = node.tagName;
82737                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
82738                     return ts.createLiteral(ts.idText(name));
82739                 }
82740                 else {
82741                     return ts.createExpressionFromEntityName(name);
82742                 }
82743             }
82744         }
82745         /**
82746          * Emit an attribute name, which is quoted if it needs to be quoted. Because
82747          * these emit into an object literal property name, we don't need to be worried
82748          * about keywords, just non-identifier characters
82749          */
82750         function getAttributeName(node) {
82751             var name = node.name;
82752             var text = ts.idText(name);
82753             if (/^[A-Za-z_]\w*$/.test(text)) {
82754                 return name;
82755             }
82756             else {
82757                 return ts.createLiteral(text);
82758             }
82759         }
82760         function visitJsxExpression(node) {
82761             return ts.visitNode(node.expression, visitor, ts.isExpression);
82762         }
82763     }
82764     ts.transformJsx = transformJsx;
82765     var entities = ts.createMapFromTemplate({
82766         quot: 0x0022,
82767         amp: 0x0026,
82768         apos: 0x0027,
82769         lt: 0x003C,
82770         gt: 0x003E,
82771         nbsp: 0x00A0,
82772         iexcl: 0x00A1,
82773         cent: 0x00A2,
82774         pound: 0x00A3,
82775         curren: 0x00A4,
82776         yen: 0x00A5,
82777         brvbar: 0x00A6,
82778         sect: 0x00A7,
82779         uml: 0x00A8,
82780         copy: 0x00A9,
82781         ordf: 0x00AA,
82782         laquo: 0x00AB,
82783         not: 0x00AC,
82784         shy: 0x00AD,
82785         reg: 0x00AE,
82786         macr: 0x00AF,
82787         deg: 0x00B0,
82788         plusmn: 0x00B1,
82789         sup2: 0x00B2,
82790         sup3: 0x00B3,
82791         acute: 0x00B4,
82792         micro: 0x00B5,
82793         para: 0x00B6,
82794         middot: 0x00B7,
82795         cedil: 0x00B8,
82796         sup1: 0x00B9,
82797         ordm: 0x00BA,
82798         raquo: 0x00BB,
82799         frac14: 0x00BC,
82800         frac12: 0x00BD,
82801         frac34: 0x00BE,
82802         iquest: 0x00BF,
82803         Agrave: 0x00C0,
82804         Aacute: 0x00C1,
82805         Acirc: 0x00C2,
82806         Atilde: 0x00C3,
82807         Auml: 0x00C4,
82808         Aring: 0x00C5,
82809         AElig: 0x00C6,
82810         Ccedil: 0x00C7,
82811         Egrave: 0x00C8,
82812         Eacute: 0x00C9,
82813         Ecirc: 0x00CA,
82814         Euml: 0x00CB,
82815         Igrave: 0x00CC,
82816         Iacute: 0x00CD,
82817         Icirc: 0x00CE,
82818         Iuml: 0x00CF,
82819         ETH: 0x00D0,
82820         Ntilde: 0x00D1,
82821         Ograve: 0x00D2,
82822         Oacute: 0x00D3,
82823         Ocirc: 0x00D4,
82824         Otilde: 0x00D5,
82825         Ouml: 0x00D6,
82826         times: 0x00D7,
82827         Oslash: 0x00D8,
82828         Ugrave: 0x00D9,
82829         Uacute: 0x00DA,
82830         Ucirc: 0x00DB,
82831         Uuml: 0x00DC,
82832         Yacute: 0x00DD,
82833         THORN: 0x00DE,
82834         szlig: 0x00DF,
82835         agrave: 0x00E0,
82836         aacute: 0x00E1,
82837         acirc: 0x00E2,
82838         atilde: 0x00E3,
82839         auml: 0x00E4,
82840         aring: 0x00E5,
82841         aelig: 0x00E6,
82842         ccedil: 0x00E7,
82843         egrave: 0x00E8,
82844         eacute: 0x00E9,
82845         ecirc: 0x00EA,
82846         euml: 0x00EB,
82847         igrave: 0x00EC,
82848         iacute: 0x00ED,
82849         icirc: 0x00EE,
82850         iuml: 0x00EF,
82851         eth: 0x00F0,
82852         ntilde: 0x00F1,
82853         ograve: 0x00F2,
82854         oacute: 0x00F3,
82855         ocirc: 0x00F4,
82856         otilde: 0x00F5,
82857         ouml: 0x00F6,
82858         divide: 0x00F7,
82859         oslash: 0x00F8,
82860         ugrave: 0x00F9,
82861         uacute: 0x00FA,
82862         ucirc: 0x00FB,
82863         uuml: 0x00FC,
82864         yacute: 0x00FD,
82865         thorn: 0x00FE,
82866         yuml: 0x00FF,
82867         OElig: 0x0152,
82868         oelig: 0x0153,
82869         Scaron: 0x0160,
82870         scaron: 0x0161,
82871         Yuml: 0x0178,
82872         fnof: 0x0192,
82873         circ: 0x02C6,
82874         tilde: 0x02DC,
82875         Alpha: 0x0391,
82876         Beta: 0x0392,
82877         Gamma: 0x0393,
82878         Delta: 0x0394,
82879         Epsilon: 0x0395,
82880         Zeta: 0x0396,
82881         Eta: 0x0397,
82882         Theta: 0x0398,
82883         Iota: 0x0399,
82884         Kappa: 0x039A,
82885         Lambda: 0x039B,
82886         Mu: 0x039C,
82887         Nu: 0x039D,
82888         Xi: 0x039E,
82889         Omicron: 0x039F,
82890         Pi: 0x03A0,
82891         Rho: 0x03A1,
82892         Sigma: 0x03A3,
82893         Tau: 0x03A4,
82894         Upsilon: 0x03A5,
82895         Phi: 0x03A6,
82896         Chi: 0x03A7,
82897         Psi: 0x03A8,
82898         Omega: 0x03A9,
82899         alpha: 0x03B1,
82900         beta: 0x03B2,
82901         gamma: 0x03B3,
82902         delta: 0x03B4,
82903         epsilon: 0x03B5,
82904         zeta: 0x03B6,
82905         eta: 0x03B7,
82906         theta: 0x03B8,
82907         iota: 0x03B9,
82908         kappa: 0x03BA,
82909         lambda: 0x03BB,
82910         mu: 0x03BC,
82911         nu: 0x03BD,
82912         xi: 0x03BE,
82913         omicron: 0x03BF,
82914         pi: 0x03C0,
82915         rho: 0x03C1,
82916         sigmaf: 0x03C2,
82917         sigma: 0x03C3,
82918         tau: 0x03C4,
82919         upsilon: 0x03C5,
82920         phi: 0x03C6,
82921         chi: 0x03C7,
82922         psi: 0x03C8,
82923         omega: 0x03C9,
82924         thetasym: 0x03D1,
82925         upsih: 0x03D2,
82926         piv: 0x03D6,
82927         ensp: 0x2002,
82928         emsp: 0x2003,
82929         thinsp: 0x2009,
82930         zwnj: 0x200C,
82931         zwj: 0x200D,
82932         lrm: 0x200E,
82933         rlm: 0x200F,
82934         ndash: 0x2013,
82935         mdash: 0x2014,
82936         lsquo: 0x2018,
82937         rsquo: 0x2019,
82938         sbquo: 0x201A,
82939         ldquo: 0x201C,
82940         rdquo: 0x201D,
82941         bdquo: 0x201E,
82942         dagger: 0x2020,
82943         Dagger: 0x2021,
82944         bull: 0x2022,
82945         hellip: 0x2026,
82946         permil: 0x2030,
82947         prime: 0x2032,
82948         Prime: 0x2033,
82949         lsaquo: 0x2039,
82950         rsaquo: 0x203A,
82951         oline: 0x203E,
82952         frasl: 0x2044,
82953         euro: 0x20AC,
82954         image: 0x2111,
82955         weierp: 0x2118,
82956         real: 0x211C,
82957         trade: 0x2122,
82958         alefsym: 0x2135,
82959         larr: 0x2190,
82960         uarr: 0x2191,
82961         rarr: 0x2192,
82962         darr: 0x2193,
82963         harr: 0x2194,
82964         crarr: 0x21B5,
82965         lArr: 0x21D0,
82966         uArr: 0x21D1,
82967         rArr: 0x21D2,
82968         dArr: 0x21D3,
82969         hArr: 0x21D4,
82970         forall: 0x2200,
82971         part: 0x2202,
82972         exist: 0x2203,
82973         empty: 0x2205,
82974         nabla: 0x2207,
82975         isin: 0x2208,
82976         notin: 0x2209,
82977         ni: 0x220B,
82978         prod: 0x220F,
82979         sum: 0x2211,
82980         minus: 0x2212,
82981         lowast: 0x2217,
82982         radic: 0x221A,
82983         prop: 0x221D,
82984         infin: 0x221E,
82985         ang: 0x2220,
82986         and: 0x2227,
82987         or: 0x2228,
82988         cap: 0x2229,
82989         cup: 0x222A,
82990         int: 0x222B,
82991         there4: 0x2234,
82992         sim: 0x223C,
82993         cong: 0x2245,
82994         asymp: 0x2248,
82995         ne: 0x2260,
82996         equiv: 0x2261,
82997         le: 0x2264,
82998         ge: 0x2265,
82999         sub: 0x2282,
83000         sup: 0x2283,
83001         nsub: 0x2284,
83002         sube: 0x2286,
83003         supe: 0x2287,
83004         oplus: 0x2295,
83005         otimes: 0x2297,
83006         perp: 0x22A5,
83007         sdot: 0x22C5,
83008         lceil: 0x2308,
83009         rceil: 0x2309,
83010         lfloor: 0x230A,
83011         rfloor: 0x230B,
83012         lang: 0x2329,
83013         rang: 0x232A,
83014         loz: 0x25CA,
83015         spades: 0x2660,
83016         clubs: 0x2663,
83017         hearts: 0x2665,
83018         diams: 0x2666
83019     });
83020 })(ts || (ts = {}));
83021 /*@internal*/
83022 var ts;
83023 (function (ts) {
83024     function transformES2016(context) {
83025         var hoistVariableDeclaration = context.hoistVariableDeclaration;
83026         return ts.chainBundle(transformSourceFile);
83027         function transformSourceFile(node) {
83028             if (node.isDeclarationFile) {
83029                 return node;
83030             }
83031             return ts.visitEachChild(node, visitor, context);
83032         }
83033         function visitor(node) {
83034             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
83035                 return node;
83036             }
83037             switch (node.kind) {
83038                 case 209 /* BinaryExpression */:
83039                     return visitBinaryExpression(node);
83040                 default:
83041                     return ts.visitEachChild(node, visitor, context);
83042             }
83043         }
83044         function visitBinaryExpression(node) {
83045             switch (node.operatorToken.kind) {
83046                 case 66 /* AsteriskAsteriskEqualsToken */:
83047                     return visitExponentiationAssignmentExpression(node);
83048                 case 42 /* AsteriskAsteriskToken */:
83049                     return visitExponentiationExpression(node);
83050                 default:
83051                     return ts.visitEachChild(node, visitor, context);
83052             }
83053         }
83054         function visitExponentiationAssignmentExpression(node) {
83055             var target;
83056             var value;
83057             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83058             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83059             if (ts.isElementAccessExpression(left)) {
83060                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
83061                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83062                 var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83063                 target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
83064                 value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
83065             }
83066             else if (ts.isPropertyAccessExpression(left)) {
83067                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
83068                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83069                 target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
83070                 value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
83071             }
83072             else {
83073                 // Transforms `a **= b` into `a = Math.pow(a, b)`
83074                 target = left;
83075                 value = left;
83076             }
83077             return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
83078         }
83079         function visitExponentiationExpression(node) {
83080             // Transforms `a ** b` into `Math.pow(a, b)`
83081             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83082             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83083             return ts.createMathPow(left, right, /*location*/ node);
83084         }
83085     }
83086     ts.transformES2016 = transformES2016;
83087 })(ts || (ts = {}));
83088 /*@internal*/
83089 var ts;
83090 (function (ts) {
83091     var ES2015SubstitutionFlags;
83092     (function (ES2015SubstitutionFlags) {
83093         /** Enables substitutions for captured `this` */
83094         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
83095         /** Enables substitutions for block-scoped bindings. */
83096         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
83097     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
83098     var LoopOutParameterFlags;
83099     (function (LoopOutParameterFlags) {
83100         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
83101         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
83102     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
83103     var CopyDirection;
83104     (function (CopyDirection) {
83105         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
83106         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
83107     })(CopyDirection || (CopyDirection = {}));
83108     var Jump;
83109     (function (Jump) {
83110         Jump[Jump["Break"] = 2] = "Break";
83111         Jump[Jump["Continue"] = 4] = "Continue";
83112         Jump[Jump["Return"] = 8] = "Return";
83113     })(Jump || (Jump = {}));
83114     // Facts we track as we traverse the tree
83115     var HierarchyFacts;
83116     (function (HierarchyFacts) {
83117         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
83118         //
83119         // Ancestor facts
83120         //
83121         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
83122         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
83123         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
83124         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
83125         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
83126         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
83127         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
83128         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
83129         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
83130         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
83131         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
83132         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
83133         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
83134         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
83135         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
83136         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
83137         //
83138         // Ancestor masks
83139         //
83140         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
83141         // We are always in *some* kind of block scope, but only specific block-scope containers are
83142         // top-level or Blocks.
83143         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
83144         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
83145         // A source file is a top-level block scope.
83146         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
83147         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
83148         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
83149         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
83150         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
83151         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
83152         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
83153         // Arrow functions are lexically scoped to their container, but are new block scopes.
83154         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
83155         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
83156         // Constructors are both new lexical scopes and new block scopes. Constructors are also
83157         // always considered non-static members of a class.
83158         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
83159         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
83160         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
83161         // within an IterationStatement to indicate whether the embedded statement is an
83162         // IterationStatementBlock.
83163         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
83164         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
83165         // 'for' statements are new block scopes and have special handling for 'let' declarations.
83166         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
83167         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
83168         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
83169         // 'let' declarations.
83170         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
83171         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
83172         // Blocks (other than function bodies) are new block scopes.
83173         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
83174         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
83175         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
83176         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
83177         //
83178         // Subtree facts
83179         //
83180         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
83181         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
83182         //
83183         // Subtree masks
83184         //
83185         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
83186         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
83187         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
83188     })(HierarchyFacts || (HierarchyFacts = {}));
83189     function transformES2015(context) {
83190         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
83191         var compilerOptions = context.getCompilerOptions();
83192         var resolver = context.getEmitResolver();
83193         var previousOnSubstituteNode = context.onSubstituteNode;
83194         var previousOnEmitNode = context.onEmitNode;
83195         context.onEmitNode = onEmitNode;
83196         context.onSubstituteNode = onSubstituteNode;
83197         var currentSourceFile;
83198         var currentText;
83199         var hierarchyFacts;
83200         var taggedTemplateStringDeclarations;
83201         function recordTaggedTemplateString(temp) {
83202             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
83203         }
83204         /**
83205          * Used to track if we are emitting body of the converted loop
83206          */
83207         var convertedLoopState;
83208         /**
83209          * Keeps track of whether substitutions have been enabled for specific cases.
83210          * They are persisted between each SourceFile transformation and should not
83211          * be reset.
83212          */
83213         var enabledSubstitutions;
83214         return ts.chainBundle(transformSourceFile);
83215         function transformSourceFile(node) {
83216             if (node.isDeclarationFile) {
83217                 return node;
83218             }
83219             currentSourceFile = node;
83220             currentText = node.text;
83221             var visited = visitSourceFile(node);
83222             ts.addEmitHelpers(visited, context.readEmitHelpers());
83223             currentSourceFile = undefined;
83224             currentText = undefined;
83225             taggedTemplateStringDeclarations = undefined;
83226             hierarchyFacts = 0 /* None */;
83227             return visited;
83228         }
83229         /**
83230          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
83231          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
83232          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
83233          */
83234         function enterSubtree(excludeFacts, includeFacts) {
83235             var ancestorFacts = hierarchyFacts;
83236             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
83237             return ancestorFacts;
83238         }
83239         /**
83240          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
83241          * subtree, propagating specific facts from the subtree.
83242          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
83243          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
83244          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
83245          */
83246         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
83247             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
83248         }
83249         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
83250             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
83251                 && node.kind === 235 /* ReturnStatement */
83252                 && !node.expression;
83253         }
83254         function shouldVisitNode(node) {
83255             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
83256                 || convertedLoopState !== undefined
83257                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 223 /* Block */)))
83258                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
83259                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
83260         }
83261         function visitor(node) {
83262             if (shouldVisitNode(node)) {
83263                 return visitJavaScript(node);
83264             }
83265             else {
83266                 return node;
83267             }
83268         }
83269         function callExpressionVisitor(node) {
83270             if (node.kind === 102 /* SuperKeyword */) {
83271                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
83272             }
83273             return visitor(node);
83274         }
83275         function visitJavaScript(node) {
83276             switch (node.kind) {
83277                 case 120 /* StaticKeyword */:
83278                     return undefined; // elide static keyword
83279                 case 245 /* ClassDeclaration */:
83280                     return visitClassDeclaration(node);
83281                 case 214 /* ClassExpression */:
83282                     return visitClassExpression(node);
83283                 case 156 /* Parameter */:
83284                     return visitParameter(node);
83285                 case 244 /* FunctionDeclaration */:
83286                     return visitFunctionDeclaration(node);
83287                 case 202 /* ArrowFunction */:
83288                     return visitArrowFunction(node);
83289                 case 201 /* FunctionExpression */:
83290                     return visitFunctionExpression(node);
83291                 case 242 /* VariableDeclaration */:
83292                     return visitVariableDeclaration(node);
83293                 case 75 /* Identifier */:
83294                     return visitIdentifier(node);
83295                 case 243 /* VariableDeclarationList */:
83296                     return visitVariableDeclarationList(node);
83297                 case 237 /* SwitchStatement */:
83298                     return visitSwitchStatement(node);
83299                 case 251 /* CaseBlock */:
83300                     return visitCaseBlock(node);
83301                 case 223 /* Block */:
83302                     return visitBlock(node, /*isFunctionBody*/ false);
83303                 case 234 /* BreakStatement */:
83304                 case 233 /* ContinueStatement */:
83305                     return visitBreakOrContinueStatement(node);
83306                 case 238 /* LabeledStatement */:
83307                     return visitLabeledStatement(node);
83308                 case 228 /* DoStatement */:
83309                 case 229 /* WhileStatement */:
83310                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
83311                 case 230 /* ForStatement */:
83312                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
83313                 case 231 /* ForInStatement */:
83314                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
83315                 case 232 /* ForOfStatement */:
83316                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
83317                 case 226 /* ExpressionStatement */:
83318                     return visitExpressionStatement(node);
83319                 case 193 /* ObjectLiteralExpression */:
83320                     return visitObjectLiteralExpression(node);
83321                 case 280 /* CatchClause */:
83322                     return visitCatchClause(node);
83323                 case 282 /* ShorthandPropertyAssignment */:
83324                     return visitShorthandPropertyAssignment(node);
83325                 case 154 /* ComputedPropertyName */:
83326                     return visitComputedPropertyName(node);
83327                 case 192 /* ArrayLiteralExpression */:
83328                     return visitArrayLiteralExpression(node);
83329                 case 196 /* CallExpression */:
83330                     return visitCallExpression(node);
83331                 case 197 /* NewExpression */:
83332                     return visitNewExpression(node);
83333                 case 200 /* ParenthesizedExpression */:
83334                     return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
83335                 case 209 /* BinaryExpression */:
83336                     return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
83337                 case 14 /* NoSubstitutionTemplateLiteral */:
83338                 case 15 /* TemplateHead */:
83339                 case 16 /* TemplateMiddle */:
83340                 case 17 /* TemplateTail */:
83341                     return visitTemplateLiteral(node);
83342                 case 10 /* StringLiteral */:
83343                     return visitStringLiteral(node);
83344                 case 8 /* NumericLiteral */:
83345                     return visitNumericLiteral(node);
83346                 case 198 /* TaggedTemplateExpression */:
83347                     return visitTaggedTemplateExpression(node);
83348                 case 211 /* TemplateExpression */:
83349                     return visitTemplateExpression(node);
83350                 case 212 /* YieldExpression */:
83351                     return visitYieldExpression(node);
83352                 case 213 /* SpreadElement */:
83353                     return visitSpreadElement(node);
83354                 case 102 /* SuperKeyword */:
83355                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
83356                 case 104 /* ThisKeyword */:
83357                     return visitThisKeyword(node);
83358                 case 219 /* MetaProperty */:
83359                     return visitMetaProperty(node);
83360                 case 161 /* MethodDeclaration */:
83361                     return visitMethodDeclaration(node);
83362                 case 163 /* GetAccessor */:
83363                 case 164 /* SetAccessor */:
83364                     return visitAccessorDeclaration(node);
83365                 case 225 /* VariableStatement */:
83366                     return visitVariableStatement(node);
83367                 case 235 /* ReturnStatement */:
83368                     return visitReturnStatement(node);
83369                 default:
83370                     return ts.visitEachChild(node, visitor, context);
83371             }
83372         }
83373         function visitSourceFile(node) {
83374             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
83375             var prologue = [];
83376             var statements = [];
83377             startLexicalEnvironment();
83378             var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
83379             statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
83380             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
83381             if (taggedTemplateStringDeclarations) {
83382                 statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
83383             }
83384             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83385             insertCaptureThisForNodeIfNeeded(prologue, node);
83386             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83387             return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
83388         }
83389         function visitSwitchStatement(node) {
83390             if (convertedLoopState !== undefined) {
83391                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
83392                 // for switch statement allow only non-labeled break
83393                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
83394                 var result = ts.visitEachChild(node, visitor, context);
83395                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
83396                 return result;
83397             }
83398             return ts.visitEachChild(node, visitor, context);
83399         }
83400         function visitCaseBlock(node) {
83401             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
83402             var updated = ts.visitEachChild(node, visitor, context);
83403             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83404             return updated;
83405         }
83406         function returnCapturedThis(node) {
83407             return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
83408         }
83409         function visitReturnStatement(node) {
83410             if (convertedLoopState) {
83411                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
83412                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83413                     node = returnCapturedThis(node);
83414                 }
83415                 return ts.createReturn(ts.createObjectLiteral([
83416                     ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
83417                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
83418                         : ts.createVoidZero())
83419                 ]));
83420             }
83421             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83422                 return returnCapturedThis(node);
83423             }
83424             return ts.visitEachChild(node, visitor, context);
83425         }
83426         function visitThisKeyword(node) {
83427             if (hierarchyFacts & 2 /* ArrowFunction */) {
83428                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
83429             }
83430             if (convertedLoopState) {
83431                 if (hierarchyFacts & 2 /* ArrowFunction */) {
83432                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
83433                     convertedLoopState.containsLexicalThis = true;
83434                     return node;
83435                 }
83436                 return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
83437             }
83438             return node;
83439         }
83440         function visitIdentifier(node) {
83441             if (!convertedLoopState) {
83442                 return node;
83443             }
83444             if (ts.isGeneratedIdentifier(node)) {
83445                 return node;
83446             }
83447             if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
83448                 return node;
83449             }
83450             return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
83451         }
83452         function visitBreakOrContinueStatement(node) {
83453             if (convertedLoopState) {
83454                 // check if we can emit break/continue as is
83455                 // it is possible if either
83456                 //   - break/continue is labeled and label is located inside the converted loop
83457                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
83458                 var jump = node.kind === 234 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
83459                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
83460                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
83461                 if (!canUseBreakOrContinue) {
83462                     var labelMarker = void 0;
83463                     var label = node.label;
83464                     if (!label) {
83465                         if (node.kind === 234 /* BreakStatement */) {
83466                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
83467                             labelMarker = "break";
83468                         }
83469                         else {
83470                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
83471                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
83472                             labelMarker = "continue";
83473                         }
83474                     }
83475                     else {
83476                         if (node.kind === 234 /* BreakStatement */) {
83477                             labelMarker = "break-" + label.escapedText;
83478                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
83479                         }
83480                         else {
83481                             labelMarker = "continue-" + label.escapedText;
83482                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
83483                         }
83484                     }
83485                     var returnExpression = ts.createLiteral(labelMarker);
83486                     if (convertedLoopState.loopOutParameters.length) {
83487                         var outParams = convertedLoopState.loopOutParameters;
83488                         var expr = void 0;
83489                         for (var i = 0; i < outParams.length; i++) {
83490                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
83491                             if (i === 0) {
83492                                 expr = copyExpr;
83493                             }
83494                             else {
83495                                 expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr);
83496                             }
83497                         }
83498                         returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression);
83499                     }
83500                     return ts.createReturn(returnExpression);
83501                 }
83502             }
83503             return ts.visitEachChild(node, visitor, context);
83504         }
83505         /**
83506          * Visits a ClassDeclaration and transforms it into a variable statement.
83507          *
83508          * @param node A ClassDeclaration node.
83509          */
83510         function visitClassDeclaration(node) {
83511             // [source]
83512             //      class C { }
83513             //
83514             // [output]
83515             //      var C = (function () {
83516             //          function C() {
83517             //          }
83518             //          return C;
83519             //      }());
83520             var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), 
83521             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
83522             ts.setOriginalNode(variable, node);
83523             var statements = [];
83524             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
83525             ts.setOriginalNode(statement, node);
83526             ts.setTextRange(statement, node);
83527             ts.startOnNewLine(statement);
83528             statements.push(statement);
83529             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
83530             if (ts.hasModifier(node, 1 /* Export */)) {
83531                 var exportStatement = ts.hasModifier(node, 512 /* Default */)
83532                     ? ts.createExportDefault(ts.getLocalName(node))
83533                     : ts.createExternalModuleExport(ts.getLocalName(node));
83534                 ts.setOriginalNode(exportStatement, statement);
83535                 statements.push(exportStatement);
83536             }
83537             var emitFlags = ts.getEmitFlags(node);
83538             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
83539                 // Add a DeclarationMarker as a marker for the end of the declaration
83540                 statements.push(ts.createEndOfDeclarationMarker(node));
83541                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
83542             }
83543             return ts.singleOrMany(statements);
83544         }
83545         /**
83546          * Visits a ClassExpression and transforms it into an expression.
83547          *
83548          * @param node A ClassExpression node.
83549          */
83550         function visitClassExpression(node) {
83551             // [source]
83552             //      C = class { }
83553             //
83554             // [output]
83555             //      C = (function () {
83556             //          function class_1() {
83557             //          }
83558             //          return class_1;
83559             //      }())
83560             return transformClassLikeDeclarationToExpression(node);
83561         }
83562         /**
83563          * Transforms a ClassExpression or ClassDeclaration into an expression.
83564          *
83565          * @param node A ClassExpression or ClassDeclaration node.
83566          */
83567         function transformClassLikeDeclarationToExpression(node) {
83568             // [source]
83569             //      class C extends D {
83570             //          constructor() {}
83571             //          method() {}
83572             //          get prop() {}
83573             //          set prop(v) {}
83574             //      }
83575             //
83576             // [output]
83577             //      (function (_super) {
83578             //          __extends(C, _super);
83579             //          function C() {
83580             //          }
83581             //          C.prototype.method = function () {}
83582             //          Object.defineProperty(C.prototype, "prop", {
83583             //              get: function() {},
83584             //              set: function() {},
83585             //              enumerable: true,
83586             //              configurable: true
83587             //          });
83588             //          return C;
83589             //      }(D))
83590             if (node.name) {
83591                 enableSubstitutionsForBlockScopedBindings();
83592             }
83593             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
83594             var classFunction = ts.createFunctionExpression(
83595             /*modifiers*/ undefined, 
83596             /*asteriskToken*/ undefined, 
83597             /*name*/ undefined, 
83598             /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], 
83599             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
83600             // To preserve the behavior of the old emitter, we explicitly indent
83601             // the body of the function here if it was requested in an earlier
83602             // transformation.
83603             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
83604             // "inner" and "outer" below are added purely to preserve source map locations from
83605             // the old emitter
83606             var inner = ts.createPartiallyEmittedExpression(classFunction);
83607             inner.end = node.end;
83608             ts.setEmitFlags(inner, 1536 /* NoComments */);
83609             var outer = ts.createPartiallyEmittedExpression(inner);
83610             outer.end = ts.skipTrivia(currentText, node.pos);
83611             ts.setEmitFlags(outer, 1536 /* NoComments */);
83612             var result = ts.createParen(ts.createCall(outer, 
83613             /*typeArguments*/ undefined, extendsClauseElement
83614                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
83615                 : []));
83616             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
83617             return result;
83618         }
83619         /**
83620          * Transforms a ClassExpression or ClassDeclaration into a function body.
83621          *
83622          * @param node A ClassExpression or ClassDeclaration node.
83623          * @param extendsClauseElement The expression for the class `extends` clause.
83624          */
83625         function transformClassBody(node, extendsClauseElement) {
83626             var statements = [];
83627             startLexicalEnvironment();
83628             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
83629             addConstructor(statements, node, extendsClauseElement);
83630             addClassMembers(statements, node);
83631             // Create a synthetic text range for the return statement.
83632             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
83633             var localName = ts.getInternalName(node);
83634             // The following partially-emitted expression exists purely to align our sourcemap
83635             // emit with the original emitter.
83636             var outer = ts.createPartiallyEmittedExpression(localName);
83637             outer.end = closingBraceLocation.end;
83638             ts.setEmitFlags(outer, 1536 /* NoComments */);
83639             var statement = ts.createReturn(outer);
83640             statement.pos = closingBraceLocation.pos;
83641             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
83642             statements.push(statement);
83643             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
83644             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
83645             ts.setEmitFlags(block, 1536 /* NoComments */);
83646             return block;
83647         }
83648         /**
83649          * Adds a call to the `__extends` helper if needed for a class.
83650          *
83651          * @param statements The statements of the class body function.
83652          * @param node The ClassExpression or ClassDeclaration node.
83653          * @param extendsClauseElement The expression for the class `extends` clause.
83654          */
83655         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
83656             if (extendsClauseElement) {
83657                 statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), 
83658                 /*location*/ extendsClauseElement));
83659             }
83660         }
83661         /**
83662          * Adds the constructor of the class to a class body function.
83663          *
83664          * @param statements The statements of the class body function.
83665          * @param node The ClassExpression or ClassDeclaration node.
83666          * @param extendsClauseElement The expression for the class `extends` clause.
83667          */
83668         function addConstructor(statements, node, extendsClauseElement) {
83669             var savedConvertedLoopState = convertedLoopState;
83670             convertedLoopState = undefined;
83671             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
83672             var constructor = ts.getFirstConstructorWithBody(node);
83673             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
83674             var constructorFunction = ts.createFunctionDeclaration(
83675             /*decorators*/ undefined, 
83676             /*modifiers*/ undefined, 
83677             /*asteriskToken*/ undefined, ts.getInternalName(node), 
83678             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
83679             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
83680             ts.setTextRange(constructorFunction, constructor || node);
83681             if (extendsClauseElement) {
83682                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
83683             }
83684             statements.push(constructorFunction);
83685             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
83686             convertedLoopState = savedConvertedLoopState;
83687         }
83688         /**
83689          * Transforms the parameters of the constructor declaration of a class.
83690          *
83691          * @param constructor The constructor for the class.
83692          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83693          *                            synthesized `super` call.
83694          */
83695         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
83696             // If the TypeScript transformer needed to synthesize a constructor for property
83697             // initializers, it would have also added a synthetic `...args` parameter and
83698             // `super` call.
83699             // If this is the case, we do not include the synthetic `...args` parameter and
83700             // will instead use the `arguments` object in ES5/3.
83701             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
83702                 || [];
83703         }
83704         function createDefaultConstructorBody(node, isDerivedClass) {
83705             // We must be here because the user didn't write a constructor
83706             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
83707             // If that's the case we can just immediately return the result of a 'super()' call.
83708             var statements = [];
83709             resumeLexicalEnvironment();
83710             ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83711             if (isDerivedClass) {
83712                 // return _super !== null && _super.apply(this, arguments) || this;
83713                 statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
83714             }
83715             var statementsArray = ts.createNodeArray(statements);
83716             ts.setTextRange(statementsArray, node.members);
83717             var block = ts.createBlock(statementsArray, /*multiLine*/ true);
83718             ts.setTextRange(block, node);
83719             ts.setEmitFlags(block, 1536 /* NoComments */);
83720             return block;
83721         }
83722         /**
83723          * Transforms the body of a constructor declaration of a class.
83724          *
83725          * @param constructor The constructor for the class.
83726          * @param node The node which contains the constructor.
83727          * @param extendsClauseElement The expression for the class `extends` clause.
83728          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83729          *                            synthesized `super` call.
83730          */
83731         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
83732             // determine whether the class is known syntactically to be a derived class (e.g. a
83733             // class that extends a value that is not syntactically known to be `null`).
83734             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */;
83735             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
83736             // representation:
83737             //
83738             // ```
83739             // // es2015 (source)
83740             // class C extends Base { }
83741             //
83742             // // es5 (transformed)
83743             // var C = (function (_super) {
83744             //     function C() {
83745             //         return _super.apply(this, arguments) || this;
83746             //     }
83747             //     return C;
83748             // })(Base);
83749             // ```
83750             if (!constructor)
83751                 return createDefaultConstructorBody(node, isDerivedClass);
83752             // The prologue will contain all leading standard and custom prologue statements added by this transform
83753             var prologue = [];
83754             var statements = [];
83755             resumeLexicalEnvironment();
83756             // If a super call has already been synthesized,
83757             // we're going to assume that we should just transform everything after that.
83758             // The assumption is that no prior step in the pipeline has added any prologue directives.
83759             var statementOffset = 0;
83760             if (!hasSynthesizedSuper)
83761                 statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
83762             addDefaultValueAssignmentsIfNeeded(statements, constructor);
83763             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
83764             if (!hasSynthesizedSuper)
83765                 statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
83766             // If the first statement is a call to `super()`, visit the statement directly
83767             var superCallExpression;
83768             if (hasSynthesizedSuper) {
83769                 superCallExpression = createDefaultSuperCallOrThis();
83770             }
83771             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
83772                 var firstStatement = constructor.body.statements[statementOffset];
83773                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
83774                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
83775                 }
83776             }
83777             if (superCallExpression) {
83778                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
83779                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
83780             }
83781             // visit the remaining statements
83782             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
83783             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83784             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
83785             if (isDerivedClass) {
83786                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
83787                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
83788                     // following representation:
83789                     //
83790                     // ```
83791                     // // es2015 (source)
83792                     // class C extends Base {
83793                     //     constructor() {
83794                     //         super("foo");
83795                     //     }
83796                     // }
83797                     //
83798                     // // es5 (transformed)
83799                     // var C = (function (_super) {
83800                     //     function C() {
83801                     //         return _super.call(this, "foo") || this;
83802                     //     }
83803                     //     return C;
83804                     // })(Base);
83805                     // ```
83806                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
83807                     var returnStatement = ts.createReturn(superCallExpression);
83808                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
83809                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
83810                     statements.push(returnStatement);
83811                 }
83812                 else {
83813                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
83814                     //
83815                     // ```
83816                     // // es2015 (source)
83817                     // class C extends Base {
83818                     //     constructor() {
83819                     //         super("foo");
83820                     //         this.x = 1;
83821                     //     }
83822                     // }
83823                     //
83824                     // // es5 (transformed)
83825                     // var C = (function (_super) {
83826                     //     function C() {
83827                     //         var _this = _super.call(this, "foo") || this;
83828                     //         _this.x = 1;
83829                     //         return _this;
83830                     //     }
83831                     //     return C;
83832                     // })(Base);
83833                     // ```
83834                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
83835                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
83836                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
83837                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
83838                         statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
83839                     }
83840                 }
83841             }
83842             else {
83843                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
83844                 // captured when necessitated by an arrow function capturing the lexical `this`:
83845                 //
83846                 // ```
83847                 // // es2015
83848                 // class C {}
83849                 //
83850                 // // es5
83851                 // var C = (function () {
83852                 //     function C() {
83853                 //     }
83854                 //     return C;
83855                 // })();
83856                 // ```
83857                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
83858             }
83859             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), 
83860             /*location*/ constructor.body.statements), 
83861             /*multiLine*/ true);
83862             ts.setTextRange(block, constructor.body);
83863             return block;
83864         }
83865         /**
83866          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
83867          * It would generate obviously dead code, so we'll try to make things a little bit prettier
83868          * by doing a minimal check on whether some common patterns always explicitly return.
83869          */
83870         function isSufficientlyCoveredByReturnStatements(statement) {
83871             // A return statement is considered covered.
83872             if (statement.kind === 235 /* ReturnStatement */) {
83873                 return true;
83874             }
83875             // An if-statement with two covered branches is covered.
83876             else if (statement.kind === 227 /* IfStatement */) {
83877                 var ifStatement = statement;
83878                 if (ifStatement.elseStatement) {
83879                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
83880                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
83881                 }
83882             }
83883             // A block is covered if it has a last statement which is covered.
83884             else if (statement.kind === 223 /* Block */) {
83885                 var lastStatement = ts.lastOrUndefined(statement.statements);
83886                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
83887                     return true;
83888                 }
83889             }
83890             return false;
83891         }
83892         function createActualThis() {
83893             return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
83894         }
83895         function createDefaultSuperCallOrThis() {
83896             return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
83897         }
83898         /**
83899          * Visits a parameter declaration.
83900          *
83901          * @param node A ParameterDeclaration node.
83902          */
83903         function visitParameter(node) {
83904             if (node.dotDotDotToken) {
83905                 // rest parameters are elided
83906                 return undefined;
83907             }
83908             else if (ts.isBindingPattern(node.name)) {
83909                 // Binding patterns are converted into a generated name and are
83910                 // evaluated inside the function body.
83911                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83912                 /*decorators*/ undefined, 
83913                 /*modifiers*/ undefined, 
83914                 /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), 
83915                 /*questionToken*/ undefined, 
83916                 /*type*/ undefined, 
83917                 /*initializer*/ undefined), 
83918                 /*location*/ node), 
83919                 /*original*/ node);
83920             }
83921             else if (node.initializer) {
83922                 // Initializers are elided
83923                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83924                 /*decorators*/ undefined, 
83925                 /*modifiers*/ undefined, 
83926                 /*dotDotDotToken*/ undefined, node.name, 
83927                 /*questionToken*/ undefined, 
83928                 /*type*/ undefined, 
83929                 /*initializer*/ undefined), 
83930                 /*location*/ node), 
83931                 /*original*/ node);
83932             }
83933             else {
83934                 return node;
83935             }
83936         }
83937         function hasDefaultValueOrBindingPattern(node) {
83938             return node.initializer !== undefined
83939                 || ts.isBindingPattern(node.name);
83940         }
83941         /**
83942          * Adds statements to the body of a function-like node if it contains parameters with
83943          * binding patterns or initializers.
83944          *
83945          * @param statements The statements for the new function body.
83946          * @param node A function-like node.
83947          */
83948         function addDefaultValueAssignmentsIfNeeded(statements, node) {
83949             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
83950                 return false;
83951             }
83952             var added = false;
83953             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
83954                 var parameter = _a[_i];
83955                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
83956                 // A rest parameter cannot have a binding pattern or an initializer,
83957                 // so let's just ignore it.
83958                 if (dotDotDotToken) {
83959                     continue;
83960                 }
83961                 if (ts.isBindingPattern(name)) {
83962                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
83963                 }
83964                 else if (initializer) {
83965                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
83966                     added = true;
83967                 }
83968             }
83969             return added;
83970         }
83971         /**
83972          * Adds statements to the body of a function-like node for parameters with binding patterns
83973          *
83974          * @param statements The statements for the new function body.
83975          * @param parameter The parameter for the function.
83976          * @param name The name of the parameter.
83977          * @param initializer The initializer for the parameter.
83978          */
83979         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
83980             // In cases where a binding pattern is simply '[]' or '{}',
83981             // we usually don't want to emit a var declaration; however, in the presence
83982             // of an initializer, we must emit that expression to preserve side effects.
83983             if (name.elements.length > 0) {
83984                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
83985                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
83986                 return true;
83987             }
83988             else if (initializer) {
83989                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
83990                 return true;
83991             }
83992             return false;
83993         }
83994         /**
83995          * Adds statements to the body of a function-like node for parameters with initializers.
83996          *
83997          * @param statements The statements for the new function body.
83998          * @param parameter The parameter for the function.
83999          * @param name The name of the parameter.
84000          * @param initializer The initializer for the parameter.
84001          */
84002         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
84003             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
84004             var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
84005                 ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
84006             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
84007             ts.startOnNewLine(statement);
84008             ts.setTextRange(statement, parameter);
84009             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
84010             ts.insertStatementAfterCustomPrologue(statements, statement);
84011         }
84012         /**
84013          * Gets a value indicating whether we need to add statements to handle a rest parameter.
84014          *
84015          * @param node A ParameterDeclaration node.
84016          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84017          *                                          part of a constructor declaration with a
84018          *                                          synthesized call to `super`
84019          */
84020         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
84021             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
84022         }
84023         /**
84024          * Adds statements to the body of a function-like node if it contains a rest parameter.
84025          *
84026          * @param statements The statements for the new function body.
84027          * @param node A function-like node.
84028          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84029          *                                          part of a constructor declaration with a
84030          *                                          synthesized call to `super`
84031          */
84032         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
84033             var prologueStatements = [];
84034             var parameter = ts.lastOrUndefined(node.parameters);
84035             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
84036                 return false;
84037             }
84038             // `declarationName` is the name of the local declaration for the parameter.
84039             var declarationName = parameter.name.kind === 75 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84040             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
84041             // `expressionName` is the name of the parameter used in expressions.
84042             var expressionName = parameter.name.kind === 75 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName;
84043             var restIndex = node.parameters.length - 1;
84044             var temp = ts.createLoopVariable();
84045             // var param = [];
84046             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84047             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84048                 ts.createVariableDeclaration(declarationName, 
84049                 /*type*/ undefined, ts.createArrayLiteral([]))
84050             ])), 
84051             /*location*/ parameter), 1048576 /* CustomPrologue */));
84052             // for (var _i = restIndex; _i < arguments.length; _i++) {
84053             //   param[_i - restIndex] = arguments[_i];
84054             // }
84055             var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
84056                 ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
84057             ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
84058                 ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
84059                     ? temp
84060                     : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), 
84061                 /*location*/ parameter))
84062             ]));
84063             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
84064             ts.startOnNewLine(forStatement);
84065             prologueStatements.push(forStatement);
84066             if (parameter.name.kind !== 75 /* Identifier */) {
84067                 // do the actual destructuring of the rest parameter if necessary
84068                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84069                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
84070             }
84071             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
84072             return true;
84073         }
84074         /**
84075          * Adds a statement to capture the `this` of a function declaration if it is needed.
84076          * NOTE: This must be executed *after* the subtree has been visited.
84077          *
84078          * @param statements The statements for the new function body.
84079          * @param node A node.
84080          */
84081         function insertCaptureThisForNodeIfNeeded(statements, node) {
84082             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 202 /* ArrowFunction */) {
84083                 insertCaptureThisForNode(statements, node, ts.createThis());
84084                 return true;
84085             }
84086             return false;
84087         }
84088         function insertCaptureThisForNode(statements, node, initializer) {
84089             enableSubstitutionsForCapturedThis();
84090             var captureThisStatement = ts.createVariableStatement(
84091             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84092                 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), 
84093                 /*type*/ undefined, initializer)
84094             ]));
84095             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84096             ts.setSourceMapRange(captureThisStatement, node);
84097             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
84098         }
84099         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
84100             if (hierarchyFacts & 16384 /* NewTarget */) {
84101                 var newTarget = void 0;
84102                 switch (node.kind) {
84103                     case 202 /* ArrowFunction */:
84104                         return statements;
84105                     case 161 /* MethodDeclaration */:
84106                     case 163 /* GetAccessor */:
84107                     case 164 /* SetAccessor */:
84108                         // Methods and accessors cannot be constructors, so 'new.target' will
84109                         // always return 'undefined'.
84110                         newTarget = ts.createVoidZero();
84111                         break;
84112                     case 162 /* Constructor */:
84113                         // Class constructors can only be called with `new`, so `this.constructor`
84114                         // should be relatively safe to use.
84115                         newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
84116                         break;
84117                     case 244 /* FunctionDeclaration */:
84118                     case 201 /* FunctionExpression */:
84119                         // Functions can be called or constructed, and may have a `this` due to
84120                         // being a member or when calling an imported function via `other_1.f()`.
84121                         newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 98 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero());
84122                         break;
84123                     default:
84124                         return ts.Debug.failBadSyntaxKind(node);
84125                 }
84126                 var captureNewTargetStatement = ts.createVariableStatement(
84127                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
84128                     ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), 
84129                     /*type*/ undefined, newTarget)
84130                 ]));
84131                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84132                 if (copyOnWrite) {
84133                     statements = statements.slice();
84134                 }
84135                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
84136             }
84137             return statements;
84138         }
84139         /**
84140          * Adds statements to the class body function for a class to define the members of the
84141          * class.
84142          *
84143          * @param statements The statements for the class body function.
84144          * @param node The ClassExpression or ClassDeclaration node.
84145          */
84146         function addClassMembers(statements, node) {
84147             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
84148                 var member = _a[_i];
84149                 switch (member.kind) {
84150                     case 222 /* SemicolonClassElement */:
84151                         statements.push(transformSemicolonClassElementToStatement(member));
84152                         break;
84153                     case 161 /* MethodDeclaration */:
84154                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
84155                         break;
84156                     case 163 /* GetAccessor */:
84157                     case 164 /* SetAccessor */:
84158                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
84159                         if (member === accessors.firstAccessor) {
84160                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
84161                         }
84162                         break;
84163                     case 162 /* Constructor */:
84164                         // Constructors are handled in visitClassExpression/visitClassDeclaration
84165                         break;
84166                     default:
84167                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
84168                         break;
84169                 }
84170             }
84171         }
84172         /**
84173          * Transforms a SemicolonClassElement into a statement for a class body function.
84174          *
84175          * @param member The SemicolonClassElement node.
84176          */
84177         function transformSemicolonClassElementToStatement(member) {
84178             return ts.setTextRange(ts.createEmptyStatement(), member);
84179         }
84180         /**
84181          * Transforms a MethodDeclaration into a statement for a class body function.
84182          *
84183          * @param receiver The receiver for the member.
84184          * @param member The MethodDeclaration node.
84185          */
84186         function transformClassMethodDeclarationToStatement(receiver, member, container) {
84187             var commentRange = ts.getCommentRange(member);
84188             var sourceMapRange = ts.getSourceMapRange(member);
84189             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
84190             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
84191             var e;
84192             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
84193                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
84194                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
84195                         : propertyName;
84196                 e = ts.createObjectDefinePropertyCall(receiver, name, ts.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
84197             }
84198             else {
84199                 var memberName = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ member.name);
84200                 e = ts.createAssignment(memberName, memberFunction);
84201             }
84202             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
84203             ts.setSourceMapRange(memberFunction, sourceMapRange);
84204             var statement = ts.setTextRange(ts.createExpressionStatement(e), /*location*/ member);
84205             ts.setOriginalNode(statement, member);
84206             ts.setCommentRange(statement, commentRange);
84207             // The location for the statement is used to emit comments only.
84208             // No source map should be emitted for this statement to align with the
84209             // old emitter.
84210             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
84211             return statement;
84212         }
84213         /**
84214          * Transforms a set of related of get/set accessors into a statement for a class body function.
84215          *
84216          * @param receiver The receiver for the member.
84217          * @param accessors The set of related get/set accessors.
84218          */
84219         function transformAccessorsToStatement(receiver, accessors, container) {
84220             var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
84221             // The location for the statement is used to emit source maps only.
84222             // No comments should be emitted for this statement to align with the
84223             // old emitter.
84224             ts.setEmitFlags(statement, 1536 /* NoComments */);
84225             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
84226             return statement;
84227         }
84228         /**
84229          * Transforms a set of related get/set accessors into an expression for either a class
84230          * body function or an ObjectLiteralExpression with computed properties.
84231          *
84232          * @param receiver The receiver for the member.
84233          */
84234         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
84235             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
84236             // To align with source maps in the old emitter, the receiver and property name
84237             // arguments are both mapped contiguously to the accessor name.
84238             var target = ts.getMutableClone(receiver);
84239             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
84240             ts.setSourceMapRange(target, firstAccessor.name);
84241             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
84242             if (ts.isPrivateIdentifier(visitedAccessorName)) {
84243                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
84244             }
84245             var propertyName = ts.createExpressionForPropertyName(visitedAccessorName);
84246             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
84247             ts.setSourceMapRange(propertyName, firstAccessor.name);
84248             var properties = [];
84249             if (getAccessor) {
84250                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
84251                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
84252                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
84253                 var getter = ts.createPropertyAssignment("get", getterFunction);
84254                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
84255                 properties.push(getter);
84256             }
84257             if (setAccessor) {
84258                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
84259                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
84260                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
84261                 var setter = ts.createPropertyAssignment("set", setterFunction);
84262                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
84263                 properties.push(setter);
84264             }
84265             properties.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
84266             var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
84267             /*typeArguments*/ undefined, [
84268                 target,
84269                 propertyName,
84270                 ts.createObjectLiteral(properties, /*multiLine*/ true)
84271             ]);
84272             if (startsOnNewLine) {
84273                 ts.startOnNewLine(call);
84274             }
84275             return call;
84276         }
84277         /**
84278          * Visits an ArrowFunction and transforms it into a FunctionExpression.
84279          *
84280          * @param node An ArrowFunction node.
84281          */
84282         function visitArrowFunction(node) {
84283             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
84284                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
84285             }
84286             var savedConvertedLoopState = convertedLoopState;
84287             convertedLoopState = undefined;
84288             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
84289             var func = ts.createFunctionExpression(
84290             /*modifiers*/ undefined, 
84291             /*asteriskToken*/ undefined, 
84292             /*name*/ undefined, 
84293             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84294             /*type*/ undefined, transformFunctionBody(node));
84295             ts.setTextRange(func, node);
84296             ts.setOriginalNode(func, node);
84297             ts.setEmitFlags(func, 8 /* CapturesThis */);
84298             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
84299                 enableSubstitutionsForCapturedThis();
84300             }
84301             // If an arrow function contains
84302             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
84303             convertedLoopState = savedConvertedLoopState;
84304             return func;
84305         }
84306         /**
84307          * Visits a FunctionExpression node.
84308          *
84309          * @param node a FunctionExpression node.
84310          */
84311         function visitFunctionExpression(node) {
84312             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
84313                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
84314                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84315             var savedConvertedLoopState = convertedLoopState;
84316             convertedLoopState = undefined;
84317             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84318             var body = transformFunctionBody(node);
84319             var name = hierarchyFacts & 16384 /* NewTarget */
84320                 ? ts.getLocalName(node)
84321                 : node.name;
84322             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84323             convertedLoopState = savedConvertedLoopState;
84324             return ts.updateFunctionExpression(node, 
84325             /*modifiers*/ undefined, node.asteriskToken, name, 
84326             /*typeParameters*/ undefined, parameters, 
84327             /*type*/ undefined, body);
84328         }
84329         /**
84330          * Visits a FunctionDeclaration node.
84331          *
84332          * @param node a FunctionDeclaration node.
84333          */
84334         function visitFunctionDeclaration(node) {
84335             var savedConvertedLoopState = convertedLoopState;
84336             convertedLoopState = undefined;
84337             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84338             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84339             var body = transformFunctionBody(node);
84340             var name = hierarchyFacts & 16384 /* NewTarget */
84341                 ? ts.getLocalName(node)
84342                 : node.name;
84343             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84344             convertedLoopState = savedConvertedLoopState;
84345             return ts.updateFunctionDeclaration(node, 
84346             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
84347             /*typeParameters*/ undefined, parameters, 
84348             /*type*/ undefined, body);
84349         }
84350         /**
84351          * Transforms a function-like node into a FunctionExpression.
84352          *
84353          * @param node The function-like node to transform.
84354          * @param location The source-map location for the new FunctionExpression.
84355          * @param name The name of the new FunctionExpression.
84356          */
84357         function transformFunctionLikeToExpression(node, location, name, container) {
84358             var savedConvertedLoopState = convertedLoopState;
84359             convertedLoopState = undefined;
84360             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
84361                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
84362                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84363             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84364             var body = transformFunctionBody(node);
84365             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) {
84366                 name = ts.getGeneratedNameForNode(node);
84367             }
84368             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84369             convertedLoopState = savedConvertedLoopState;
84370             return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
84371             /*modifiers*/ undefined, node.asteriskToken, name, 
84372             /*typeParameters*/ undefined, parameters, 
84373             /*type*/ undefined, body), location), 
84374             /*original*/ node);
84375         }
84376         /**
84377          * Transforms the body of a function-like node.
84378          *
84379          * @param node A function-like node.
84380          */
84381         function transformFunctionBody(node) {
84382             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
84383             var singleLine = false; // indicates whether the block *may* be emitted as a single line
84384             var statementsLocation;
84385             var closeBraceLocation;
84386             var prologue = [];
84387             var statements = [];
84388             var body = node.body;
84389             var statementOffset;
84390             resumeLexicalEnvironment();
84391             if (ts.isBlock(body)) {
84392                 // ensureUseStrict is false because no new prologue-directive should be added.
84393                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
84394                 statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
84395                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction);
84396                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement);
84397             }
84398             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
84399             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
84400             if (ts.isBlock(body)) {
84401                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
84402                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
84403                 statementsLocation = body.statements;
84404                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
84405                 // If the original body was a multi-line block, this must be a multi-line block.
84406                 if (!multiLine && body.multiLine) {
84407                     multiLine = true;
84408                 }
84409             }
84410             else {
84411                 ts.Debug.assert(node.kind === 202 /* ArrowFunction */);
84412                 // To align with the old emitter, we use a synthetic end position on the location
84413                 // for the statement list we synthesize when we down-level an arrow function with
84414                 // an expression function body. This prevents both comments and source maps from
84415                 // being emitted for the end position only.
84416                 statementsLocation = ts.moveRangeEnd(body, -1);
84417                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
84418                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
84419                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
84420                         singleLine = true;
84421                     }
84422                     else {
84423                         multiLine = true;
84424                     }
84425                 }
84426                 var expression = ts.visitNode(body, visitor, ts.isExpression);
84427                 var returnStatement = ts.createReturn(expression);
84428                 ts.setTextRange(returnStatement, body);
84429                 ts.moveSyntheticComments(returnStatement, body);
84430                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
84431                 statements.push(returnStatement);
84432                 // To align with the source map emit for the old emitter, we set a custom
84433                 // source map location for the close brace.
84434                 closeBraceLocation = body;
84435             }
84436             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
84437             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
84438             insertCaptureThisForNodeIfNeeded(prologue, node);
84439             // If we added any final generated statements, this must be a multi-line block
84440             if (ts.some(prologue)) {
84441                 multiLine = true;
84442             }
84443             statements.unshift.apply(statements, prologue);
84444             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
84445                 // no changes were made, preserve the tree
84446                 return body;
84447             }
84448             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
84449             ts.setTextRange(block, node.body);
84450             if (!multiLine && singleLine) {
84451                 ts.setEmitFlags(block, 1 /* SingleLine */);
84452             }
84453             if (closeBraceLocation) {
84454                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
84455             }
84456             ts.setOriginalNode(block, node.body);
84457             return block;
84458         }
84459         function visitBlock(node, isFunctionBody) {
84460             if (isFunctionBody) {
84461                 // A function body is not a block scope.
84462                 return ts.visitEachChild(node, visitor, context);
84463             }
84464             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
84465                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
84466                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
84467             var updated = ts.visitEachChild(node, visitor, context);
84468             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84469             return updated;
84470         }
84471         /**
84472          * Visits an ExpressionStatement that contains a destructuring assignment.
84473          *
84474          * @param node An ExpressionStatement node.
84475          */
84476         function visitExpressionStatement(node) {
84477             // If we are here it is most likely because our expression is a destructuring assignment.
84478             switch (node.expression.kind) {
84479                 case 200 /* ParenthesizedExpression */:
84480                     return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84481                 case 209 /* BinaryExpression */:
84482                     return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84483             }
84484             return ts.visitEachChild(node, visitor, context);
84485         }
84486         /**
84487          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
84488          *
84489          * @param node A ParenthesizedExpression node.
84490          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84491          *                                of a destructuring assignment.
84492          */
84493         function visitParenthesizedExpression(node, needsDestructuringValue) {
84494             // If we are here it is most likely because our expression is a destructuring assignment.
84495             if (!needsDestructuringValue) {
84496                 // By default we always emit the RHS at the end of a flattened destructuring
84497                 // expression. If we are in a state where we do not need the destructuring value,
84498                 // we pass that information along to the children that care about it.
84499                 switch (node.expression.kind) {
84500                     case 200 /* ParenthesizedExpression */:
84501                         return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84502                     case 209 /* BinaryExpression */:
84503                         return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84504                 }
84505             }
84506             return ts.visitEachChild(node, visitor, context);
84507         }
84508         /**
84509          * Visits a BinaryExpression that contains a destructuring assignment.
84510          *
84511          * @param node A BinaryExpression node.
84512          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84513          *                                of a destructuring assignment.
84514          */
84515         function visitBinaryExpression(node, needsDestructuringValue) {
84516             // If we are here it is because this is a destructuring assignment.
84517             if (ts.isDestructuringAssignment(node)) {
84518                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
84519             }
84520             return ts.visitEachChild(node, visitor, context);
84521         }
84522         function isVariableStatementOfTypeScriptClassWrapper(node) {
84523             return node.declarationList.declarations.length === 1
84524                 && !!node.declarationList.declarations[0].initializer
84525                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
84526         }
84527         function visitVariableStatement(node) {
84528             var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
84529             var updated;
84530             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
84531                 // we are inside a converted loop - hoist variable declarations
84532                 var assignments = void 0;
84533                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
84534                     var decl = _a[_i];
84535                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
84536                     if (decl.initializer) {
84537                         var assignment = void 0;
84538                         if (ts.isBindingPattern(decl.name)) {
84539                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
84540                         }
84541                         else {
84542                             assignment = ts.createBinary(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
84543                             ts.setTextRange(assignment, decl);
84544                         }
84545                         assignments = ts.append(assignments, assignment);
84546                     }
84547                 }
84548                 if (assignments) {
84549                     updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
84550                 }
84551                 else {
84552                     // none of declarations has initializer - the entire variable statement can be deleted
84553                     updated = undefined;
84554                 }
84555             }
84556             else {
84557                 updated = ts.visitEachChild(node, visitor, context);
84558             }
84559             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84560             return updated;
84561         }
84562         /**
84563          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
84564          *
84565          * @param node A VariableDeclarationList node.
84566          */
84567         function visitVariableDeclarationList(node) {
84568             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
84569                 if (node.flags & 3 /* BlockScoped */) {
84570                     enableSubstitutionsForBlockScopedBindings();
84571                 }
84572                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
84573                     ? visitVariableDeclarationInLetDeclarationList
84574                     : visitVariableDeclaration);
84575                 var declarationList = ts.createVariableDeclarationList(declarations);
84576                 ts.setOriginalNode(declarationList, node);
84577                 ts.setTextRange(declarationList, node);
84578                 ts.setCommentRange(declarationList, node);
84579                 // If the first or last declaration is a binding pattern, we need to modify
84580                 // the source map range for the declaration list.
84581                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
84582                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
84583                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
84584                 }
84585                 return declarationList;
84586             }
84587             return ts.visitEachChild(node, visitor, context);
84588         }
84589         function getRangeUnion(declarations) {
84590             // declarations may not be sorted by position.
84591             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
84592             var pos = -1, end = -1;
84593             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
84594                 var node = declarations_10[_i];
84595                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
84596                 end = Math.max(end, node.end);
84597             }
84598             return ts.createRange(pos, end);
84599         }
84600         /**
84601          * Gets a value indicating whether we should emit an explicit initializer for a variable
84602          * declaration in a `let` declaration list.
84603          *
84604          * @param node A VariableDeclaration node.
84605          */
84606         function shouldEmitExplicitInitializerForLetDeclaration(node) {
84607             // Nested let bindings might need to be initialized explicitly to preserve
84608             // ES6 semantic:
84609             //
84610             //  { let x = 1; }
84611             //  { let x; } // x here should be undefined. not 1
84612             //
84613             // Top level bindings never collide with anything and thus don't require
84614             // explicit initialization. As for nested let bindings there are two cases:
84615             //
84616             // - Nested let bindings that were not renamed definitely should be
84617             //   initialized explicitly:
84618             //
84619             //    { let x = 1; }
84620             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
84621             //
84622             //   Without explicit initialization code in /*1*/ can be executed even if
84623             //   some-condition is evaluated to false.
84624             //
84625             // - Renaming introduces fresh name that should not collide with any
84626             //   existing names, however renamed bindings sometimes also should be
84627             //   explicitly initialized. One particular case: non-captured binding
84628             //   declared inside loop body (but not in loop initializer):
84629             //
84630             //    let x;
84631             //    for (;;) {
84632             //        let x;
84633             //    }
84634             //
84635             //   In downlevel codegen inner 'x' will be renamed so it won't collide
84636             //   with outer 'x' however it will should be reset on every iteration as
84637             //   if it was declared anew.
84638             //
84639             //   * Why non-captured binding?
84640             //     - Because if loop contains block scoped binding captured in some
84641             //       function then loop body will be rewritten to have a fresh scope
84642             //       on every iteration so everything will just work.
84643             //
84644             //   * Why loop initializer is excluded?
84645             //     - Since we've introduced a fresh name it already will be undefined.
84646             var flags = resolver.getNodeCheckFlags(node);
84647             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
84648             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
84649             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
84650                 || (isCapturedInFunction
84651                     && isDeclaredInLoop
84652                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
84653             var emitExplicitInitializer = !emittedAsTopLevel
84654                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
84655                 && (!resolver.isDeclarationWithCollidingName(node)
84656                     || (isDeclaredInLoop
84657                         && !isCapturedInFunction
84658                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
84659             return emitExplicitInitializer;
84660         }
84661         /**
84662          * Visits a VariableDeclaration in a `let` declaration list.
84663          *
84664          * @param node A VariableDeclaration node.
84665          */
84666         function visitVariableDeclarationInLetDeclarationList(node) {
84667             // For binding pattern names that lack initializers there is no point to emit
84668             // explicit initializer since downlevel codegen for destructuring will fail
84669             // in the absence of initializer so all binding elements will say uninitialized
84670             var name = node.name;
84671             if (ts.isBindingPattern(name)) {
84672                 return visitVariableDeclaration(node);
84673             }
84674             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
84675                 var clone_3 = ts.getMutableClone(node);
84676                 clone_3.initializer = ts.createVoidZero();
84677                 return clone_3;
84678             }
84679             return ts.visitEachChild(node, visitor, context);
84680         }
84681         /**
84682          * Visits a VariableDeclaration node with a binding pattern.
84683          *
84684          * @param node A VariableDeclaration node.
84685          */
84686         function visitVariableDeclaration(node) {
84687             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
84688             var updated;
84689             if (ts.isBindingPattern(node.name)) {
84690                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
84691                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
84692             }
84693             else {
84694                 updated = ts.visitEachChild(node, visitor, context);
84695             }
84696             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84697             return updated;
84698         }
84699         function recordLabel(node) {
84700             convertedLoopState.labels.set(ts.idText(node.label), true);
84701         }
84702         function resetLabel(node) {
84703             convertedLoopState.labels.set(ts.idText(node.label), false);
84704         }
84705         function visitLabeledStatement(node) {
84706             if (convertedLoopState && !convertedLoopState.labels) {
84707                 convertedLoopState.labels = ts.createMap();
84708             }
84709             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
84710             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
84711                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
84712                 : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
84713         }
84714         function visitIterationStatement(node, outermostLabeledStatement) {
84715             switch (node.kind) {
84716                 case 228 /* DoStatement */:
84717                 case 229 /* WhileStatement */:
84718                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
84719                 case 230 /* ForStatement */:
84720                     return visitForStatement(node, outermostLabeledStatement);
84721                 case 231 /* ForInStatement */:
84722                     return visitForInStatement(node, outermostLabeledStatement);
84723                 case 232 /* ForOfStatement */:
84724                     return visitForOfStatement(node, outermostLabeledStatement);
84725             }
84726         }
84727         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
84728             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
84729             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
84730             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84731             return updated;
84732         }
84733         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
84734             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
84735         }
84736         function visitForStatement(node, outermostLabeledStatement) {
84737             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
84738         }
84739         function visitForInStatement(node, outermostLabeledStatement) {
84740             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
84741         }
84742         function visitForOfStatement(node, outermostLabeledStatement) {
84743             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
84744         }
84745         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
84746             var statements = [];
84747             var initializer = node.initializer;
84748             if (ts.isVariableDeclarationList(initializer)) {
84749                 if (node.initializer.flags & 3 /* BlockScoped */) {
84750                     enableSubstitutionsForBlockScopedBindings();
84751                 }
84752                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
84753                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
84754                     // This works whether the declaration is a var, let, or const.
84755                     // It will use rhsIterationValue _a[_i] as the initializer.
84756                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
84757                     var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
84758                     ts.setOriginalNode(declarationList, node.initializer);
84759                     // Adjust the source map range for the first declaration to align with the old
84760                     // emitter.
84761                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
84762                     statements.push(ts.createVariableStatement(
84763                     /*modifiers*/ undefined, declarationList));
84764                 }
84765                 else {
84766                     // The following call does not include the initializer, so we have
84767                     // to emit it separately.
84768                     statements.push(ts.setTextRange(ts.createVariableStatement(
84769                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
84770                         ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), 
84771                         /*type*/ undefined, boundValue)
84772                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
84773                 }
84774             }
84775             else {
84776                 // Initializer is an expression. Emit the expression in the body, so that it's
84777                 // evaluated on every iteration.
84778                 var assignment = ts.createAssignment(initializer, boundValue);
84779                 if (ts.isDestructuringAssignment(assignment)) {
84780                     ts.aggregateTransformFlags(assignment);
84781                     statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
84782                 }
84783                 else {
84784                     assignment.end = initializer.end;
84785                     statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
84786                 }
84787             }
84788             if (convertedLoopBodyStatements) {
84789                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
84790             }
84791             else {
84792                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
84793                 if (ts.isBlock(statement)) {
84794                     return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
84795                 }
84796                 else {
84797                     statements.push(statement);
84798                     return createSyntheticBlockForConvertedStatements(statements);
84799                 }
84800             }
84801         }
84802         function createSyntheticBlockForConvertedStatements(statements) {
84803             return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), 
84804             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
84805         }
84806         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
84807             // The following ES6 code:
84808             //
84809             //    for (let v of expr) { }
84810             //
84811             // should be emitted as
84812             //
84813             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
84814             //        var v = _a[_i];
84815             //    }
84816             //
84817             // where _a and _i are temps emitted to capture the RHS and the counter,
84818             // respectively.
84819             // When the left hand side is an expression instead of a let declaration,
84820             // the "let v" is not emitted.
84821             // When the left hand side is a let/const, the v is renamed if there is
84822             // another v in scope.
84823             // Note that all assignments to the LHS are emitted in the body, including
84824             // all destructuring.
84825             // Note also that because an extra statement is needed to assign to the LHS,
84826             // for-of bodies are always emitted as blocks.
84827             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84828             // In the case where the user wrote an identifier as the RHS, like this:
84829             //
84830             //     for (let v of arr) { }
84831             //
84832             // we don't want to emit a temporary variable for the RHS, just use it directly.
84833             var counter = ts.createLoopVariable();
84834             var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84835             // The old emitter does not emit source maps for the expression
84836             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
84837             var forStatement = ts.setTextRange(ts.createFor(
84838             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84839                 ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
84840                 ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
84841             ]), node.expression), 2097152 /* NoHoisting */), 
84842             /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), 
84843             /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), 
84844             /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), 
84845             /*location*/ node);
84846             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
84847             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
84848             ts.setTextRange(forStatement, node);
84849             return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
84850         }
84851         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
84852             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84853             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84854             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84855             var errorRecord = ts.createUniqueName("e");
84856             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
84857             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
84858             var values = ts.createValuesHelper(context, expression, node.expression);
84859             var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
84860             hoistVariableDeclaration(errorRecord);
84861             hoistVariableDeclaration(returnMethod);
84862             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
84863             var initializer = ancestorFacts & 1024 /* IterationContainer */
84864                 ? ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), values])
84865                 : values;
84866             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
84867             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84868                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
84869                 ts.createVariableDeclaration(result, /*type*/ undefined, next)
84870             ]), node.expression), 2097152 /* NoHoisting */), 
84871             /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), 
84872             /*incrementor*/ ts.createAssignment(result, next), 
84873             /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), 
84874             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
84875             return ts.createTry(ts.createBlock([
84876                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
84877             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
84878                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
84879                     ts.createPropertyAssignment("error", catchVariable)
84880                 ])))
84881             ]), 1 /* SingleLine */)), ts.createBlock([
84882                 ts.createTry(
84883                 /*tryBlock*/ ts.createBlock([
84884                     ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */),
84885                 ]), 
84886                 /*catchClause*/ undefined, 
84887                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
84888                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
84889                 ]), 1 /* SingleLine */))
84890             ]));
84891         }
84892         /**
84893          * Visits an ObjectLiteralExpression with computed property names.
84894          *
84895          * @param node An ObjectLiteralExpression node.
84896          */
84897         function visitObjectLiteralExpression(node) {
84898             // We are here because a ComputedPropertyName was used somewhere in the expression.
84899             var properties = node.properties;
84900             var numProperties = properties.length;
84901             // Find the first computed property.
84902             // Everything until that point can be emitted as part of the initial object literal.
84903             var numInitialProperties = numProperties;
84904             var numInitialPropertiesWithoutYield = numProperties;
84905             for (var i = 0; i < numProperties; i++) {
84906                 var property = properties[i];
84907                 if ((property.transformFlags & 262144 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
84908                     && i < numInitialPropertiesWithoutYield) {
84909                     numInitialPropertiesWithoutYield = i;
84910                 }
84911                 if (property.name.kind === 154 /* ComputedPropertyName */) {
84912                     numInitialProperties = i;
84913                     break;
84914                 }
84915             }
84916             if (numInitialProperties !== numProperties) {
84917                 if (numInitialPropertiesWithoutYield < numInitialProperties) {
84918                     numInitialProperties = numInitialPropertiesWithoutYield;
84919                 }
84920                 // For computed properties, we need to create a unique handle to the object
84921                 // literal so we can modify it without risking internal assignments tainting the object.
84922                 var temp = ts.createTempVariable(hoistVariableDeclaration);
84923                 // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
84924                 var expressions = [];
84925                 var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
84926                 if (node.multiLine) {
84927                     ts.startOnNewLine(assignment);
84928                 }
84929                 expressions.push(assignment);
84930                 addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
84931                 // We need to clone the temporary identifier so that we can write it on a
84932                 // new line
84933                 expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
84934                 return ts.inlineExpressions(expressions);
84935             }
84936             return ts.visitEachChild(node, visitor, context);
84937         }
84938         function shouldConvertPartOfIterationStatement(node) {
84939             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
84940         }
84941         function shouldConvertInitializerOfForStatement(node) {
84942             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
84943         }
84944         function shouldConvertConditionOfForStatement(node) {
84945             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
84946         }
84947         function shouldConvertIncrementorOfForStatement(node) {
84948             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
84949         }
84950         function shouldConvertIterationStatement(node) {
84951             return shouldConvertBodyOfIterationStatement(node)
84952                 || shouldConvertInitializerOfForStatement(node);
84953         }
84954         function shouldConvertBodyOfIterationStatement(node) {
84955             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
84956         }
84957         /**
84958          * Records constituents of name for the given variable to be hoisted in the outer scope.
84959          */
84960         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
84961             if (!state.hoistedLocalVariables) {
84962                 state.hoistedLocalVariables = [];
84963             }
84964             visit(node.name);
84965             function visit(node) {
84966                 if (node.kind === 75 /* Identifier */) {
84967                     state.hoistedLocalVariables.push(node);
84968                 }
84969                 else {
84970                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
84971                         var element = _a[_i];
84972                         if (!ts.isOmittedExpression(element)) {
84973                             visit(element.name);
84974                         }
84975                     }
84976                 }
84977             }
84978         }
84979         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
84980             if (!shouldConvertIterationStatement(node)) {
84981                 var saveAllowedNonLabeledJumps = void 0;
84982                 if (convertedLoopState) {
84983                     // we get here if we are trying to emit normal loop loop inside converted loop
84984                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
84985                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
84986                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
84987                 }
84988                 var result = convert
84989                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
84990                     : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
84991                 if (convertedLoopState) {
84992                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
84993                 }
84994                 return result;
84995             }
84996             var currentState = createConvertedLoopState(node);
84997             var statements = [];
84998             var outerConvertedLoopState = convertedLoopState;
84999             convertedLoopState = currentState;
85000             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
85001             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
85002             convertedLoopState = outerConvertedLoopState;
85003             if (initializerFunction)
85004                 statements.push(initializerFunction.functionDeclaration);
85005             if (bodyFunction)
85006                 statements.push(bodyFunction.functionDeclaration);
85007             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
85008             if (initializerFunction) {
85009                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
85010             }
85011             var loop;
85012             if (bodyFunction) {
85013                 if (convert) {
85014                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
85015                 }
85016                 else {
85017                     var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true));
85018                     ts.aggregateTransformFlags(clone_4);
85019                     loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
85020                 }
85021             }
85022             else {
85023                 var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
85024                 ts.aggregateTransformFlags(clone_5);
85025                 loop = ts.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel);
85026             }
85027             statements.push(loop);
85028             return statements;
85029         }
85030         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
85031             switch (node.kind) {
85032                 case 230 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
85033                 case 231 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
85034                 case 232 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
85035                 case 228 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
85036                 case 229 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
85037                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
85038             }
85039         }
85040         function convertForStatement(node, initializerFunction, convertedLoopBody) {
85041             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
85042             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
85043             return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody);
85044         }
85045         function convertForOfStatement(node, convertedLoopBody) {
85046             return ts.updateForOf(node, 
85047             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85048         }
85049         function convertForInStatement(node, convertedLoopBody) {
85050             return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85051         }
85052         function convertDoStatement(node, convertedLoopBody) {
85053             return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
85054         }
85055         function convertWhileStatement(node, convertedLoopBody) {
85056             return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85057         }
85058         function createConvertedLoopState(node) {
85059             var loopInitializer;
85060             switch (node.kind) {
85061                 case 230 /* ForStatement */:
85062                 case 231 /* ForInStatement */:
85063                 case 232 /* ForOfStatement */:
85064                     var initializer = node.initializer;
85065                     if (initializer && initializer.kind === 243 /* VariableDeclarationList */) {
85066                         loopInitializer = initializer;
85067                     }
85068                     break;
85069             }
85070             // variables that will be passed to the loop as parameters
85071             var loopParameters = [];
85072             // variables declared in the loop initializer that will be changed inside the loop
85073             var loopOutParameters = [];
85074             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
85075                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
85076                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
85077                     var decl = _a[_i];
85078                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85079                 }
85080             }
85081             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
85082             if (convertedLoopState) {
85083                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
85084                 // if outer converted loop has already accumulated some state - pass it through
85085                 if (convertedLoopState.argumentsName) {
85086                     // outer loop has already used 'arguments' so we've already have some name to alias it
85087                     // use the same name in all nested loops
85088                     currentState.argumentsName = convertedLoopState.argumentsName;
85089                 }
85090                 if (convertedLoopState.thisName) {
85091                     // outer loop has already used 'this' so we've already have some name to alias it
85092                     // use the same name in all nested loops
85093                     currentState.thisName = convertedLoopState.thisName;
85094                 }
85095                 if (convertedLoopState.hoistedLocalVariables) {
85096                     // we've already collected some non-block scoped variable declarations in enclosing loop
85097                     // use the same storage in nested loop
85098                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
85099                 }
85100             }
85101             return currentState;
85102         }
85103         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
85104             var extraVariableDeclarations;
85105             // propagate state from the inner loop to the outer loop if necessary
85106             if (state.argumentsName) {
85107                 // if alias for arguments is set
85108                 if (outerState) {
85109                     // pass it to outer converted loop
85110                     outerState.argumentsName = state.argumentsName;
85111                 }
85112                 else {
85113                     // this is top level converted loop and we need to create an alias for 'arguments' object
85114                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, 
85115                     /*type*/ undefined, ts.createIdentifier("arguments")));
85116                 }
85117             }
85118             if (state.thisName) {
85119                 // if alias for this is set
85120                 if (outerState) {
85121                     // pass it to outer converted loop
85122                     outerState.thisName = state.thisName;
85123                 }
85124                 else {
85125                     // this is top level converted loop so we need to create an alias for 'this' here
85126                     // NOTE:
85127                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
85128                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
85129                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, 
85130                     /*type*/ undefined, ts.createIdentifier("this")));
85131                 }
85132             }
85133             if (state.hoistedLocalVariables) {
85134                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
85135                 if (outerState) {
85136                     // pass them to outer converted loop
85137                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
85138                 }
85139                 else {
85140                     if (!extraVariableDeclarations) {
85141                         extraVariableDeclarations = [];
85142                     }
85143                     // hoist collected variable declarations
85144                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
85145                         var identifier = _a[_i];
85146                         extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
85147                     }
85148                 }
85149             }
85150             // add extra variables to hold out parameters if necessary
85151             if (state.loopOutParameters.length) {
85152                 if (!extraVariableDeclarations) {
85153                     extraVariableDeclarations = [];
85154                 }
85155                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
85156                     var outParam = _c[_b];
85157                     extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
85158                 }
85159             }
85160             if (state.conditionVariable) {
85161                 if (!extraVariableDeclarations) {
85162                     extraVariableDeclarations = [];
85163                 }
85164                 extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse()));
85165             }
85166             // create variable statement to hold all introduced variable declarations
85167             if (extraVariableDeclarations) {
85168                 statements.push(ts.createVariableStatement(
85169                 /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
85170             }
85171         }
85172         function createOutVariable(p) {
85173             return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName);
85174         }
85175         /**
85176          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
85177          * that is captured in a closure inside of the initializer. The `_loop_init` function is
85178          * used to preserve the per-iteration environment semantics of
85179          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85180          */
85181         function createFunctionForInitializerOfForStatement(node, currentState) {
85182             var functionName = ts.createUniqueName("_loop_init");
85183             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
85184             var emitFlags = 0 /* None */;
85185             if (currentState.containsLexicalThis)
85186                 emitFlags |= 8 /* CapturesThis */;
85187             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
85188                 emitFlags |= 262144 /* AsyncFunctionBody */;
85189             var statements = [];
85190             statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer));
85191             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
85192             // This transforms the following ES2015 syntax:
85193             //
85194             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
85195             //      // loop body
85196             //  }
85197             //
85198             // Into the following ES5 syntax:
85199             //
85200             //  var _loop_init_1 = function () {
85201             //      var i = (setImmediate(() => console.log(i)), 0);
85202             //      out_i_1 = i;
85203             //  };
85204             //  var out_i_1;
85205             //  _loop_init_1();
85206             //  for (var i = out_i_1; i < 2; i++) {
85207             //      // loop body
85208             //  }
85209             //
85210             // Which prevents mutations to `i` in the per-iteration environment of the body
85211             // from affecting the initial value for `i` outside of the per-iteration environment.
85212             var functionDeclaration = ts.createVariableStatement(
85213             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85214                 ts.createVariableDeclaration(functionName, 
85215                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85216                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85217                 /*name*/ undefined, 
85218                 /*typeParameters*/ undefined, 
85219                 /*parameters*/ undefined, 
85220                 /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
85221             ]), 2097152 /* NoHoisting */));
85222             var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
85223             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85224         }
85225         /**
85226          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
85227          * that is captured in a closure inside of the loop body. The `_loop` function is used to
85228          * preserve the per-iteration environment semantics of
85229          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85230          */
85231         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
85232             var functionName = ts.createUniqueName("_loop");
85233             startLexicalEnvironment();
85234             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
85235             var lexicalEnvironment = endLexicalEnvironment();
85236             var statements = [];
85237             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
85238                 // If a block-scoped variable declared in the initializer of `node` is captured in
85239                 // the condition or incrementor, we must move the condition and incrementor into
85240                 // the body of the for loop.
85241                 //
85242                 // This transforms the following ES2015 syntax:
85243                 //
85244                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
85245                 //      // loop body
85246                 //  }
85247                 //
85248                 // Into the following ES5 syntax:
85249                 //
85250                 //  var _loop_1 = function (i) {
85251                 //      if (inc_1)
85252                 //          setImmediate(() => console.log(i)), i++;
85253                 //      else
85254                 //          inc_1 = true;
85255                 //      if (!(setImmediate(() => console.log(i)), i < 2))
85256                 //          return out_i_1 = i, "break";
85257                 //      // loop body
85258                 //      out_i_1 = i;
85259                 //  }
85260                 //  var out_i_1, inc_1 = false;
85261                 //  for (var i = 0;;) {
85262                 //      var state_1 = _loop_1(i);
85263                 //      i = out_i_1;
85264                 //      if (state_1 === "break")
85265                 //          break;
85266                 //  }
85267                 //
85268                 // Which prevents mutations to `i` in the per-iteration environment of the body
85269                 // from affecting the value of `i` in the previous per-iteration environment.
85270                 //
85271                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
85272                 // environment that is carried over to the next iteration of the loop. As a result,
85273                 // we must indicate whether this is the first evaluation of the loop body so that
85274                 // we only evaluate the incrementor on subsequent evaluations.
85275                 currentState.conditionVariable = ts.createUniqueName("inc");
85276                 statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue()))));
85277                 if (shouldConvertConditionOfForStatement(node)) {
85278                     statements.push(ts.createIf(ts.createPrefix(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement)));
85279                 }
85280             }
85281             if (ts.isBlock(statement)) {
85282                 ts.addRange(statements, statement.statements);
85283             }
85284             else {
85285                 statements.push(statement);
85286             }
85287             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
85288             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
85289             var loopBody = ts.createBlock(statements, /*multiLine*/ true);
85290             if (ts.isBlock(statement))
85291                 ts.setOriginalNode(loopBody, statement);
85292             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
85293             var emitFlags = 0;
85294             if (currentState.containsLexicalThis)
85295                 emitFlags |= 8 /* CapturesThis */;
85296             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
85297                 emitFlags |= 262144 /* AsyncFunctionBody */;
85298             // This transforms the following ES2015 syntax (in addition to other variations):
85299             //
85300             //  for (let i = 0; i < 2; i++) {
85301             //      setImmediate(() => console.log(i));
85302             //  }
85303             //
85304             // Into the following ES5 syntax:
85305             //
85306             //  var _loop_1 = function (i) {
85307             //      setImmediate(() => console.log(i));
85308             //  };
85309             //  for (var i = 0; i < 2; i++) {
85310             //      _loop_1(i);
85311             //  }
85312             var functionDeclaration = ts.createVariableStatement(
85313             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85314                 ts.createVariableDeclaration(functionName, 
85315                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85316                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85317                 /*name*/ undefined, 
85318                 /*typeParameters*/ undefined, currentState.loopParameters, 
85319                 /*type*/ undefined, loopBody), emitFlags))
85320             ]), 2097152 /* NoHoisting */));
85321             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
85322             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85323         }
85324         function copyOutParameter(outParam, copyDirection) {
85325             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
85326             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
85327             return ts.createBinary(target, 62 /* EqualsToken */, source);
85328         }
85329         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
85330             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
85331                 var outParam = outParams_1[_i];
85332                 if (outParam.flags & partFlags) {
85333                     statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
85334                 }
85335             }
85336         }
85337         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
85338             var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []);
85339             var callResult = containsYield
85340                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85341                 : call;
85342             return ts.createStatement(callResult);
85343         }
85344         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
85345             var statements = [];
85346             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
85347             // simple loops are emitted as just 'loop()';
85348             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
85349             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
85350                 !state.labeledNonLocalBreaks &&
85351                 !state.labeledNonLocalContinues;
85352             var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
85353             var callResult = containsYield
85354                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85355                 : call;
85356             if (isSimpleLoop) {
85357                 statements.push(ts.createExpressionStatement(callResult));
85358                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85359             }
85360             else {
85361                 var loopResultName = ts.createUniqueName("state");
85362                 var stateVariable = ts.createVariableStatement(
85363                 /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
85364                 statements.push(stateVariable);
85365                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85366                 if (state.nonLocalJumps & 8 /* Return */) {
85367                     var returnStatement = void 0;
85368                     if (outerState) {
85369                         outerState.nonLocalJumps |= 8 /* Return */;
85370                         returnStatement = ts.createReturn(loopResultName);
85371                     }
85372                     else {
85373                         returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
85374                     }
85375                     statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
85376                 }
85377                 if (state.nonLocalJumps & 2 /* Break */) {
85378                     statements.push(ts.createIf(ts.createBinary(loopResultName, 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
85379                 }
85380                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
85381                     var caseClauses = [];
85382                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
85383                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
85384                     statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
85385                 }
85386             }
85387             return statements;
85388         }
85389         function setLabeledJump(state, isBreak, labelText, labelMarker) {
85390             if (isBreak) {
85391                 if (!state.labeledNonLocalBreaks) {
85392                     state.labeledNonLocalBreaks = ts.createMap();
85393                 }
85394                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
85395             }
85396             else {
85397                 if (!state.labeledNonLocalContinues) {
85398                     state.labeledNonLocalContinues = ts.createMap();
85399                 }
85400                 state.labeledNonLocalContinues.set(labelText, labelMarker);
85401             }
85402         }
85403         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
85404             if (!table) {
85405                 return;
85406             }
85407             table.forEach(function (labelMarker, labelText) {
85408                 var statements = [];
85409                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
85410                 // then emit labeled break\continue
85411                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
85412                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
85413                     var label = ts.createIdentifier(labelText);
85414                     statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
85415                 }
85416                 else {
85417                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
85418                     statements.push(ts.createReturn(loopResultName));
85419                 }
85420                 caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
85421             });
85422         }
85423         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
85424             var name = decl.name;
85425             if (ts.isBindingPattern(name)) {
85426                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
85427                     var element = _a[_i];
85428                     if (!ts.isOmittedExpression(element)) {
85429                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85430                     }
85431                 }
85432             }
85433             else {
85434                 loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
85435                 var checkFlags = resolver.getNodeCheckFlags(decl);
85436                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
85437                     var outParamName = ts.createUniqueName("out_" + ts.idText(name));
85438                     var flags = 0;
85439                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
85440                         flags |= 1 /* Body */;
85441                     }
85442                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
85443                         flags |= 2 /* Initializer */;
85444                     }
85445                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
85446                 }
85447             }
85448         }
85449         /**
85450          * Adds the members of an object literal to an array of expressions.
85451          *
85452          * @param expressions An array of expressions.
85453          * @param node An ObjectLiteralExpression node.
85454          * @param receiver The receiver for members of the ObjectLiteralExpression.
85455          * @param numInitialNonComputedProperties The number of initial properties without
85456          *                                        computed property names.
85457          */
85458         function addObjectLiteralMembers(expressions, node, receiver, start) {
85459             var properties = node.properties;
85460             var numProperties = properties.length;
85461             for (var i = start; i < numProperties; i++) {
85462                 var property = properties[i];
85463                 switch (property.kind) {
85464                     case 163 /* GetAccessor */:
85465                     case 164 /* SetAccessor */:
85466                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
85467                         if (property === accessors.firstAccessor) {
85468                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
85469                         }
85470                         break;
85471                     case 161 /* MethodDeclaration */:
85472                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
85473                         break;
85474                     case 281 /* PropertyAssignment */:
85475                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
85476                         break;
85477                     case 282 /* ShorthandPropertyAssignment */:
85478                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
85479                         break;
85480                     default:
85481                         ts.Debug.failBadSyntaxKind(node);
85482                         break;
85483                 }
85484             }
85485         }
85486         /**
85487          * Transforms a PropertyAssignment node into an expression.
85488          *
85489          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
85490          * @param property The PropertyAssignment node.
85491          * @param receiver The receiver for the assignment.
85492          */
85493         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85494             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
85495             ts.setTextRange(expression, property);
85496             if (startsOnNewLine) {
85497                 ts.startOnNewLine(expression);
85498             }
85499             return expression;
85500         }
85501         /**
85502          * Transforms a ShorthandPropertyAssignment node into an expression.
85503          *
85504          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
85505          * @param property The ShorthandPropertyAssignment node.
85506          * @param receiver The receiver for the assignment.
85507          */
85508         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85509             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
85510             ts.setTextRange(expression, property);
85511             if (startsOnNewLine) {
85512                 ts.startOnNewLine(expression);
85513             }
85514             return expression;
85515         }
85516         /**
85517          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
85518          *
85519          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
85520          * @param method The MethodDeclaration node.
85521          * @param receiver The receiver for the assignment.
85522          */
85523         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
85524             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
85525             ts.setTextRange(expression, method);
85526             if (startsOnNewLine) {
85527                 ts.startOnNewLine(expression);
85528             }
85529             return expression;
85530         }
85531         function visitCatchClause(node) {
85532             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
85533             var updated;
85534             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
85535             if (ts.isBindingPattern(node.variableDeclaration.name)) {
85536                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
85537                 var newVariableDeclaration = ts.createVariableDeclaration(temp);
85538                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
85539                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
85540                 var list = ts.createVariableDeclarationList(vars);
85541                 ts.setTextRange(list, node.variableDeclaration);
85542                 var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
85543                 updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
85544             }
85545             else {
85546                 updated = ts.visitEachChild(node, visitor, context);
85547             }
85548             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
85549             return updated;
85550         }
85551         function addStatementToStartOfBlock(block, statement) {
85552             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
85553             return ts.updateBlock(block, __spreadArrays([statement], transformedStatements));
85554         }
85555         /**
85556          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
85557          * PropertyAssignment.
85558          *
85559          * @param node A MethodDeclaration node.
85560          */
85561         function visitMethodDeclaration(node) {
85562             // We should only get here for methods on an object literal with regular identifier names.
85563             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
85564             // Methods with computed property names are handled in visitObjectLiteralExpression.
85565             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85566             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
85567             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
85568             return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), 
85569             /*location*/ node);
85570         }
85571         /**
85572          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
85573          *
85574          * @param node An AccessorDeclaration node.
85575          */
85576         function visitAccessorDeclaration(node) {
85577             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85578             var savedConvertedLoopState = convertedLoopState;
85579             convertedLoopState = undefined;
85580             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
85581             var updated;
85582             var parameters = ts.visitParameterList(node.parameters, visitor, context);
85583             var body = transformFunctionBody(node);
85584             if (node.kind === 163 /* GetAccessor */) {
85585                 updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
85586             }
85587             else {
85588                 updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
85589             }
85590             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
85591             convertedLoopState = savedConvertedLoopState;
85592             return updated;
85593         }
85594         /**
85595          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
85596          *
85597          * @param node A ShorthandPropertyAssignment node.
85598          */
85599         function visitShorthandPropertyAssignment(node) {
85600             return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), 
85601             /*location*/ node);
85602         }
85603         function visitComputedPropertyName(node) {
85604             return ts.visitEachChild(node, visitor, context);
85605         }
85606         /**
85607          * Visits a YieldExpression node.
85608          *
85609          * @param node A YieldExpression node.
85610          */
85611         function visitYieldExpression(node) {
85612             // `yield` expressions are transformed using the generators transformer.
85613             return ts.visitEachChild(node, visitor, context);
85614         }
85615         /**
85616          * Visits an ArrayLiteralExpression that contains a spread element.
85617          *
85618          * @param node An ArrayLiteralExpression node.
85619          */
85620         function visitArrayLiteralExpression(node) {
85621             if (ts.some(node.elements, ts.isSpreadElement)) {
85622                 // We are here because we contain a SpreadElementExpression.
85623                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
85624             }
85625             return ts.visitEachChild(node, visitor, context);
85626         }
85627         /**
85628          * Visits a CallExpression that contains either a spread element or `super`.
85629          *
85630          * @param node a CallExpression.
85631          */
85632         function visitCallExpression(node) {
85633             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
85634                 return visitTypeScriptClassWrapper(node);
85635             }
85636             var expression = ts.skipOuterExpressions(node.expression);
85637             if (expression.kind === 102 /* SuperKeyword */ ||
85638                 ts.isSuperProperty(expression) ||
85639                 ts.some(node.arguments, ts.isSpreadElement)) {
85640                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
85641             }
85642             return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
85643             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
85644         }
85645         function visitTypeScriptClassWrapper(node) {
85646             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
85647             // The wrapper has a form similar to:
85648             //
85649             //  (function() {
85650             //      class C { // 1
85651             //      }
85652             //      C.x = 1; // 2
85653             //      return C;
85654             //  }())
85655             //
85656             // When we transform the class, we end up with something like this:
85657             //
85658             //  (function () {
85659             //      var C = (function () { // 3
85660             //          function C() {
85661             //          }
85662             //          return C; // 4
85663             //      }());
85664             //      C.x = 1;
85665             //      return C;
85666             //  }())
85667             //
85668             // We want to simplify the two nested IIFEs to end up with something like this:
85669             //
85670             //  (function () {
85671             //      function C() {
85672             //      }
85673             //      C.x = 1;
85674             //      return C;
85675             //  }())
85676             // We skip any outer expressions in a number of places to get to the innermost
85677             // expression, but we will restore them later to preserve comments and source maps.
85678             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
85679             // The class statements are the statements generated by visiting the first statement with initializer of the
85680             // body (1), while all other statements are added to remainingStatements (2)
85681             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
85682             // visit the class body statements outside of any converted loop body.
85683             var savedConvertedLoopState = convertedLoopState;
85684             convertedLoopState = undefined;
85685             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
85686             convertedLoopState = savedConvertedLoopState;
85687             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
85688             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
85689             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
85690             // We know there is only one variable declaration here as we verified this in an
85691             // earlier call to isTypeScriptClassWrapper
85692             var variable = varStatement.declarationList.declarations[0];
85693             var initializer = ts.skipOuterExpressions(variable.initializer);
85694             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
85695             // we see as an assignment, for example:
85696             //
85697             //  (function () {
85698             //      var C_1;
85699             //      var C = C_1 = (function () {
85700             //          function C() {
85701             //          }
85702             //          C.x = function () { return C_1; }
85703             //          return C;
85704             //      }());
85705             //      C = C_1 = __decorate([dec], C);
85706             //      return C;
85707             //  }())
85708             //
85709             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
85710             // The underlying call (3) is another IIFE that may contain a '_super' argument.
85711             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
85712             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
85713             var funcStatements = func.body.statements;
85714             var classBodyStart = 0;
85715             var classBodyEnd = -1;
85716             var statements = [];
85717             if (aliasAssignment) {
85718                 // If we have a class alias assignment, we need to move it to the down-level constructor
85719                 // function we generated for the class.
85720                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
85721                 if (extendsCall) {
85722                     statements.push(extendsCall);
85723                     classBodyStart++;
85724                 }
85725                 // The next statement is the function declaration.
85726                 statements.push(funcStatements[classBodyStart]);
85727                 classBodyStart++;
85728                 // Add the class alias following the declaration.
85729                 statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
85730             }
85731             // Find the trailing 'return' statement (4)
85732             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
85733                 classBodyEnd--;
85734             }
85735             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
85736             // as we already have one that has been introduced by the 'ts' transformer.
85737             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
85738             if (classBodyEnd < -1) {
85739                 // If there were any hoisted declarations following the return statement, we should
85740                 // append them.
85741                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
85742             }
85743             // Add the remaining statements of the outer wrapper.
85744             ts.addRange(statements, remainingStatements);
85745             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
85746             // after the remaining statements from the 'ts' transformer.
85747             ts.addRange(statements, classStatements, /*start*/ 1);
85748             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
85749             // and comment locations.
85750             return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, 
85751             /*modifiers*/ undefined, 
85752             /*asteriskToken*/ undefined, 
85753             /*name*/ undefined, 
85754             /*typeParameters*/ undefined, func.parameters, 
85755             /*type*/ undefined, ts.updateBlock(func.body, statements))), 
85756             /*typeArguments*/ undefined, call.arguments))));
85757         }
85758         function visitImmediateSuperCallInBody(node) {
85759             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
85760         }
85761         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
85762             // We are here either because SuperKeyword was used somewhere in the expression, or
85763             // because we contain a SpreadElementExpression.
85764             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
85765                 node.expression.kind === 102 /* SuperKeyword */ ||
85766                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
85767                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85768                 if (node.expression.kind === 102 /* SuperKeyword */) {
85769                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
85770                 }
85771                 var resultingCall = void 0;
85772                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
85773                     // [source]
85774                     //      f(...a, b)
85775                     //      x.m(...a, b)
85776                     //      super(...a, b)
85777                     //      super.m(...a, b) // in static
85778                     //      super.m(...a, b) // in instance
85779                     //
85780                     // [output]
85781                     //      f.apply(void 0, a.concat([b]))
85782                     //      (_a = x).m.apply(_a, a.concat([b]))
85783                     //      _super.apply(this, a.concat([b]))
85784                     //      _super.m.apply(this, a.concat([b]))
85785                     //      _super.prototype.m.apply(this, a.concat([b]))
85786                     resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 102 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
85787                 }
85788                 else {
85789                     // [source]
85790                     //      super(a)
85791                     //      super.m(a) // in static
85792                     //      super.m(a) // in instance
85793                     //
85794                     // [output]
85795                     //      _super.call(this, a)
85796                     //      _super.m.call(this, a)
85797                     //      _super.prototype.m.call(this, a)
85798                     resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 102 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), 
85799                     /*location*/ node);
85800                 }
85801                 if (node.expression.kind === 102 /* SuperKeyword */) {
85802                     var initializer = ts.createLogicalOr(resultingCall, createActualThis());
85803                     resultingCall = assignToCapturedThis
85804                         ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
85805                         : initializer;
85806                 }
85807                 return ts.setOriginalNode(resultingCall, node);
85808             }
85809             return ts.visitEachChild(node, visitor, context);
85810         }
85811         /**
85812          * Visits a NewExpression that contains a spread element.
85813          *
85814          * @param node A NewExpression node.
85815          */
85816         function visitNewExpression(node) {
85817             if (ts.some(node.arguments, ts.isSpreadElement)) {
85818                 // We are here because we contain a SpreadElementExpression.
85819                 // [source]
85820                 //      new C(...a)
85821                 //
85822                 // [output]
85823                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
85824                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85825                 return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray(__spreadArrays([ts.createVoidZero()], node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), 
85826                 /*typeArguments*/ undefined, []);
85827             }
85828             return ts.visitEachChild(node, visitor, context);
85829         }
85830         /**
85831          * Transforms an array of Expression nodes that contains a SpreadExpression.
85832          *
85833          * @param elements The array of Expression nodes.
85834          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
85835          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
85836          */
85837         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
85838             // [source]
85839             //      [a, ...b, c]
85840             //
85841             // [output (downlevelIteration)]
85842             //      __spread([a], b, [c])
85843             //
85844             // [output]
85845             //      __spreadArrays([a], b, [c])
85846             // Map spans of spread expressions into their expressions and spans of other
85847             // expressions into an array literal.
85848             var numElements = elements.length;
85849             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
85850                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
85851             }));
85852             if (compilerOptions.downlevelIteration) {
85853                 if (segments.length === 1) {
85854                     var firstSegment = segments[0];
85855                     if (isCallToHelper(firstSegment, "___spread")) {
85856                         return segments[0];
85857                     }
85858                 }
85859                 return ts.createSpreadHelper(context, segments);
85860             }
85861             else {
85862                 if (segments.length === 1) {
85863                     var firstSegment = segments[0];
85864                     if (!needsUniqueCopy
85865                         || isPackedArrayLiteral(firstSegment)
85866                         || isCallToHelper(firstSegment, "___spreadArrays")) {
85867                         return segments[0];
85868                     }
85869                 }
85870                 return ts.createSpreadArraysHelper(context, segments);
85871             }
85872         }
85873         function isPackedElement(node) {
85874             return !ts.isOmittedExpression(node);
85875         }
85876         function isPackedArrayLiteral(node) {
85877             return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
85878         }
85879         function isCallToHelper(firstSegment, helperName) {
85880             return ts.isCallExpression(firstSegment)
85881                 && ts.isIdentifier(firstSegment.expression)
85882                 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
85883                 && firstSegment.expression.escapedText === helperName;
85884         }
85885         function partitionSpread(node) {
85886             return ts.isSpreadElement(node)
85887                 ? visitSpanOfSpreads
85888                 : visitSpanOfNonSpreads;
85889         }
85890         function visitSpanOfSpreads(chunk) {
85891             return ts.map(chunk, visitExpressionOfSpread);
85892         }
85893         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
85894             return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
85895         }
85896         function visitSpreadElement(node) {
85897             return ts.visitNode(node.expression, visitor, ts.isExpression);
85898         }
85899         /**
85900          * Transforms the expression of a SpreadExpression node.
85901          *
85902          * @param node A SpreadExpression node.
85903          */
85904         function visitExpressionOfSpread(node) {
85905             return ts.visitNode(node.expression, visitor, ts.isExpression);
85906         }
85907         /**
85908          * Visits a template literal.
85909          *
85910          * @param node A template literal.
85911          */
85912         function visitTemplateLiteral(node) {
85913             return ts.setTextRange(ts.createLiteral(node.text), node);
85914         }
85915         /**
85916          * Visits a string literal with an extended unicode escape.
85917          *
85918          * @param node A string literal.
85919          */
85920         function visitStringLiteral(node) {
85921             if (node.hasExtendedUnicodeEscape) {
85922                 return ts.setTextRange(ts.createLiteral(node.text), node);
85923             }
85924             return node;
85925         }
85926         /**
85927          * Visits a binary or octal (ES6) numeric literal.
85928          *
85929          * @param node A string literal.
85930          */
85931         function visitNumericLiteral(node) {
85932             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
85933                 return ts.setTextRange(ts.createNumericLiteral(node.text), node);
85934             }
85935             return node;
85936         }
85937         /**
85938          * Visits a TaggedTemplateExpression node.
85939          *
85940          * @param node A TaggedTemplateExpression node.
85941          */
85942         function visitTaggedTemplateExpression(node) {
85943             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
85944         }
85945         /**
85946          * Visits a TemplateExpression node.
85947          *
85948          * @param node A TemplateExpression node.
85949          */
85950         function visitTemplateExpression(node) {
85951             var expressions = [];
85952             addTemplateHead(expressions, node);
85953             addTemplateSpans(expressions, node);
85954             // createAdd will check if each expression binds less closely than binary '+'.
85955             // If it does, it wraps the expression in parentheses. Otherwise, something like
85956             //    `abc${ 1 << 2 }`
85957             // becomes
85958             //    "abc" + 1 << 2 + ""
85959             // which is really
85960             //    ("abc" + 1) << (2 + "")
85961             // rather than
85962             //    "abc" + (1 << 2) + ""
85963             var expression = ts.reduceLeft(expressions, ts.createAdd);
85964             if (ts.nodeIsSynthesized(expression)) {
85965                 expression.pos = node.pos;
85966                 expression.end = node.end;
85967             }
85968             return expression;
85969         }
85970         /**
85971          * Gets a value indicating whether we need to include the head of a TemplateExpression.
85972          *
85973          * @param node A TemplateExpression node.
85974          */
85975         function shouldAddTemplateHead(node) {
85976             // If this expression has an empty head literal and the first template span has a non-empty
85977             // literal, then emitting the empty head literal is not necessary.
85978             //     `${ foo } and ${ bar }`
85979             // can be emitted as
85980             //     foo + " and " + bar
85981             // This is because it is only required that one of the first two operands in the emit
85982             // output must be a string literal, so that the other operand and all following operands
85983             // are forced into strings.
85984             //
85985             // If the first template span has an empty literal, then the head must still be emitted.
85986             //     `${ foo }${ bar }`
85987             // must still be emitted as
85988             //     "" + foo + bar
85989             // There is always atleast one templateSpan in this code path, since
85990             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
85991             ts.Debug.assert(node.templateSpans.length !== 0);
85992             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
85993         }
85994         /**
85995          * Adds the head of a TemplateExpression to an array of expressions.
85996          *
85997          * @param expressions An array of expressions.
85998          * @param node A TemplateExpression node.
85999          */
86000         function addTemplateHead(expressions, node) {
86001             if (!shouldAddTemplateHead(node)) {
86002                 return;
86003             }
86004             expressions.push(ts.createLiteral(node.head.text));
86005         }
86006         /**
86007          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
86008          *
86009          * @param expressions An array of expressions.
86010          * @param node A TemplateExpression node.
86011          */
86012         function addTemplateSpans(expressions, node) {
86013             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
86014                 var span = _a[_i];
86015                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
86016                 // Only emit if the literal is non-empty.
86017                 // The binary '+' operator is left-associative, so the first string concatenation
86018                 // with the head will force the result up to this point to be a string.
86019                 // Emitting a '+ ""' has no semantic effect for middles and tails.
86020                 if (span.literal.text.length !== 0) {
86021                     expressions.push(ts.createLiteral(span.literal.text));
86022                 }
86023             }
86024         }
86025         /**
86026          * Visits the `super` keyword
86027          */
86028         function visitSuperKeyword(isExpressionOfCall) {
86029             return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") :
86030                 ts.createFileLevelUniqueName("_super");
86031         }
86032         function visitMetaProperty(node) {
86033             if (node.keywordToken === 99 /* NewKeyword */ && node.name.escapedText === "target") {
86034                 hierarchyFacts |= 16384 /* NewTarget */;
86035                 return ts.createFileLevelUniqueName("_newTarget");
86036             }
86037             return node;
86038         }
86039         /**
86040          * Called by the printer just before a node is printed.
86041          *
86042          * @param hint A hint as to the intended usage of the node.
86043          * @param node The node to be printed.
86044          * @param emitCallback The callback used to emit the node.
86045          */
86046         function onEmitNode(hint, node, emitCallback) {
86047             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
86048                 // If we are tracking a captured `this`, keep track of the enclosing function.
86049                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
86050                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
86051                     : 65 /* FunctionIncludes */);
86052                 previousOnEmitNode(hint, node, emitCallback);
86053                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
86054                 return;
86055             }
86056             previousOnEmitNode(hint, node, emitCallback);
86057         }
86058         /**
86059          * Enables a more costly code path for substitutions when we determine a source file
86060          * contains block-scoped bindings (e.g. `let` or `const`).
86061          */
86062         function enableSubstitutionsForBlockScopedBindings() {
86063             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
86064                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
86065                 context.enableSubstitution(75 /* Identifier */);
86066             }
86067         }
86068         /**
86069          * Enables a more costly code path for substitutions when we determine a source file
86070          * contains a captured `this`.
86071          */
86072         function enableSubstitutionsForCapturedThis() {
86073             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
86074                 enabledSubstitutions |= 1 /* CapturedThis */;
86075                 context.enableSubstitution(104 /* ThisKeyword */);
86076                 context.enableEmitNotification(162 /* Constructor */);
86077                 context.enableEmitNotification(161 /* MethodDeclaration */);
86078                 context.enableEmitNotification(163 /* GetAccessor */);
86079                 context.enableEmitNotification(164 /* SetAccessor */);
86080                 context.enableEmitNotification(202 /* ArrowFunction */);
86081                 context.enableEmitNotification(201 /* FunctionExpression */);
86082                 context.enableEmitNotification(244 /* FunctionDeclaration */);
86083             }
86084         }
86085         /**
86086          * Hooks node substitutions.
86087          *
86088          * @param hint The context for the emitter.
86089          * @param node The node to substitute.
86090          */
86091         function onSubstituteNode(hint, node) {
86092             node = previousOnSubstituteNode(hint, node);
86093             if (hint === 1 /* Expression */) {
86094                 return substituteExpression(node);
86095             }
86096             if (ts.isIdentifier(node)) {
86097                 return substituteIdentifier(node);
86098             }
86099             return node;
86100         }
86101         /**
86102          * Hooks substitutions for non-expression identifiers.
86103          */
86104         function substituteIdentifier(node) {
86105             // Only substitute the identifier if we have enabled substitutions for block-scoped
86106             // bindings.
86107             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86108                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
86109                 if (original && isNameOfDeclarationWithCollidingName(original)) {
86110                     return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
86111                 }
86112             }
86113             return node;
86114         }
86115         /**
86116          * Determines whether a name is the name of a declaration with a colliding name.
86117          * NOTE: This function expects to be called with an original source tree node.
86118          *
86119          * @param node An original source tree node.
86120          */
86121         function isNameOfDeclarationWithCollidingName(node) {
86122             switch (node.parent.kind) {
86123                 case 191 /* BindingElement */:
86124                 case 245 /* ClassDeclaration */:
86125                 case 248 /* EnumDeclaration */:
86126                 case 242 /* VariableDeclaration */:
86127                     return node.parent.name === node
86128                         && resolver.isDeclarationWithCollidingName(node.parent);
86129             }
86130             return false;
86131         }
86132         /**
86133          * Substitutes an expression.
86134          *
86135          * @param node An Expression node.
86136          */
86137         function substituteExpression(node) {
86138             switch (node.kind) {
86139                 case 75 /* Identifier */:
86140                     return substituteExpressionIdentifier(node);
86141                 case 104 /* ThisKeyword */:
86142                     return substituteThisKeyword(node);
86143             }
86144             return node;
86145         }
86146         /**
86147          * Substitutes an expression identifier.
86148          *
86149          * @param node An Identifier node.
86150          */
86151         function substituteExpressionIdentifier(node) {
86152             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86153                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
86154                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
86155                     return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
86156                 }
86157             }
86158             return node;
86159         }
86160         function isPartOfClassBody(declaration, node) {
86161             var currentNode = ts.getParseTreeNode(node);
86162             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
86163                 // if the node has no correlation to a parse tree node, its definitely not
86164                 // part of the body.
86165                 // if the node is outside of the document range of the declaration, its
86166                 // definitely not part of the body.
86167                 return false;
86168             }
86169             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
86170             while (currentNode) {
86171                 if (currentNode === blockScope || currentNode === declaration) {
86172                     // if we are in the enclosing block scope of the declaration, we are definitely
86173                     // not inside the class body.
86174                     return false;
86175                 }
86176                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
86177                     return true;
86178                 }
86179                 currentNode = currentNode.parent;
86180             }
86181             return false;
86182         }
86183         /**
86184          * Substitutes `this` when contained within an arrow function.
86185          *
86186          * @param node The ThisKeyword node.
86187          */
86188         function substituteThisKeyword(node) {
86189             if (enabledSubstitutions & 1 /* CapturedThis */
86190                 && hierarchyFacts & 16 /* CapturesThis */) {
86191                 return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
86192             }
86193             return node;
86194         }
86195         function getClassMemberPrefix(node, member) {
86196             return ts.hasModifier(member, 32 /* Static */)
86197                 ? ts.getInternalName(node)
86198                 : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
86199         }
86200         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
86201             if (!constructor || !hasExtendsClause) {
86202                 return false;
86203             }
86204             if (ts.some(constructor.parameters)) {
86205                 return false;
86206             }
86207             var statement = ts.firstOrUndefined(constructor.body.statements);
86208             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 226 /* ExpressionStatement */) {
86209                 return false;
86210             }
86211             var statementExpression = statement.expression;
86212             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 196 /* CallExpression */) {
86213                 return false;
86214             }
86215             var callTarget = statementExpression.expression;
86216             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 102 /* SuperKeyword */) {
86217                 return false;
86218             }
86219             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
86220             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 213 /* SpreadElement */) {
86221                 return false;
86222             }
86223             var expression = callArgument.expression;
86224             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
86225         }
86226     }
86227     ts.transformES2015 = transformES2015;
86228     function createExtendsHelper(context, name) {
86229         context.requestEmitHelper(ts.extendsHelper);
86230         return ts.createCall(ts.getUnscopedHelperName("__extends"), 
86231         /*typeArguments*/ undefined, [
86232             name,
86233             ts.createFileLevelUniqueName("_super")
86234         ]);
86235     }
86236     ts.extendsHelper = {
86237         name: "typescript:extends",
86238         importName: "__extends",
86239         scoped: false,
86240         priority: 0,
86241         text: "\n            var __extends = (this && this.__extends) || (function () {\n                var extendStatics = function (d, b) {\n                    extendStatics = Object.setPrototypeOf ||\n                        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n                        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n                    return extendStatics(d, b);\n                };\n\n                return function (d, b) {\n                    extendStatics(d, b);\n                    function __() { this.constructor = d; }\n                    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n                };\n            })();"
86242     };
86243 })(ts || (ts = {}));
86244 /*@internal*/
86245 var ts;
86246 (function (ts) {
86247     /**
86248      * Transforms ES5 syntax into ES3 syntax.
86249      *
86250      * @param context Context and state information for the transformation.
86251      */
86252     function transformES5(context) {
86253         var compilerOptions = context.getCompilerOptions();
86254         // enable emit notification only if using --jsx preserve or react-native
86255         var previousOnEmitNode;
86256         var noSubstitution;
86257         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
86258             previousOnEmitNode = context.onEmitNode;
86259             context.onEmitNode = onEmitNode;
86260             context.enableEmitNotification(268 /* JsxOpeningElement */);
86261             context.enableEmitNotification(269 /* JsxClosingElement */);
86262             context.enableEmitNotification(267 /* JsxSelfClosingElement */);
86263             noSubstitution = [];
86264         }
86265         var previousOnSubstituteNode = context.onSubstituteNode;
86266         context.onSubstituteNode = onSubstituteNode;
86267         context.enableSubstitution(194 /* PropertyAccessExpression */);
86268         context.enableSubstitution(281 /* PropertyAssignment */);
86269         return ts.chainBundle(transformSourceFile);
86270         /**
86271          * Transforms an ES5 source file to ES3.
86272          *
86273          * @param node A SourceFile
86274          */
86275         function transformSourceFile(node) {
86276             return node;
86277         }
86278         /**
86279          * Called by the printer just before a node is printed.
86280          *
86281          * @param hint A hint as to the intended usage of the node.
86282          * @param node The node to emit.
86283          * @param emitCallback A callback used to emit the node.
86284          */
86285         function onEmitNode(hint, node, emitCallback) {
86286             switch (node.kind) {
86287                 case 268 /* JsxOpeningElement */:
86288                 case 269 /* JsxClosingElement */:
86289                 case 267 /* JsxSelfClosingElement */:
86290                     var tagName = node.tagName;
86291                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
86292                     break;
86293             }
86294             previousOnEmitNode(hint, node, emitCallback);
86295         }
86296         /**
86297          * Hooks node substitutions.
86298          *
86299          * @param hint A hint as to the intended usage of the node.
86300          * @param node The node to substitute.
86301          */
86302         function onSubstituteNode(hint, node) {
86303             if (node.id && noSubstitution && noSubstitution[node.id]) {
86304                 return previousOnSubstituteNode(hint, node);
86305             }
86306             node = previousOnSubstituteNode(hint, node);
86307             if (ts.isPropertyAccessExpression(node)) {
86308                 return substitutePropertyAccessExpression(node);
86309             }
86310             else if (ts.isPropertyAssignment(node)) {
86311                 return substitutePropertyAssignment(node);
86312             }
86313             return node;
86314         }
86315         /**
86316          * Substitutes a PropertyAccessExpression whose name is a reserved word.
86317          *
86318          * @param node A PropertyAccessExpression
86319          */
86320         function substitutePropertyAccessExpression(node) {
86321             if (ts.isPrivateIdentifier(node.name)) {
86322                 return node;
86323             }
86324             var literalName = trySubstituteReservedName(node.name);
86325             if (literalName) {
86326                 return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
86327             }
86328             return node;
86329         }
86330         /**
86331          * Substitutes a PropertyAssignment whose name is a reserved word.
86332          *
86333          * @param node A PropertyAssignment
86334          */
86335         function substitutePropertyAssignment(node) {
86336             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
86337             if (literalName) {
86338                 return ts.updatePropertyAssignment(node, literalName, node.initializer);
86339             }
86340             return node;
86341         }
86342         /**
86343          * If an identifier name is a reserved word, returns a string literal for the name.
86344          *
86345          * @param name An Identifier
86346          */
86347         function trySubstituteReservedName(name) {
86348             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
86349             if (token !== undefined && token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */) {
86350                 return ts.setTextRange(ts.createLiteral(name), name);
86351             }
86352             return undefined;
86353         }
86354     }
86355     ts.transformES5 = transformES5;
86356 })(ts || (ts = {}));
86357 // Transforms generator functions into a compatible ES5 representation with similar runtime
86358 // semantics. This is accomplished by first transforming the body of each generator
86359 // function into an intermediate representation that is the compiled into a JavaScript
86360 // switch statement.
86361 //
86362 // Many functions in this transformer will contain comments indicating the expected
86363 // intermediate representation. For illustrative purposes, the following intermediate
86364 // language is used to define this intermediate representation:
86365 //
86366 //  .nop                            - Performs no operation.
86367 //  .local NAME, ...                - Define local variable declarations.
86368 //  .mark LABEL                     - Mark the location of a label.
86369 //  .br LABEL                       - Jump to a label. If jumping out of a protected
86370 //                                    region, all .finally blocks are executed.
86371 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
86372 //                                    If jumping out of a protected region, all .finally
86373 //                                    blocks are executed.
86374 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
86375 //                                    If jumping out of a protected region, all .finally
86376 //                                    blocks are executed.
86377 //  .yield (x)                      - Yield the value of the optional expression `x`.
86378 //                                    Resume at the next label.
86379 //  .yieldstar (x)                  - Delegate yield to the value of the optional
86380 //                                    expression `x`. Resume at the next label.
86381 //                                    NOTE: `x` must be an Iterator, not an Iterable.
86382 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
86383 //                                    "break" abrupt completions jump to the CONTINUE or
86384 //                                    BREAK labels, respectively.
86385 //  .endloop                        - Marks the end of a loop.
86386 //  .with (x)                       - Marks the beginning of a WithStatement block, using
86387 //                                    the supplied expression.
86388 //  .endwith                        - Marks the end of a WithStatement.
86389 //  .switch                         - Marks the beginning of a SwitchStatement.
86390 //  .endswitch                      - Marks the end of a SwitchStatement.
86391 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
86392 //                                    supplied name.
86393 //  .endlabeled                     - Marks the end of a LabeledStatement.
86394 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
86395 //                                    labels for each block.
86396 //  .catch (x)                      - Marks the beginning of a catch block.
86397 //  .finally                        - Marks the beginning of a finally block.
86398 //  .endfinally                     - Marks the end of a finally block.
86399 //  .endtry                         - Marks the end of a protected region.
86400 //  .throw (x)                      - Throws the value of the expression `x`.
86401 //  .return (x)                     - Returns the value of the expression `x`.
86402 //
86403 // In addition, the illustrative intermediate representation introduces some special
86404 // variables:
86405 //
86406 //  %sent%                          - Either returns the next value sent to the generator,
86407 //                                    returns the result of a delegated yield, or throws
86408 //                                    the exception sent to the generator.
86409 //  %error%                         - Returns the value of the current exception in a
86410 //                                    catch block.
86411 //
86412 // This intermediate representation is then compiled into JavaScript syntax. The resulting
86413 // compilation output looks something like the following:
86414 //
86415 //  function f() {
86416 //      var /*locals*/;
86417 //      /*functions*/
86418 //      return __generator(function (state) {
86419 //          switch (state.label) {
86420 //              /*cases per label*/
86421 //          }
86422 //      });
86423 //  }
86424 //
86425 // Each of the above instructions corresponds to JavaScript emit similar to the following:
86426 //
86427 //  .local NAME                   | var NAME;
86428 // -------------------------------|----------------------------------------------
86429 //  .mark LABEL                   | case LABEL:
86430 // -------------------------------|----------------------------------------------
86431 //  .br LABEL                     |     return [3 /*break*/, LABEL];
86432 // -------------------------------|----------------------------------------------
86433 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
86434 // -------------------------------|----------------------------------------------
86435 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
86436 // -------------------------------|----------------------------------------------
86437 //  .yield (x)                    |     return [4 /*yield*/, x];
86438 //  .mark RESUME                  | case RESUME:
86439 //      a = %sent%;               |     a = state.sent();
86440 // -------------------------------|----------------------------------------------
86441 //  .yieldstar (x)                |     return [5 /*yield**/, x];
86442 //  .mark RESUME                  | case RESUME:
86443 //      a = %sent%;               |     a = state.sent();
86444 // -------------------------------|----------------------------------------------
86445 //  .with (_a)                    |     with (_a) {
86446 //      a();                      |         a();
86447 //                                |     }
86448 //                                |     state.label = LABEL;
86449 //  .mark LABEL                   | case LABEL:
86450 //                                |     with (_a) {
86451 //      b();                      |         b();
86452 //                                |     }
86453 //  .endwith                      |
86454 // -------------------------------|----------------------------------------------
86455 //                                | case 0:
86456 //                                |     state.trys = [];
86457 //                                | ...
86458 //  .try TRY, CATCH, FINALLY, END |
86459 //  .mark TRY                     | case TRY:
86460 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
86461 //  .nop                          |
86462 //      a();                      |     a();
86463 //  .br END                       |     return [3 /*break*/, END];
86464 //  .catch (e)                    |
86465 //  .mark CATCH                   | case CATCH:
86466 //                                |     e = state.sent();
86467 //      b();                      |     b();
86468 //  .br END                       |     return [3 /*break*/, END];
86469 //  .finally                      |
86470 //  .mark FINALLY                 | case FINALLY:
86471 //      c();                      |     c();
86472 //  .endfinally                   |     return [7 /*endfinally*/];
86473 //  .endtry                       |
86474 //  .mark END                     | case END:
86475 /*@internal*/
86476 var ts;
86477 (function (ts) {
86478     var OpCode;
86479     (function (OpCode) {
86480         OpCode[OpCode["Nop"] = 0] = "Nop";
86481         OpCode[OpCode["Statement"] = 1] = "Statement";
86482         OpCode[OpCode["Assign"] = 2] = "Assign";
86483         OpCode[OpCode["Break"] = 3] = "Break";
86484         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
86485         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
86486         OpCode[OpCode["Yield"] = 6] = "Yield";
86487         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
86488         OpCode[OpCode["Return"] = 8] = "Return";
86489         OpCode[OpCode["Throw"] = 9] = "Throw";
86490         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
86491     })(OpCode || (OpCode = {}));
86492     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
86493     var BlockAction;
86494     (function (BlockAction) {
86495         BlockAction[BlockAction["Open"] = 0] = "Open";
86496         BlockAction[BlockAction["Close"] = 1] = "Close";
86497     })(BlockAction || (BlockAction = {}));
86498     // the kind for a generated code block in a FunctionBuilder
86499     var CodeBlockKind;
86500     (function (CodeBlockKind) {
86501         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
86502         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
86503         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
86504         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
86505         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
86506     })(CodeBlockKind || (CodeBlockKind = {}));
86507     // the state for a generated code exception block
86508     var ExceptionBlockState;
86509     (function (ExceptionBlockState) {
86510         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
86511         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
86512         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
86513         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
86514     })(ExceptionBlockState || (ExceptionBlockState = {}));
86515     // NOTE: changes to this enum should be reflected in the __generator helper.
86516     var Instruction;
86517     (function (Instruction) {
86518         Instruction[Instruction["Next"] = 0] = "Next";
86519         Instruction[Instruction["Throw"] = 1] = "Throw";
86520         Instruction[Instruction["Return"] = 2] = "Return";
86521         Instruction[Instruction["Break"] = 3] = "Break";
86522         Instruction[Instruction["Yield"] = 4] = "Yield";
86523         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
86524         Instruction[Instruction["Catch"] = 6] = "Catch";
86525         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
86526     })(Instruction || (Instruction = {}));
86527     function getInstructionName(instruction) {
86528         switch (instruction) {
86529             case 2 /* Return */: return "return";
86530             case 3 /* Break */: return "break";
86531             case 4 /* Yield */: return "yield";
86532             case 5 /* YieldStar */: return "yield*";
86533             case 7 /* Endfinally */: return "endfinally";
86534             default: return undefined; // TODO: GH#18217
86535         }
86536     }
86537     function transformGenerators(context) {
86538         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
86539         var compilerOptions = context.getCompilerOptions();
86540         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86541         var resolver = context.getEmitResolver();
86542         var previousOnSubstituteNode = context.onSubstituteNode;
86543         context.onSubstituteNode = onSubstituteNode;
86544         var renamedCatchVariables;
86545         var renamedCatchVariableDeclarations;
86546         var inGeneratorFunctionBody;
86547         var inStatementContainingYield;
86548         // The following three arrays store information about generated code blocks.
86549         // All three arrays are correlated by their index. This approach is used over allocating
86550         // objects to store the same information to avoid GC overhead.
86551         //
86552         var blocks; // Information about the code block
86553         var blockOffsets; // The operation offset at which a code block begins or ends
86554         var blockActions; // Whether the code block is opened or closed
86555         var blockStack; // A stack of currently open code blocks
86556         // Labels are used to mark locations in the code that can be the target of a Break (jump)
86557         // operation. These are translated into case clauses in a switch statement.
86558         // The following two arrays are correlated by their index. This approach is used over
86559         // allocating objects to store the same information to avoid GC overhead.
86560         //
86561         var labelOffsets; // The operation offset at which the label is defined.
86562         var labelExpressions; // The NumericLiteral nodes bound to each label.
86563         var nextLabelId = 1; // The next label id to use.
86564         // Operations store information about generated code for the function body. This
86565         // Includes things like statements, assignments, breaks (jumps), and yields.
86566         // The following three arrays are correlated by their index. This approach is used over
86567         // allocating objects to store the same information to avoid GC overhead.
86568         //
86569         var operations; // The operation to perform.
86570         var operationArguments; // The arguments to the operation.
86571         var operationLocations; // The source map location for the operation.
86572         var state; // The name of the state object used by the generator at runtime.
86573         // The following variables store information used by the `build` function:
86574         //
86575         var blockIndex = 0; // The index of the current block.
86576         var labelNumber = 0; // The current label number.
86577         var labelNumbers;
86578         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
86579         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
86580         var clauses; // The case clauses generated for labels.
86581         var statements; // The statements for the current label.
86582         var exceptionBlockStack; // A stack of containing exception blocks.
86583         var currentExceptionBlock; // The current exception block.
86584         var withBlockStack; // A stack containing `with` blocks.
86585         return ts.chainBundle(transformSourceFile);
86586         function transformSourceFile(node) {
86587             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
86588                 return node;
86589             }
86590             var visited = ts.visitEachChild(node, visitor, context);
86591             ts.addEmitHelpers(visited, context.readEmitHelpers());
86592             return visited;
86593         }
86594         /**
86595          * Visits a node.
86596          *
86597          * @param node The node to visit.
86598          */
86599         function visitor(node) {
86600             var transformFlags = node.transformFlags;
86601             if (inStatementContainingYield) {
86602                 return visitJavaScriptInStatementContainingYield(node);
86603             }
86604             else if (inGeneratorFunctionBody) {
86605                 return visitJavaScriptInGeneratorFunctionBody(node);
86606             }
86607             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
86608                 return visitGenerator(node);
86609             }
86610             else if (transformFlags & 512 /* ContainsGenerator */) {
86611                 return ts.visitEachChild(node, visitor, context);
86612             }
86613             else {
86614                 return node;
86615             }
86616         }
86617         /**
86618          * Visits a node that is contained within a statement that contains yield.
86619          *
86620          * @param node The node to visit.
86621          */
86622         function visitJavaScriptInStatementContainingYield(node) {
86623             switch (node.kind) {
86624                 case 228 /* DoStatement */:
86625                     return visitDoStatement(node);
86626                 case 229 /* WhileStatement */:
86627                     return visitWhileStatement(node);
86628                 case 237 /* SwitchStatement */:
86629                     return visitSwitchStatement(node);
86630                 case 238 /* LabeledStatement */:
86631                     return visitLabeledStatement(node);
86632                 default:
86633                     return visitJavaScriptInGeneratorFunctionBody(node);
86634             }
86635         }
86636         /**
86637          * Visits a node that is contained within a generator function.
86638          *
86639          * @param node The node to visit.
86640          */
86641         function visitJavaScriptInGeneratorFunctionBody(node) {
86642             switch (node.kind) {
86643                 case 244 /* FunctionDeclaration */:
86644                     return visitFunctionDeclaration(node);
86645                 case 201 /* FunctionExpression */:
86646                     return visitFunctionExpression(node);
86647                 case 163 /* GetAccessor */:
86648                 case 164 /* SetAccessor */:
86649                     return visitAccessorDeclaration(node);
86650                 case 225 /* VariableStatement */:
86651                     return visitVariableStatement(node);
86652                 case 230 /* ForStatement */:
86653                     return visitForStatement(node);
86654                 case 231 /* ForInStatement */:
86655                     return visitForInStatement(node);
86656                 case 234 /* BreakStatement */:
86657                     return visitBreakStatement(node);
86658                 case 233 /* ContinueStatement */:
86659                     return visitContinueStatement(node);
86660                 case 235 /* ReturnStatement */:
86661                     return visitReturnStatement(node);
86662                 default:
86663                     if (node.transformFlags & 262144 /* ContainsYield */) {
86664                         return visitJavaScriptContainingYield(node);
86665                     }
86666                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
86667                         return ts.visitEachChild(node, visitor, context);
86668                     }
86669                     else {
86670                         return node;
86671                     }
86672             }
86673         }
86674         /**
86675          * Visits a node that contains a YieldExpression.
86676          *
86677          * @param node The node to visit.
86678          */
86679         function visitJavaScriptContainingYield(node) {
86680             switch (node.kind) {
86681                 case 209 /* BinaryExpression */:
86682                     return visitBinaryExpression(node);
86683                 case 210 /* ConditionalExpression */:
86684                     return visitConditionalExpression(node);
86685                 case 212 /* YieldExpression */:
86686                     return visitYieldExpression(node);
86687                 case 192 /* ArrayLiteralExpression */:
86688                     return visitArrayLiteralExpression(node);
86689                 case 193 /* ObjectLiteralExpression */:
86690                     return visitObjectLiteralExpression(node);
86691                 case 195 /* ElementAccessExpression */:
86692                     return visitElementAccessExpression(node);
86693                 case 196 /* CallExpression */:
86694                     return visitCallExpression(node);
86695                 case 197 /* NewExpression */:
86696                     return visitNewExpression(node);
86697                 default:
86698                     return ts.visitEachChild(node, visitor, context);
86699             }
86700         }
86701         /**
86702          * Visits a generator function.
86703          *
86704          * @param node The node to visit.
86705          */
86706         function visitGenerator(node) {
86707             switch (node.kind) {
86708                 case 244 /* FunctionDeclaration */:
86709                     return visitFunctionDeclaration(node);
86710                 case 201 /* FunctionExpression */:
86711                     return visitFunctionExpression(node);
86712                 default:
86713                     return ts.Debug.failBadSyntaxKind(node);
86714             }
86715         }
86716         /**
86717          * Visits a function declaration.
86718          *
86719          * This will be called when one of the following conditions are met:
86720          * - The function declaration is a generator function.
86721          * - The function declaration is contained within the body of a generator function.
86722          *
86723          * @param node The node to visit.
86724          */
86725         function visitFunctionDeclaration(node) {
86726             // Currently, we only support generators that were originally async functions.
86727             if (node.asteriskToken) {
86728                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
86729                 /*decorators*/ undefined, node.modifiers, 
86730                 /*asteriskToken*/ undefined, node.name, 
86731                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86732                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86733                 /*location*/ node), node);
86734             }
86735             else {
86736                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86737                 var savedInStatementContainingYield = inStatementContainingYield;
86738                 inGeneratorFunctionBody = false;
86739                 inStatementContainingYield = false;
86740                 node = ts.visitEachChild(node, visitor, context);
86741                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86742                 inStatementContainingYield = savedInStatementContainingYield;
86743             }
86744             if (inGeneratorFunctionBody) {
86745                 // Function declarations in a generator function body are hoisted
86746                 // to the top of the lexical scope and elided from the current statement.
86747                 hoistFunctionDeclaration(node);
86748                 return undefined;
86749             }
86750             else {
86751                 return node;
86752             }
86753         }
86754         /**
86755          * Visits a function expression.
86756          *
86757          * This will be called when one of the following conditions are met:
86758          * - The function expression is a generator function.
86759          * - The function expression is contained within the body of a generator function.
86760          *
86761          * @param node The node to visit.
86762          */
86763         function visitFunctionExpression(node) {
86764             // Currently, we only support generators that were originally async functions.
86765             if (node.asteriskToken) {
86766                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
86767                 /*modifiers*/ undefined, 
86768                 /*asteriskToken*/ undefined, node.name, 
86769                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86770                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86771                 /*location*/ node), node);
86772             }
86773             else {
86774                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86775                 var savedInStatementContainingYield = inStatementContainingYield;
86776                 inGeneratorFunctionBody = false;
86777                 inStatementContainingYield = false;
86778                 node = ts.visitEachChild(node, visitor, context);
86779                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86780                 inStatementContainingYield = savedInStatementContainingYield;
86781             }
86782             return node;
86783         }
86784         /**
86785          * Visits a get or set accessor declaration.
86786          *
86787          * This will be called when one of the following conditions are met:
86788          * - The accessor is contained within the body of a generator function.
86789          *
86790          * @param node The node to visit.
86791          */
86792         function visitAccessorDeclaration(node) {
86793             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86794             var savedInStatementContainingYield = inStatementContainingYield;
86795             inGeneratorFunctionBody = false;
86796             inStatementContainingYield = false;
86797             node = ts.visitEachChild(node, visitor, context);
86798             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86799             inStatementContainingYield = savedInStatementContainingYield;
86800             return node;
86801         }
86802         /**
86803          * Transforms the body of a generator function declaration.
86804          *
86805          * @param node The function body to transform.
86806          */
86807         function transformGeneratorFunctionBody(body) {
86808             // Save existing generator state
86809             var statements = [];
86810             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86811             var savedInStatementContainingYield = inStatementContainingYield;
86812             var savedBlocks = blocks;
86813             var savedBlockOffsets = blockOffsets;
86814             var savedBlockActions = blockActions;
86815             var savedBlockStack = blockStack;
86816             var savedLabelOffsets = labelOffsets;
86817             var savedLabelExpressions = labelExpressions;
86818             var savedNextLabelId = nextLabelId;
86819             var savedOperations = operations;
86820             var savedOperationArguments = operationArguments;
86821             var savedOperationLocations = operationLocations;
86822             var savedState = state;
86823             // Initialize generator state
86824             inGeneratorFunctionBody = true;
86825             inStatementContainingYield = false;
86826             blocks = undefined;
86827             blockOffsets = undefined;
86828             blockActions = undefined;
86829             blockStack = undefined;
86830             labelOffsets = undefined;
86831             labelExpressions = undefined;
86832             nextLabelId = 1;
86833             operations = undefined;
86834             operationArguments = undefined;
86835             operationLocations = undefined;
86836             state = ts.createTempVariable(/*recordTempVariable*/ undefined);
86837             // Build the generator
86838             resumeLexicalEnvironment();
86839             var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
86840             transformAndEmitStatements(body.statements, statementOffset);
86841             var buildResult = build();
86842             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86843             statements.push(ts.createReturn(buildResult));
86844             // Restore previous generator state
86845             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86846             inStatementContainingYield = savedInStatementContainingYield;
86847             blocks = savedBlocks;
86848             blockOffsets = savedBlockOffsets;
86849             blockActions = savedBlockActions;
86850             blockStack = savedBlockStack;
86851             labelOffsets = savedLabelOffsets;
86852             labelExpressions = savedLabelExpressions;
86853             nextLabelId = savedNextLabelId;
86854             operations = savedOperations;
86855             operationArguments = savedOperationArguments;
86856             operationLocations = savedOperationLocations;
86857             state = savedState;
86858             return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
86859         }
86860         /**
86861          * Visits a variable statement.
86862          *
86863          * This will be called when one of the following conditions are met:
86864          * - The variable statement is contained within the body of a generator function.
86865          *
86866          * @param node The node to visit.
86867          */
86868         function visitVariableStatement(node) {
86869             if (node.transformFlags & 262144 /* ContainsYield */) {
86870                 transformAndEmitVariableDeclarationList(node.declarationList);
86871                 return undefined;
86872             }
86873             else {
86874                 // Do not hoist custom prologues.
86875                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
86876                     return node;
86877                 }
86878                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
86879                     var variable = _a[_i];
86880                     hoistVariableDeclaration(variable.name);
86881                 }
86882                 var variables = ts.getInitializedVariables(node.declarationList);
86883                 if (variables.length === 0) {
86884                     return undefined;
86885                 }
86886                 return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
86887             }
86888         }
86889         /**
86890          * Visits a binary expression.
86891          *
86892          * This will be called when one of the following conditions are met:
86893          * - The node contains a YieldExpression.
86894          *
86895          * @param node The node to visit.
86896          */
86897         function visitBinaryExpression(node) {
86898             var assoc = ts.getExpressionAssociativity(node);
86899             switch (assoc) {
86900                 case 0 /* Left */:
86901                     return visitLeftAssociativeBinaryExpression(node);
86902                 case 1 /* Right */:
86903                     return visitRightAssociativeBinaryExpression(node);
86904                 default:
86905                     return ts.Debug.assertNever(assoc);
86906             }
86907         }
86908         /**
86909          * Visits a right-associative binary expression containing `yield`.
86910          *
86911          * @param node The node to visit.
86912          */
86913         function visitRightAssociativeBinaryExpression(node) {
86914             var left = node.left, right = node.right;
86915             if (containsYield(right)) {
86916                 var target = void 0;
86917                 switch (left.kind) {
86918                     case 194 /* PropertyAccessExpression */:
86919                         // [source]
86920                         //      a.b = yield;
86921                         //
86922                         // [intermediate]
86923                         //  .local _a
86924                         //      _a = a;
86925                         //  .yield resumeLabel
86926                         //  .mark resumeLabel
86927                         //      _a.b = %sent%;
86928                         target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
86929                         break;
86930                     case 195 /* ElementAccessExpression */:
86931                         // [source]
86932                         //      a[b] = yield;
86933                         //
86934                         // [intermediate]
86935                         //  .local _a, _b
86936                         //      _a = a;
86937                         //      _b = b;
86938                         //  .yield resumeLabel
86939                         //  .mark resumeLabel
86940                         //      _a[_b] = %sent%;
86941                         target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
86942                         break;
86943                     default:
86944                         target = ts.visitNode(left, visitor, ts.isExpression);
86945                         break;
86946                 }
86947                 var operator = node.operatorToken.kind;
86948                 if (ts.isCompoundAssignment(operator)) {
86949                     return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
86950                 }
86951                 else {
86952                     return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
86953                 }
86954             }
86955             return ts.visitEachChild(node, visitor, context);
86956         }
86957         function visitLeftAssociativeBinaryExpression(node) {
86958             if (containsYield(node.right)) {
86959                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
86960                     return visitLogicalBinaryExpression(node);
86961                 }
86962                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
86963                     return visitCommaExpression(node);
86964                 }
86965                 // [source]
86966                 //      a() + (yield) + c()
86967                 //
86968                 // [intermediate]
86969                 //  .local _a
86970                 //      _a = a();
86971                 //  .yield resumeLabel
86972                 //      _a + %sent% + c()
86973                 var clone_6 = ts.getMutableClone(node);
86974                 clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
86975                 clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression);
86976                 return clone_6;
86977             }
86978             return ts.visitEachChild(node, visitor, context);
86979         }
86980         /**
86981          * Visits a logical binary expression containing `yield`.
86982          *
86983          * @param node A node to visit.
86984          */
86985         function visitLogicalBinaryExpression(node) {
86986             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
86987             // to be transformed as such:
86988             //
86989             // [source]
86990             //      x = a() && yield;
86991             //
86992             // [intermediate]
86993             //  .local _a
86994             //      _a = a();
86995             //  .brfalse resultLabel, (_a)
86996             //  .yield resumeLabel
86997             //  .mark resumeLabel
86998             //      _a = %sent%;
86999             //  .mark resultLabel
87000             //      x = _a;
87001             //
87002             // [source]
87003             //      x = a() || yield;
87004             //
87005             // [intermediate]
87006             //  .local _a
87007             //      _a = a();
87008             //  .brtrue resultLabel, (_a)
87009             //  .yield resumeLabel
87010             //  .mark resumeLabel
87011             //      _a = %sent%;
87012             //  .mark resultLabel
87013             //      x = _a;
87014             var resultLabel = defineLabel();
87015             var resultLocal = declareLocal();
87016             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
87017             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
87018                 // Logical `&&` shortcuts when the left-hand operand is falsey.
87019                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
87020             }
87021             else {
87022                 // Logical `||` shortcuts when the left-hand operand is truthy.
87023                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
87024             }
87025             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
87026             markLabel(resultLabel);
87027             return resultLocal;
87028         }
87029         /**
87030          * Visits a comma expression containing `yield`.
87031          *
87032          * @param node The node to visit.
87033          */
87034         function visitCommaExpression(node) {
87035             // [source]
87036             //      x = a(), yield, b();
87037             //
87038             // [intermediate]
87039             //      a();
87040             //  .yield resumeLabel
87041             //  .mark resumeLabel
87042             //      x = %sent%, b();
87043             var pendingExpressions = [];
87044             visit(node.left);
87045             visit(node.right);
87046             return ts.inlineExpressions(pendingExpressions);
87047             function visit(node) {
87048                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
87049                     visit(node.left);
87050                     visit(node.right);
87051                 }
87052                 else {
87053                     if (containsYield(node) && pendingExpressions.length > 0) {
87054                         emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
87055                         pendingExpressions = [];
87056                     }
87057                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
87058                 }
87059             }
87060         }
87061         /**
87062          * Visits a conditional expression containing `yield`.
87063          *
87064          * @param node The node to visit.
87065          */
87066         function visitConditionalExpression(node) {
87067             // [source]
87068             //      x = a() ? yield : b();
87069             //
87070             // [intermediate]
87071             //  .local _a
87072             //  .brfalse whenFalseLabel, (a())
87073             //  .yield resumeLabel
87074             //  .mark resumeLabel
87075             //      _a = %sent%;
87076             //  .br resultLabel
87077             //  .mark whenFalseLabel
87078             //      _a = b();
87079             //  .mark resultLabel
87080             //      x = _a;
87081             // We only need to perform a specific transformation if a `yield` expression exists
87082             // in either the `whenTrue` or `whenFalse` branches.
87083             // A `yield` in the condition will be handled by the normal visitor.
87084             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
87085                 var whenFalseLabel = defineLabel();
87086                 var resultLabel = defineLabel();
87087                 var resultLocal = declareLocal();
87088                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
87089                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
87090                 emitBreak(resultLabel);
87091                 markLabel(whenFalseLabel);
87092                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
87093                 markLabel(resultLabel);
87094                 return resultLocal;
87095             }
87096             return ts.visitEachChild(node, visitor, context);
87097         }
87098         /**
87099          * Visits a `yield` expression.
87100          *
87101          * @param node The node to visit.
87102          */
87103         function visitYieldExpression(node) {
87104             // [source]
87105             //      x = yield a();
87106             //
87107             // [intermediate]
87108             //  .yield resumeLabel, (a())
87109             //  .mark resumeLabel
87110             //      x = %sent%;
87111             var resumeLabel = defineLabel();
87112             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87113             if (node.asteriskToken) {
87114                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
87115                     ? ts.createValuesHelper(context, expression, /*location*/ node)
87116                     : expression;
87117                 emitYieldStar(iterator, /*location*/ node);
87118             }
87119             else {
87120                 emitYield(expression, /*location*/ node);
87121             }
87122             markLabel(resumeLabel);
87123             return createGeneratorResume(/*location*/ node);
87124         }
87125         /**
87126          * Visits an ArrayLiteralExpression that contains a YieldExpression.
87127          *
87128          * @param node The node to visit.
87129          */
87130         function visitArrayLiteralExpression(node) {
87131             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
87132         }
87133         /**
87134          * Visits an array of expressions containing one or more YieldExpression nodes
87135          * and returns an expression for the resulting value.
87136          *
87137          * @param elements The elements to visit.
87138          * @param multiLine Whether array literals created should be emitted on multiple lines.
87139          */
87140         function visitElements(elements, leadingElement, location, multiLine) {
87141             // [source]
87142             //      ar = [1, yield, 2];
87143             //
87144             // [intermediate]
87145             //  .local _a
87146             //      _a = [1];
87147             //  .yield resumeLabel
87148             //  .mark resumeLabel
87149             //      ar = _a.concat([%sent%, 2]);
87150             var numInitialElements = countInitialNodesWithoutYield(elements);
87151             var temp;
87152             if (numInitialElements > 0) {
87153                 temp = declareLocal();
87154                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
87155                 emitAssignment(temp, ts.createArrayLiteral(leadingElement
87156                     ? __spreadArrays([leadingElement], initialElements) : initialElements));
87157                 leadingElement = undefined;
87158             }
87159             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
87160             return temp
87161                 ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87162                 : ts.setTextRange(ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
87163             function reduceElement(expressions, element) {
87164                 if (containsYield(element) && expressions.length > 0) {
87165                     var hasAssignedTemp = temp !== undefined;
87166                     if (!temp) {
87167                         temp = declareLocal();
87168                     }
87169                     emitAssignment(temp, hasAssignedTemp
87170                         ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87171                         : ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
87172                     leadingElement = undefined;
87173                     expressions = [];
87174                 }
87175                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
87176                 return expressions;
87177             }
87178         }
87179         function visitObjectLiteralExpression(node) {
87180             // [source]
87181             //      o = {
87182             //          a: 1,
87183             //          b: yield,
87184             //          c: 2
87185             //      };
87186             //
87187             // [intermediate]
87188             //  .local _a
87189             //      _a = {
87190             //          a: 1
87191             //      };
87192             //  .yield resumeLabel
87193             //  .mark resumeLabel
87194             //      o = (_a.b = %sent%,
87195             //          _a.c = 2,
87196             //          _a);
87197             var properties = node.properties;
87198             var multiLine = node.multiLine;
87199             var numInitialProperties = countInitialNodesWithoutYield(properties);
87200             var temp = declareLocal();
87201             emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
87202             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
87203             expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
87204             return ts.inlineExpressions(expressions);
87205             function reduceProperty(expressions, property) {
87206                 if (containsYield(property) && expressions.length > 0) {
87207                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
87208                     expressions = [];
87209                 }
87210                 var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
87211                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
87212                 if (visited) {
87213                     if (multiLine) {
87214                         ts.startOnNewLine(visited);
87215                     }
87216                     expressions.push(visited);
87217                 }
87218                 return expressions;
87219             }
87220         }
87221         /**
87222          * Visits an ElementAccessExpression that contains a YieldExpression.
87223          *
87224          * @param node The node to visit.
87225          */
87226         function visitElementAccessExpression(node) {
87227             if (containsYield(node.argumentExpression)) {
87228                 // [source]
87229                 //      a = x[yield];
87230                 //
87231                 // [intermediate]
87232                 //  .local _a
87233                 //      _a = x;
87234                 //  .yield resumeLabel
87235                 //  .mark resumeLabel
87236                 //      a = _a[%sent%]
87237                 var clone_7 = ts.getMutableClone(node);
87238                 clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
87239                 clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
87240                 return clone_7;
87241             }
87242             return ts.visitEachChild(node, visitor, context);
87243         }
87244         function visitCallExpression(node) {
87245             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
87246                 // [source]
87247                 //      a.b(1, yield, 2);
87248                 //
87249                 // [intermediate]
87250                 //  .local _a, _b, _c
87251                 //      _b = (_a = a).b;
87252                 //      _c = [1];
87253                 //  .yield resumeLabel
87254                 //  .mark resumeLabel
87255                 //      _b.apply(_a, _c.concat([%sent%, 2]));
87256                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
87257                 return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), 
87258                 /*location*/ node), node);
87259             }
87260             return ts.visitEachChild(node, visitor, context);
87261         }
87262         function visitNewExpression(node) {
87263             if (ts.forEach(node.arguments, containsYield)) {
87264                 // [source]
87265                 //      new a.b(1, yield, 2);
87266                 //
87267                 // [intermediate]
87268                 //  .local _a, _b, _c
87269                 //      _b = (_a = a.b).bind;
87270                 //      _c = [1];
87271                 //  .yield resumeLabel
87272                 //  .mark resumeLabel
87273                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
87274                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
87275                 return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
87276                 /*leadingElement*/ ts.createVoidZero())), 
87277                 /*typeArguments*/ undefined, []), node), node);
87278             }
87279             return ts.visitEachChild(node, visitor, context);
87280         }
87281         function transformAndEmitStatements(statements, start) {
87282             if (start === void 0) { start = 0; }
87283             var numStatements = statements.length;
87284             for (var i = start; i < numStatements; i++) {
87285                 transformAndEmitStatement(statements[i]);
87286             }
87287         }
87288         function transformAndEmitEmbeddedStatement(node) {
87289             if (ts.isBlock(node)) {
87290                 transformAndEmitStatements(node.statements);
87291             }
87292             else {
87293                 transformAndEmitStatement(node);
87294             }
87295         }
87296         function transformAndEmitStatement(node) {
87297             var savedInStatementContainingYield = inStatementContainingYield;
87298             if (!inStatementContainingYield) {
87299                 inStatementContainingYield = containsYield(node);
87300             }
87301             transformAndEmitStatementWorker(node);
87302             inStatementContainingYield = savedInStatementContainingYield;
87303         }
87304         function transformAndEmitStatementWorker(node) {
87305             switch (node.kind) {
87306                 case 223 /* Block */:
87307                     return transformAndEmitBlock(node);
87308                 case 226 /* ExpressionStatement */:
87309                     return transformAndEmitExpressionStatement(node);
87310                 case 227 /* IfStatement */:
87311                     return transformAndEmitIfStatement(node);
87312                 case 228 /* DoStatement */:
87313                     return transformAndEmitDoStatement(node);
87314                 case 229 /* WhileStatement */:
87315                     return transformAndEmitWhileStatement(node);
87316                 case 230 /* ForStatement */:
87317                     return transformAndEmitForStatement(node);
87318                 case 231 /* ForInStatement */:
87319                     return transformAndEmitForInStatement(node);
87320                 case 233 /* ContinueStatement */:
87321                     return transformAndEmitContinueStatement(node);
87322                 case 234 /* BreakStatement */:
87323                     return transformAndEmitBreakStatement(node);
87324                 case 235 /* ReturnStatement */:
87325                     return transformAndEmitReturnStatement(node);
87326                 case 236 /* WithStatement */:
87327                     return transformAndEmitWithStatement(node);
87328                 case 237 /* SwitchStatement */:
87329                     return transformAndEmitSwitchStatement(node);
87330                 case 238 /* LabeledStatement */:
87331                     return transformAndEmitLabeledStatement(node);
87332                 case 239 /* ThrowStatement */:
87333                     return transformAndEmitThrowStatement(node);
87334                 case 240 /* TryStatement */:
87335                     return transformAndEmitTryStatement(node);
87336                 default:
87337                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87338             }
87339         }
87340         function transformAndEmitBlock(node) {
87341             if (containsYield(node)) {
87342                 transformAndEmitStatements(node.statements);
87343             }
87344             else {
87345                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87346             }
87347         }
87348         function transformAndEmitExpressionStatement(node) {
87349             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87350         }
87351         function transformAndEmitVariableDeclarationList(node) {
87352             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
87353                 var variable = _a[_i];
87354                 var name = ts.getSynthesizedClone(variable.name);
87355                 ts.setCommentRange(name, variable.name);
87356                 hoistVariableDeclaration(name);
87357             }
87358             var variables = ts.getInitializedVariables(node);
87359             var numVariables = variables.length;
87360             var variablesWritten = 0;
87361             var pendingExpressions = [];
87362             while (variablesWritten < numVariables) {
87363                 for (var i = variablesWritten; i < numVariables; i++) {
87364                     var variable = variables[i];
87365                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
87366                         break;
87367                     }
87368                     pendingExpressions.push(transformInitializedVariable(variable));
87369                 }
87370                 if (pendingExpressions.length) {
87371                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
87372                     variablesWritten += pendingExpressions.length;
87373                     pendingExpressions = [];
87374                 }
87375             }
87376             return undefined;
87377         }
87378         function transformInitializedVariable(node) {
87379             return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
87380         }
87381         function transformAndEmitIfStatement(node) {
87382             if (containsYield(node)) {
87383                 // [source]
87384                 //      if (x)
87385                 //          /*thenStatement*/
87386                 //      else
87387                 //          /*elseStatement*/
87388                 //
87389                 // [intermediate]
87390                 //  .brfalse elseLabel, (x)
87391                 //      /*thenStatement*/
87392                 //  .br endLabel
87393                 //  .mark elseLabel
87394                 //      /*elseStatement*/
87395                 //  .mark endLabel
87396                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
87397                     var endLabel = defineLabel();
87398                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
87399                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
87400                     transformAndEmitEmbeddedStatement(node.thenStatement);
87401                     if (node.elseStatement) {
87402                         emitBreak(endLabel);
87403                         markLabel(elseLabel);
87404                         transformAndEmitEmbeddedStatement(node.elseStatement);
87405                     }
87406                     markLabel(endLabel);
87407                 }
87408                 else {
87409                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87410                 }
87411             }
87412             else {
87413                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87414             }
87415         }
87416         function transformAndEmitDoStatement(node) {
87417             if (containsYield(node)) {
87418                 // [source]
87419                 //      do {
87420                 //          /*body*/
87421                 //      }
87422                 //      while (i < 10);
87423                 //
87424                 // [intermediate]
87425                 //  .loop conditionLabel, endLabel
87426                 //  .mark loopLabel
87427                 //      /*body*/
87428                 //  .mark conditionLabel
87429                 //  .brtrue loopLabel, (i < 10)
87430                 //  .endloop
87431                 //  .mark endLabel
87432                 var conditionLabel = defineLabel();
87433                 var loopLabel = defineLabel();
87434                 beginLoopBlock(/*continueLabel*/ conditionLabel);
87435                 markLabel(loopLabel);
87436                 transformAndEmitEmbeddedStatement(node.statement);
87437                 markLabel(conditionLabel);
87438                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87439                 endLoopBlock();
87440             }
87441             else {
87442                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87443             }
87444         }
87445         function visitDoStatement(node) {
87446             if (inStatementContainingYield) {
87447                 beginScriptLoopBlock();
87448                 node = ts.visitEachChild(node, visitor, context);
87449                 endLoopBlock();
87450                 return node;
87451             }
87452             else {
87453                 return ts.visitEachChild(node, visitor, context);
87454             }
87455         }
87456         function transformAndEmitWhileStatement(node) {
87457             if (containsYield(node)) {
87458                 // [source]
87459                 //      while (i < 10) {
87460                 //          /*body*/
87461                 //      }
87462                 //
87463                 // [intermediate]
87464                 //  .loop loopLabel, endLabel
87465                 //  .mark loopLabel
87466                 //  .brfalse endLabel, (i < 10)
87467                 //      /*body*/
87468                 //  .br loopLabel
87469                 //  .endloop
87470                 //  .mark endLabel
87471                 var loopLabel = defineLabel();
87472                 var endLabel = beginLoopBlock(loopLabel);
87473                 markLabel(loopLabel);
87474                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87475                 transformAndEmitEmbeddedStatement(node.statement);
87476                 emitBreak(loopLabel);
87477                 endLoopBlock();
87478             }
87479             else {
87480                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87481             }
87482         }
87483         function visitWhileStatement(node) {
87484             if (inStatementContainingYield) {
87485                 beginScriptLoopBlock();
87486                 node = ts.visitEachChild(node, visitor, context);
87487                 endLoopBlock();
87488                 return node;
87489             }
87490             else {
87491                 return ts.visitEachChild(node, visitor, context);
87492             }
87493         }
87494         function transformAndEmitForStatement(node) {
87495             if (containsYield(node)) {
87496                 // [source]
87497                 //      for (var i = 0; i < 10; i++) {
87498                 //          /*body*/
87499                 //      }
87500                 //
87501                 // [intermediate]
87502                 //  .local i
87503                 //      i = 0;
87504                 //  .loop incrementLabel, endLoopLabel
87505                 //  .mark conditionLabel
87506                 //  .brfalse endLoopLabel, (i < 10)
87507                 //      /*body*/
87508                 //  .mark incrementLabel
87509                 //      i++;
87510                 //  .br conditionLabel
87511                 //  .endloop
87512                 //  .mark endLoopLabel
87513                 var conditionLabel = defineLabel();
87514                 var incrementLabel = defineLabel();
87515                 var endLabel = beginLoopBlock(incrementLabel);
87516                 if (node.initializer) {
87517                     var initializer = node.initializer;
87518                     if (ts.isVariableDeclarationList(initializer)) {
87519                         transformAndEmitVariableDeclarationList(initializer);
87520                     }
87521                     else {
87522                         emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
87523                     }
87524                 }
87525                 markLabel(conditionLabel);
87526                 if (node.condition) {
87527                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
87528                 }
87529                 transformAndEmitEmbeddedStatement(node.statement);
87530                 markLabel(incrementLabel);
87531                 if (node.incrementor) {
87532                     emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
87533                 }
87534                 emitBreak(conditionLabel);
87535                 endLoopBlock();
87536             }
87537             else {
87538                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87539             }
87540         }
87541         function visitForStatement(node) {
87542             if (inStatementContainingYield) {
87543                 beginScriptLoopBlock();
87544             }
87545             var initializer = node.initializer;
87546             if (initializer && ts.isVariableDeclarationList(initializer)) {
87547                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87548                     var variable = _a[_i];
87549                     hoistVariableDeclaration(variable.name);
87550                 }
87551                 var variables = ts.getInitializedVariables(initializer);
87552                 node = ts.updateFor(node, variables.length > 0
87553                     ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
87554                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87555             }
87556             else {
87557                 node = ts.visitEachChild(node, visitor, context);
87558             }
87559             if (inStatementContainingYield) {
87560                 endLoopBlock();
87561             }
87562             return node;
87563         }
87564         function transformAndEmitForInStatement(node) {
87565             // TODO(rbuckton): Source map locations
87566             if (containsYield(node)) {
87567                 // [source]
87568                 //      for (var p in o) {
87569                 //          /*body*/
87570                 //      }
87571                 //
87572                 // [intermediate]
87573                 //  .local _a, _b, _i
87574                 //      _a = [];
87575                 //      for (_b in o) _a.push(_b);
87576                 //      _i = 0;
87577                 //  .loop incrementLabel, endLoopLabel
87578                 //  .mark conditionLabel
87579                 //  .brfalse endLoopLabel, (_i < _a.length)
87580                 //      p = _a[_i];
87581                 //      /*body*/
87582                 //  .mark incrementLabel
87583                 //      _b++;
87584                 //  .br conditionLabel
87585                 //  .endloop
87586                 //  .mark endLoopLabel
87587                 var keysArray = declareLocal(); // _a
87588                 var key = declareLocal(); // _b
87589                 var keysIndex = ts.createLoopVariable(); // _i
87590                 var initializer = node.initializer;
87591                 hoistVariableDeclaration(keysIndex);
87592                 emitAssignment(keysArray, ts.createArrayLiteral());
87593                 emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), 
87594                 /*typeArguments*/ undefined, [key]))));
87595                 emitAssignment(keysIndex, ts.createLiteral(0));
87596                 var conditionLabel = defineLabel();
87597                 var incrementLabel = defineLabel();
87598                 var endLabel = beginLoopBlock(incrementLabel);
87599                 markLabel(conditionLabel);
87600                 emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
87601                 var variable = void 0;
87602                 if (ts.isVariableDeclarationList(initializer)) {
87603                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87604                         var variable_1 = _a[_i];
87605                         hoistVariableDeclaration(variable_1.name);
87606                     }
87607                     variable = ts.getSynthesizedClone(initializer.declarations[0].name);
87608                 }
87609                 else {
87610                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
87611                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
87612                 }
87613                 emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
87614                 transformAndEmitEmbeddedStatement(node.statement);
87615                 markLabel(incrementLabel);
87616                 emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
87617                 emitBreak(conditionLabel);
87618                 endLoopBlock();
87619             }
87620             else {
87621                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87622             }
87623         }
87624         function visitForInStatement(node) {
87625             // [source]
87626             //      for (var x in a) {
87627             //          /*body*/
87628             //      }
87629             //
87630             // [intermediate]
87631             //  .local x
87632             //  .loop
87633             //      for (x in a) {
87634             //          /*body*/
87635             //      }
87636             //  .endloop
87637             if (inStatementContainingYield) {
87638                 beginScriptLoopBlock();
87639             }
87640             var initializer = node.initializer;
87641             if (ts.isVariableDeclarationList(initializer)) {
87642                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87643                     var variable = _a[_i];
87644                     hoistVariableDeclaration(variable.name);
87645                 }
87646                 node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87647             }
87648             else {
87649                 node = ts.visitEachChild(node, visitor, context);
87650             }
87651             if (inStatementContainingYield) {
87652                 endLoopBlock();
87653             }
87654             return node;
87655         }
87656         function transformAndEmitContinueStatement(node) {
87657             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
87658             if (label > 0) {
87659                 emitBreak(label, /*location*/ node);
87660             }
87661             else {
87662                 // invalid continue without a containing loop. Leave the node as is, per #17875.
87663                 emitStatement(node);
87664             }
87665         }
87666         function visitContinueStatement(node) {
87667             if (inStatementContainingYield) {
87668                 var label = findContinueTarget(node.label && ts.idText(node.label));
87669                 if (label > 0) {
87670                     return createInlineBreak(label, /*location*/ node);
87671                 }
87672             }
87673             return ts.visitEachChild(node, visitor, context);
87674         }
87675         function transformAndEmitBreakStatement(node) {
87676             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
87677             if (label > 0) {
87678                 emitBreak(label, /*location*/ node);
87679             }
87680             else {
87681                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
87682                 emitStatement(node);
87683             }
87684         }
87685         function visitBreakStatement(node) {
87686             if (inStatementContainingYield) {
87687                 var label = findBreakTarget(node.label && ts.idText(node.label));
87688                 if (label > 0) {
87689                     return createInlineBreak(label, /*location*/ node);
87690                 }
87691             }
87692             return ts.visitEachChild(node, visitor, context);
87693         }
87694         function transformAndEmitReturnStatement(node) {
87695             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87696             /*location*/ node);
87697         }
87698         function visitReturnStatement(node) {
87699             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87700             /*location*/ node);
87701         }
87702         function transformAndEmitWithStatement(node) {
87703             if (containsYield(node)) {
87704                 // [source]
87705                 //      with (x) {
87706                 //          /*body*/
87707                 //      }
87708                 //
87709                 // [intermediate]
87710                 //  .with (x)
87711                 //      /*body*/
87712                 //  .endwith
87713                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
87714                 transformAndEmitEmbeddedStatement(node.statement);
87715                 endWithBlock();
87716             }
87717             else {
87718                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87719             }
87720         }
87721         function transformAndEmitSwitchStatement(node) {
87722             if (containsYield(node.caseBlock)) {
87723                 // [source]
87724                 //      switch (x) {
87725                 //          case a:
87726                 //              /*caseStatements*/
87727                 //          case b:
87728                 //              /*caseStatements*/
87729                 //          default:
87730                 //              /*defaultStatements*/
87731                 //      }
87732                 //
87733                 // [intermediate]
87734                 //  .local _a
87735                 //  .switch endLabel
87736                 //      _a = x;
87737                 //      switch (_a) {
87738                 //          case a:
87739                 //  .br clauseLabels[0]
87740                 //      }
87741                 //      switch (_a) {
87742                 //          case b:
87743                 //  .br clauseLabels[1]
87744                 //      }
87745                 //  .br clauseLabels[2]
87746                 //  .mark clauseLabels[0]
87747                 //      /*caseStatements*/
87748                 //  .mark clauseLabels[1]
87749                 //      /*caseStatements*/
87750                 //  .mark clauseLabels[2]
87751                 //      /*caseStatements*/
87752                 //  .endswitch
87753                 //  .mark endLabel
87754                 var caseBlock = node.caseBlock;
87755                 var numClauses = caseBlock.clauses.length;
87756                 var endLabel = beginSwitchBlock();
87757                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
87758                 // Create labels for each clause and find the index of the first default clause.
87759                 var clauseLabels = [];
87760                 var defaultClauseIndex = -1;
87761                 for (var i = 0; i < numClauses; i++) {
87762                     var clause = caseBlock.clauses[i];
87763                     clauseLabels.push(defineLabel());
87764                     if (clause.kind === 278 /* DefaultClause */ && defaultClauseIndex === -1) {
87765                         defaultClauseIndex = i;
87766                     }
87767                 }
87768                 // Emit switch statements for each run of case clauses either from the first case
87769                 // clause or the next case clause with a `yield` in its expression, up to the next
87770                 // case clause with a `yield` in its expression.
87771                 var clausesWritten = 0;
87772                 var pendingClauses = [];
87773                 while (clausesWritten < numClauses) {
87774                     var defaultClausesSkipped = 0;
87775                     for (var i = clausesWritten; i < numClauses; i++) {
87776                         var clause = caseBlock.clauses[i];
87777                         if (clause.kind === 277 /* CaseClause */) {
87778                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
87779                                 break;
87780                             }
87781                             pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
87782                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
87783                             ]));
87784                         }
87785                         else {
87786                             defaultClausesSkipped++;
87787                         }
87788                     }
87789                     if (pendingClauses.length) {
87790                         emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
87791                         clausesWritten += pendingClauses.length;
87792                         pendingClauses = [];
87793                     }
87794                     if (defaultClausesSkipped > 0) {
87795                         clausesWritten += defaultClausesSkipped;
87796                         defaultClausesSkipped = 0;
87797                     }
87798                 }
87799                 if (defaultClauseIndex >= 0) {
87800                     emitBreak(clauseLabels[defaultClauseIndex]);
87801                 }
87802                 else {
87803                     emitBreak(endLabel);
87804                 }
87805                 for (var i = 0; i < numClauses; i++) {
87806                     markLabel(clauseLabels[i]);
87807                     transformAndEmitStatements(caseBlock.clauses[i].statements);
87808                 }
87809                 endSwitchBlock();
87810             }
87811             else {
87812                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87813             }
87814         }
87815         function visitSwitchStatement(node) {
87816             if (inStatementContainingYield) {
87817                 beginScriptSwitchBlock();
87818             }
87819             node = ts.visitEachChild(node, visitor, context);
87820             if (inStatementContainingYield) {
87821                 endSwitchBlock();
87822             }
87823             return node;
87824         }
87825         function transformAndEmitLabeledStatement(node) {
87826             if (containsYield(node)) {
87827                 // [source]
87828                 //      x: {
87829                 //          /*body*/
87830                 //      }
87831                 //
87832                 // [intermediate]
87833                 //  .labeled "x", endLabel
87834                 //      /*body*/
87835                 //  .endlabeled
87836                 //  .mark endLabel
87837                 beginLabeledBlock(ts.idText(node.label));
87838                 transformAndEmitEmbeddedStatement(node.statement);
87839                 endLabeledBlock();
87840             }
87841             else {
87842                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87843             }
87844         }
87845         function visitLabeledStatement(node) {
87846             if (inStatementContainingYield) {
87847                 beginScriptLabeledBlock(ts.idText(node.label));
87848             }
87849             node = ts.visitEachChild(node, visitor, context);
87850             if (inStatementContainingYield) {
87851                 endLabeledBlock();
87852             }
87853             return node;
87854         }
87855         function transformAndEmitThrowStatement(node) {
87856             emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), 
87857             /*location*/ node);
87858         }
87859         function transformAndEmitTryStatement(node) {
87860             if (containsYield(node)) {
87861                 // [source]
87862                 //      try {
87863                 //          /*tryBlock*/
87864                 //      }
87865                 //      catch (e) {
87866                 //          /*catchBlock*/
87867                 //      }
87868                 //      finally {
87869                 //          /*finallyBlock*/
87870                 //      }
87871                 //
87872                 // [intermediate]
87873                 //  .local _a
87874                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
87875                 //  .mark tryLabel
87876                 //  .nop
87877                 //      /*tryBlock*/
87878                 //  .br endLabel
87879                 //  .catch
87880                 //  .mark catchLabel
87881                 //      _a = %error%;
87882                 //      /*catchBlock*/
87883                 //  .br endLabel
87884                 //  .finally
87885                 //  .mark finallyLabel
87886                 //      /*finallyBlock*/
87887                 //  .endfinally
87888                 //  .endtry
87889                 //  .mark endLabel
87890                 beginExceptionBlock();
87891                 transformAndEmitEmbeddedStatement(node.tryBlock);
87892                 if (node.catchClause) {
87893                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
87894                     transformAndEmitEmbeddedStatement(node.catchClause.block);
87895                 }
87896                 if (node.finallyBlock) {
87897                     beginFinallyBlock();
87898                     transformAndEmitEmbeddedStatement(node.finallyBlock);
87899                 }
87900                 endExceptionBlock();
87901             }
87902             else {
87903                 emitStatement(ts.visitEachChild(node, visitor, context));
87904             }
87905         }
87906         function containsYield(node) {
87907             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
87908         }
87909         function countInitialNodesWithoutYield(nodes) {
87910             var numNodes = nodes.length;
87911             for (var i = 0; i < numNodes; i++) {
87912                 if (containsYield(nodes[i])) {
87913                     return i;
87914                 }
87915             }
87916             return -1;
87917         }
87918         function onSubstituteNode(hint, node) {
87919             node = previousOnSubstituteNode(hint, node);
87920             if (hint === 1 /* Expression */) {
87921                 return substituteExpression(node);
87922             }
87923             return node;
87924         }
87925         function substituteExpression(node) {
87926             if (ts.isIdentifier(node)) {
87927                 return substituteExpressionIdentifier(node);
87928             }
87929             return node;
87930         }
87931         function substituteExpressionIdentifier(node) {
87932             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
87933                 var original = ts.getOriginalNode(node);
87934                 if (ts.isIdentifier(original) && original.parent) {
87935                     var declaration = resolver.getReferencedValueDeclaration(original);
87936                     if (declaration) {
87937                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
87938                         if (name) {
87939                             var clone_8 = ts.getMutableClone(name);
87940                             ts.setSourceMapRange(clone_8, node);
87941                             ts.setCommentRange(clone_8, node);
87942                             return clone_8;
87943                         }
87944                     }
87945                 }
87946             }
87947             return node;
87948         }
87949         function cacheExpression(node) {
87950             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
87951                 return node;
87952             }
87953             var temp = ts.createTempVariable(hoistVariableDeclaration);
87954             emitAssignment(temp, node, /*location*/ node);
87955             return temp;
87956         }
87957         function declareLocal(name) {
87958             var temp = name
87959                 ? ts.createUniqueName(name)
87960                 : ts.createTempVariable(/*recordTempVariable*/ undefined);
87961             hoistVariableDeclaration(temp);
87962             return temp;
87963         }
87964         /**
87965          * Defines a label, uses as the target of a Break operation.
87966          */
87967         function defineLabel() {
87968             if (!labelOffsets) {
87969                 labelOffsets = [];
87970             }
87971             var label = nextLabelId;
87972             nextLabelId++;
87973             labelOffsets[label] = -1;
87974             return label;
87975         }
87976         /**
87977          * Marks the current operation with the specified label.
87978          */
87979         function markLabel(label) {
87980             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
87981             labelOffsets[label] = operations ? operations.length : 0;
87982         }
87983         /**
87984          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
87985          *
87986          * @param block Information about the block.
87987          */
87988         function beginBlock(block) {
87989             if (!blocks) {
87990                 blocks = [];
87991                 blockActions = [];
87992                 blockOffsets = [];
87993                 blockStack = [];
87994             }
87995             var index = blockActions.length;
87996             blockActions[index] = 0 /* Open */;
87997             blockOffsets[index] = operations ? operations.length : 0;
87998             blocks[index] = block;
87999             blockStack.push(block);
88000             return index;
88001         }
88002         /**
88003          * Ends the current block operation.
88004          */
88005         function endBlock() {
88006             var block = peekBlock();
88007             if (block === undefined)
88008                 return ts.Debug.fail("beginBlock was never called.");
88009             var index = blockActions.length;
88010             blockActions[index] = 1 /* Close */;
88011             blockOffsets[index] = operations ? operations.length : 0;
88012             blocks[index] = block;
88013             blockStack.pop();
88014             return block;
88015         }
88016         /**
88017          * Gets the current open block.
88018          */
88019         function peekBlock() {
88020             return ts.lastOrUndefined(blockStack);
88021         }
88022         /**
88023          * Gets the kind of the current open block.
88024          */
88025         function peekBlockKind() {
88026             var block = peekBlock();
88027             return block && block.kind;
88028         }
88029         /**
88030          * Begins a code block for a generated `with` statement.
88031          *
88032          * @param expression An identifier representing expression for the `with` block.
88033          */
88034         function beginWithBlock(expression) {
88035             var startLabel = defineLabel();
88036             var endLabel = defineLabel();
88037             markLabel(startLabel);
88038             beginBlock({
88039                 kind: 1 /* With */,
88040                 expression: expression,
88041                 startLabel: startLabel,
88042                 endLabel: endLabel
88043             });
88044         }
88045         /**
88046          * Ends a code block for a generated `with` statement.
88047          */
88048         function endWithBlock() {
88049             ts.Debug.assert(peekBlockKind() === 1 /* With */);
88050             var block = endBlock();
88051             markLabel(block.endLabel);
88052         }
88053         /**
88054          * Begins a code block for a generated `try` statement.
88055          */
88056         function beginExceptionBlock() {
88057             var startLabel = defineLabel();
88058             var endLabel = defineLabel();
88059             markLabel(startLabel);
88060             beginBlock({
88061                 kind: 0 /* Exception */,
88062                 state: 0 /* Try */,
88063                 startLabel: startLabel,
88064                 endLabel: endLabel
88065             });
88066             emitNop();
88067             return endLabel;
88068         }
88069         /**
88070          * Enters the `catch` clause of a generated `try` statement.
88071          *
88072          * @param variable The catch variable.
88073          */
88074         function beginCatchBlock(variable) {
88075             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88076             // generated identifiers should already be unique within a file
88077             var name;
88078             if (ts.isGeneratedIdentifier(variable.name)) {
88079                 name = variable.name;
88080                 hoistVariableDeclaration(variable.name);
88081             }
88082             else {
88083                 var text = ts.idText(variable.name);
88084                 name = declareLocal(text);
88085                 if (!renamedCatchVariables) {
88086                     renamedCatchVariables = ts.createMap();
88087                     renamedCatchVariableDeclarations = [];
88088                     context.enableSubstitution(75 /* Identifier */);
88089                 }
88090                 renamedCatchVariables.set(text, true);
88091                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
88092             }
88093             var exception = peekBlock();
88094             ts.Debug.assert(exception.state < 1 /* Catch */);
88095             var endLabel = exception.endLabel;
88096             emitBreak(endLabel);
88097             var catchLabel = defineLabel();
88098             markLabel(catchLabel);
88099             exception.state = 1 /* Catch */;
88100             exception.catchVariable = name;
88101             exception.catchLabel = catchLabel;
88102             emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
88103             emitNop();
88104         }
88105         /**
88106          * Enters the `finally` block of a generated `try` statement.
88107          */
88108         function beginFinallyBlock() {
88109             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88110             var exception = peekBlock();
88111             ts.Debug.assert(exception.state < 2 /* Finally */);
88112             var endLabel = exception.endLabel;
88113             emitBreak(endLabel);
88114             var finallyLabel = defineLabel();
88115             markLabel(finallyLabel);
88116             exception.state = 2 /* Finally */;
88117             exception.finallyLabel = finallyLabel;
88118         }
88119         /**
88120          * Ends the code block for a generated `try` statement.
88121          */
88122         function endExceptionBlock() {
88123             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88124             var exception = endBlock();
88125             var state = exception.state;
88126             if (state < 2 /* Finally */) {
88127                 emitBreak(exception.endLabel);
88128             }
88129             else {
88130                 emitEndfinally();
88131             }
88132             markLabel(exception.endLabel);
88133             emitNop();
88134             exception.state = 3 /* Done */;
88135         }
88136         /**
88137          * Begins a code block that supports `break` or `continue` statements that are defined in
88138          * the source tree and not from generated code.
88139          *
88140          * @param labelText Names from containing labeled statements.
88141          */
88142         function beginScriptLoopBlock() {
88143             beginBlock({
88144                 kind: 3 /* Loop */,
88145                 isScript: true,
88146                 breakLabel: -1,
88147                 continueLabel: -1
88148             });
88149         }
88150         /**
88151          * Begins a code block that supports `break` or `continue` statements that are defined in
88152          * generated code. Returns a label used to mark the operation to which to jump when a
88153          * `break` statement targets this block.
88154          *
88155          * @param continueLabel A Label used to mark the operation to which to jump when a
88156          *                      `continue` statement targets this block.
88157          */
88158         function beginLoopBlock(continueLabel) {
88159             var breakLabel = defineLabel();
88160             beginBlock({
88161                 kind: 3 /* Loop */,
88162                 isScript: false,
88163                 breakLabel: breakLabel,
88164                 continueLabel: continueLabel,
88165             });
88166             return breakLabel;
88167         }
88168         /**
88169          * Ends a code block that supports `break` or `continue` statements that are defined in
88170          * generated code or in the source tree.
88171          */
88172         function endLoopBlock() {
88173             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
88174             var block = endBlock();
88175             var breakLabel = block.breakLabel;
88176             if (!block.isScript) {
88177                 markLabel(breakLabel);
88178             }
88179         }
88180         /**
88181          * Begins a code block that supports `break` statements that are defined in the source
88182          * tree and not from generated code.
88183          *
88184          */
88185         function beginScriptSwitchBlock() {
88186             beginBlock({
88187                 kind: 2 /* Switch */,
88188                 isScript: true,
88189                 breakLabel: -1
88190             });
88191         }
88192         /**
88193          * Begins a code block that supports `break` statements that are defined in generated code.
88194          * Returns a label used to mark the operation to which to jump when a `break` statement
88195          * targets this block.
88196          */
88197         function beginSwitchBlock() {
88198             var breakLabel = defineLabel();
88199             beginBlock({
88200                 kind: 2 /* Switch */,
88201                 isScript: false,
88202                 breakLabel: breakLabel,
88203             });
88204             return breakLabel;
88205         }
88206         /**
88207          * Ends a code block that supports `break` statements that are defined in generated code.
88208          */
88209         function endSwitchBlock() {
88210             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
88211             var block = endBlock();
88212             var breakLabel = block.breakLabel;
88213             if (!block.isScript) {
88214                 markLabel(breakLabel);
88215             }
88216         }
88217         function beginScriptLabeledBlock(labelText) {
88218             beginBlock({
88219                 kind: 4 /* Labeled */,
88220                 isScript: true,
88221                 labelText: labelText,
88222                 breakLabel: -1
88223             });
88224         }
88225         function beginLabeledBlock(labelText) {
88226             var breakLabel = defineLabel();
88227             beginBlock({
88228                 kind: 4 /* Labeled */,
88229                 isScript: false,
88230                 labelText: labelText,
88231                 breakLabel: breakLabel
88232             });
88233         }
88234         function endLabeledBlock() {
88235             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
88236             var block = endBlock();
88237             if (!block.isScript) {
88238                 markLabel(block.breakLabel);
88239             }
88240         }
88241         /**
88242          * Indicates whether the provided block supports `break` statements.
88243          *
88244          * @param block A code block.
88245          */
88246         function supportsUnlabeledBreak(block) {
88247             return block.kind === 2 /* Switch */
88248                 || block.kind === 3 /* Loop */;
88249         }
88250         /**
88251          * Indicates whether the provided block supports `break` statements with labels.
88252          *
88253          * @param block A code block.
88254          */
88255         function supportsLabeledBreakOrContinue(block) {
88256             return block.kind === 4 /* Labeled */;
88257         }
88258         /**
88259          * Indicates whether the provided block supports `continue` statements.
88260          *
88261          * @param block A code block.
88262          */
88263         function supportsUnlabeledContinue(block) {
88264             return block.kind === 3 /* Loop */;
88265         }
88266         function hasImmediateContainingLabeledBlock(labelText, start) {
88267             for (var j = start; j >= 0; j--) {
88268                 var containingBlock = blockStack[j];
88269                 if (supportsLabeledBreakOrContinue(containingBlock)) {
88270                     if (containingBlock.labelText === labelText) {
88271                         return true;
88272                     }
88273                 }
88274                 else {
88275                     break;
88276                 }
88277             }
88278             return false;
88279         }
88280         /**
88281          * Finds the label that is the target for a `break` statement.
88282          *
88283          * @param labelText An optional name of a containing labeled statement.
88284          */
88285         function findBreakTarget(labelText) {
88286             if (blockStack) {
88287                 if (labelText) {
88288                     for (var i = blockStack.length - 1; i >= 0; i--) {
88289                         var block = blockStack[i];
88290                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
88291                             return block.breakLabel;
88292                         }
88293                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88294                             return block.breakLabel;
88295                         }
88296                     }
88297                 }
88298                 else {
88299                     for (var i = blockStack.length - 1; i >= 0; i--) {
88300                         var block = blockStack[i];
88301                         if (supportsUnlabeledBreak(block)) {
88302                             return block.breakLabel;
88303                         }
88304                     }
88305                 }
88306             }
88307             return 0;
88308         }
88309         /**
88310          * Finds the label that is the target for a `continue` statement.
88311          *
88312          * @param labelText An optional name of a containing labeled statement.
88313          */
88314         function findContinueTarget(labelText) {
88315             if (blockStack) {
88316                 if (labelText) {
88317                     for (var i = blockStack.length - 1; i >= 0; i--) {
88318                         var block = blockStack[i];
88319                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88320                             return block.continueLabel;
88321                         }
88322                     }
88323                 }
88324                 else {
88325                     for (var i = blockStack.length - 1; i >= 0; i--) {
88326                         var block = blockStack[i];
88327                         if (supportsUnlabeledContinue(block)) {
88328                             return block.continueLabel;
88329                         }
88330                     }
88331                 }
88332             }
88333             return 0;
88334         }
88335         /**
88336          * Creates an expression that can be used to indicate the value for a label.
88337          *
88338          * @param label A label.
88339          */
88340         function createLabel(label) {
88341             if (label !== undefined && label > 0) {
88342                 if (labelExpressions === undefined) {
88343                     labelExpressions = [];
88344                 }
88345                 var expression = ts.createLiteral(-1);
88346                 if (labelExpressions[label] === undefined) {
88347                     labelExpressions[label] = [expression];
88348                 }
88349                 else {
88350                     labelExpressions[label].push(expression);
88351                 }
88352                 return expression;
88353             }
88354             return ts.createOmittedExpression();
88355         }
88356         /**
88357          * Creates a numeric literal for the provided instruction.
88358          */
88359         function createInstruction(instruction) {
88360             var literal = ts.createLiteral(instruction);
88361             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
88362             return literal;
88363         }
88364         /**
88365          * Creates a statement that can be used indicate a Break operation to the provided label.
88366          *
88367          * @param label A label.
88368          * @param location An optional source map location for the statement.
88369          */
88370         function createInlineBreak(label, location) {
88371             ts.Debug.assertLessThan(0, label, "Invalid label");
88372             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88373                 createInstruction(3 /* Break */),
88374                 createLabel(label)
88375             ])), location);
88376         }
88377         /**
88378          * Creates a statement that can be used indicate a Return operation.
88379          *
88380          * @param expression The expression for the return statement.
88381          * @param location An optional source map location for the statement.
88382          */
88383         function createInlineReturn(expression, location) {
88384             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88385                 ? [createInstruction(2 /* Return */), expression]
88386                 : [createInstruction(2 /* Return */)])), location);
88387         }
88388         /**
88389          * Creates an expression that can be used to resume from a Yield operation.
88390          */
88391         function createGeneratorResume(location) {
88392             return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), 
88393             /*typeArguments*/ undefined, []), location);
88394         }
88395         /**
88396          * Emits an empty instruction.
88397          */
88398         function emitNop() {
88399             emitWorker(0 /* Nop */);
88400         }
88401         /**
88402          * Emits a Statement.
88403          *
88404          * @param node A statement.
88405          */
88406         function emitStatement(node) {
88407             if (node) {
88408                 emitWorker(1 /* Statement */, [node]);
88409             }
88410             else {
88411                 emitNop();
88412             }
88413         }
88414         /**
88415          * Emits an Assignment operation.
88416          *
88417          * @param left The left-hand side of the assignment.
88418          * @param right The right-hand side of the assignment.
88419          * @param location An optional source map location for the assignment.
88420          */
88421         function emitAssignment(left, right, location) {
88422             emitWorker(2 /* Assign */, [left, right], location);
88423         }
88424         /**
88425          * Emits a Break operation to the specified label.
88426          *
88427          * @param label A label.
88428          * @param location An optional source map location for the assignment.
88429          */
88430         function emitBreak(label, location) {
88431             emitWorker(3 /* Break */, [label], location);
88432         }
88433         /**
88434          * Emits a Break operation to the specified label when a condition evaluates to a truthy
88435          * value at runtime.
88436          *
88437          * @param label A label.
88438          * @param condition The condition.
88439          * @param location An optional source map location for the assignment.
88440          */
88441         function emitBreakWhenTrue(label, condition, location) {
88442             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
88443         }
88444         /**
88445          * Emits a Break to the specified label when a condition evaluates to a falsey value at
88446          * runtime.
88447          *
88448          * @param label A label.
88449          * @param condition The condition.
88450          * @param location An optional source map location for the assignment.
88451          */
88452         function emitBreakWhenFalse(label, condition, location) {
88453             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
88454         }
88455         /**
88456          * Emits a YieldStar operation for the provided expression.
88457          *
88458          * @param expression An optional value for the yield operation.
88459          * @param location An optional source map location for the assignment.
88460          */
88461         function emitYieldStar(expression, location) {
88462             emitWorker(7 /* YieldStar */, [expression], location);
88463         }
88464         /**
88465          * Emits a Yield operation for the provided expression.
88466          *
88467          * @param expression An optional value for the yield operation.
88468          * @param location An optional source map location for the assignment.
88469          */
88470         function emitYield(expression, location) {
88471             emitWorker(6 /* Yield */, [expression], location);
88472         }
88473         /**
88474          * Emits a Return operation for the provided expression.
88475          *
88476          * @param expression An optional value for the operation.
88477          * @param location An optional source map location for the assignment.
88478          */
88479         function emitReturn(expression, location) {
88480             emitWorker(8 /* Return */, [expression], location);
88481         }
88482         /**
88483          * Emits a Throw operation for the provided expression.
88484          *
88485          * @param expression A value for the operation.
88486          * @param location An optional source map location for the assignment.
88487          */
88488         function emitThrow(expression, location) {
88489             emitWorker(9 /* Throw */, [expression], location);
88490         }
88491         /**
88492          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
88493          */
88494         function emitEndfinally() {
88495             emitWorker(10 /* Endfinally */);
88496         }
88497         /**
88498          * Emits an operation.
88499          *
88500          * @param code The OpCode for the operation.
88501          * @param args The optional arguments for the operation.
88502          */
88503         function emitWorker(code, args, location) {
88504             if (operations === undefined) {
88505                 operations = [];
88506                 operationArguments = [];
88507                 operationLocations = [];
88508             }
88509             if (labelOffsets === undefined) {
88510                 // mark entry point
88511                 markLabel(defineLabel());
88512             }
88513             var operationIndex = operations.length;
88514             operations[operationIndex] = code;
88515             operationArguments[operationIndex] = args;
88516             operationLocations[operationIndex] = location;
88517         }
88518         /**
88519          * Builds the generator function body.
88520          */
88521         function build() {
88522             blockIndex = 0;
88523             labelNumber = 0;
88524             labelNumbers = undefined;
88525             lastOperationWasAbrupt = false;
88526             lastOperationWasCompletion = false;
88527             clauses = undefined;
88528             statements = undefined;
88529             exceptionBlockStack = undefined;
88530             currentExceptionBlock = undefined;
88531             withBlockStack = undefined;
88532             var buildResult = buildStatements();
88533             return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
88534             /*modifiers*/ undefined, 
88535             /*asteriskToken*/ undefined, 
88536             /*name*/ undefined, 
88537             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
88538             /*type*/ undefined, ts.createBlock(buildResult, 
88539             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
88540         }
88541         /**
88542          * Builds the statements for the generator function body.
88543          */
88544         function buildStatements() {
88545             if (operations) {
88546                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
88547                     writeOperation(operationIndex);
88548                 }
88549                 flushFinalLabel(operations.length);
88550             }
88551             else {
88552                 flushFinalLabel(0);
88553             }
88554             if (clauses) {
88555                 var labelExpression = ts.createPropertyAccess(state, "label");
88556                 var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
88557                 return [ts.startOnNewLine(switchStatement)];
88558             }
88559             if (statements) {
88560                 return statements;
88561             }
88562             return [];
88563         }
88564         /**
88565          * Flush the current label and advance to a new label.
88566          */
88567         function flushLabel() {
88568             if (!statements) {
88569                 return;
88570             }
88571             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
88572             lastOperationWasAbrupt = false;
88573             lastOperationWasCompletion = false;
88574             labelNumber++;
88575         }
88576         /**
88577          * Flush the final label of the generator function body.
88578          */
88579         function flushFinalLabel(operationIndex) {
88580             if (isFinalLabelReachable(operationIndex)) {
88581                 tryEnterLabel(operationIndex);
88582                 withBlockStack = undefined;
88583                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
88584             }
88585             if (statements && clauses) {
88586                 appendLabel(/*markLabelEnd*/ false);
88587             }
88588             updateLabelExpressions();
88589         }
88590         /**
88591          * Tests whether the final label of the generator function body
88592          * is reachable by user code.
88593          */
88594         function isFinalLabelReachable(operationIndex) {
88595             // if the last operation was *not* a completion (return/throw) then
88596             // the final label is reachable.
88597             if (!lastOperationWasCompletion) {
88598                 return true;
88599             }
88600             // if there are no labels defined or referenced, then the final label is
88601             // not reachable.
88602             if (!labelOffsets || !labelExpressions) {
88603                 return false;
88604             }
88605             // if the label for this offset is referenced, then the final label
88606             // is reachable.
88607             for (var label = 0; label < labelOffsets.length; label++) {
88608                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
88609                     return true;
88610                 }
88611             }
88612             return false;
88613         }
88614         /**
88615          * Appends a case clause for the last label and sets the new label.
88616          *
88617          * @param markLabelEnd Indicates that the transition between labels was a fall-through
88618          *                     from a previous case clause and the change in labels should be
88619          *                     reflected on the `state` object.
88620          */
88621         function appendLabel(markLabelEnd) {
88622             if (!clauses) {
88623                 clauses = [];
88624             }
88625             if (statements) {
88626                 if (withBlockStack) {
88627                     // The previous label was nested inside one or more `with` blocks, so we
88628                     // surround the statements in generated `with` blocks to create the same environment.
88629                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
88630                         var withBlock = withBlockStack[i];
88631                         statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
88632                     }
88633                 }
88634                 if (currentExceptionBlock) {
88635                     // The previous label was nested inside of an exception block, so we must
88636                     // indicate entry into a protected region by pushing the label numbers
88637                     // for each block in the protected region.
88638                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
88639                     statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), 
88640                     /*typeArguments*/ undefined, [
88641                         ts.createArrayLiteral([
88642                             createLabel(startLabel),
88643                             createLabel(catchLabel),
88644                             createLabel(finallyLabel),
88645                             createLabel(endLabel)
88646                         ])
88647                     ])));
88648                     currentExceptionBlock = undefined;
88649                 }
88650                 if (markLabelEnd) {
88651                     // The case clause for the last label falls through to this label, so we
88652                     // add an assignment statement to reflect the change in labels.
88653                     statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
88654                 }
88655             }
88656             clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
88657             statements = undefined;
88658         }
88659         /**
88660          * Tries to enter into a new label at the current operation index.
88661          */
88662         function tryEnterLabel(operationIndex) {
88663             if (!labelOffsets) {
88664                 return;
88665             }
88666             for (var label = 0; label < labelOffsets.length; label++) {
88667                 if (labelOffsets[label] === operationIndex) {
88668                     flushLabel();
88669                     if (labelNumbers === undefined) {
88670                         labelNumbers = [];
88671                     }
88672                     if (labelNumbers[labelNumber] === undefined) {
88673                         labelNumbers[labelNumber] = [label];
88674                     }
88675                     else {
88676                         labelNumbers[labelNumber].push(label);
88677                     }
88678                 }
88679             }
88680         }
88681         /**
88682          * Updates literal expressions for labels with actual label numbers.
88683          */
88684         function updateLabelExpressions() {
88685             if (labelExpressions !== undefined && labelNumbers !== undefined) {
88686                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
88687                     var labels = labelNumbers[labelNumber_1];
88688                     if (labels !== undefined) {
88689                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
88690                             var label = labels_1[_i];
88691                             var expressions = labelExpressions[label];
88692                             if (expressions !== undefined) {
88693                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
88694                                     var expression = expressions_1[_a];
88695                                     expression.text = String(labelNumber_1);
88696                                 }
88697                             }
88698                         }
88699                     }
88700                 }
88701             }
88702         }
88703         /**
88704          * Tries to enter or leave a code block.
88705          */
88706         function tryEnterOrLeaveBlock(operationIndex) {
88707             if (blocks) {
88708                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
88709                     var block = blocks[blockIndex];
88710                     var blockAction = blockActions[blockIndex];
88711                     switch (block.kind) {
88712                         case 0 /* Exception */:
88713                             if (blockAction === 0 /* Open */) {
88714                                 if (!exceptionBlockStack) {
88715                                     exceptionBlockStack = [];
88716                                 }
88717                                 if (!statements) {
88718                                     statements = [];
88719                                 }
88720                                 exceptionBlockStack.push(currentExceptionBlock);
88721                                 currentExceptionBlock = block;
88722                             }
88723                             else if (blockAction === 1 /* Close */) {
88724                                 currentExceptionBlock = exceptionBlockStack.pop();
88725                             }
88726                             break;
88727                         case 1 /* With */:
88728                             if (blockAction === 0 /* Open */) {
88729                                 if (!withBlockStack) {
88730                                     withBlockStack = [];
88731                                 }
88732                                 withBlockStack.push(block);
88733                             }
88734                             else if (blockAction === 1 /* Close */) {
88735                                 withBlockStack.pop();
88736                             }
88737                             break;
88738                         // default: do nothing
88739                     }
88740                 }
88741             }
88742         }
88743         /**
88744          * Writes an operation as a statement to the current label's statement list.
88745          *
88746          * @param operation The OpCode of the operation
88747          */
88748         function writeOperation(operationIndex) {
88749             tryEnterLabel(operationIndex);
88750             tryEnterOrLeaveBlock(operationIndex);
88751             // early termination, nothing else to process in this label
88752             if (lastOperationWasAbrupt) {
88753                 return;
88754             }
88755             lastOperationWasAbrupt = false;
88756             lastOperationWasCompletion = false;
88757             var opcode = operations[operationIndex];
88758             if (opcode === 0 /* Nop */) {
88759                 return;
88760             }
88761             else if (opcode === 10 /* Endfinally */) {
88762                 return writeEndfinally();
88763             }
88764             var args = operationArguments[operationIndex];
88765             if (opcode === 1 /* Statement */) {
88766                 return writeStatement(args[0]);
88767             }
88768             var location = operationLocations[operationIndex];
88769             switch (opcode) {
88770                 case 2 /* Assign */:
88771                     return writeAssign(args[0], args[1], location);
88772                 case 3 /* Break */:
88773                     return writeBreak(args[0], location);
88774                 case 4 /* BreakWhenTrue */:
88775                     return writeBreakWhenTrue(args[0], args[1], location);
88776                 case 5 /* BreakWhenFalse */:
88777                     return writeBreakWhenFalse(args[0], args[1], location);
88778                 case 6 /* Yield */:
88779                     return writeYield(args[0], location);
88780                 case 7 /* YieldStar */:
88781                     return writeYieldStar(args[0], location);
88782                 case 8 /* Return */:
88783                     return writeReturn(args[0], location);
88784                 case 9 /* Throw */:
88785                     return writeThrow(args[0], location);
88786             }
88787         }
88788         /**
88789          * Writes a statement to the current label's statement list.
88790          *
88791          * @param statement A statement to write.
88792          */
88793         function writeStatement(statement) {
88794             if (statement) {
88795                 if (!statements) {
88796                     statements = [statement];
88797                 }
88798                 else {
88799                     statements.push(statement);
88800                 }
88801             }
88802         }
88803         /**
88804          * Writes an Assign operation to the current label's statement list.
88805          *
88806          * @param left The left-hand side of the assignment.
88807          * @param right The right-hand side of the assignment.
88808          * @param operationLocation The source map location for the operation.
88809          */
88810         function writeAssign(left, right, operationLocation) {
88811             writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
88812         }
88813         /**
88814          * Writes a Throw operation to the current label's statement list.
88815          *
88816          * @param expression The value to throw.
88817          * @param operationLocation The source map location for the operation.
88818          */
88819         function writeThrow(expression, operationLocation) {
88820             lastOperationWasAbrupt = true;
88821             lastOperationWasCompletion = true;
88822             writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
88823         }
88824         /**
88825          * Writes a Return operation to the current label's statement list.
88826          *
88827          * @param expression The value to return.
88828          * @param operationLocation The source map location for the operation.
88829          */
88830         function writeReturn(expression, operationLocation) {
88831             lastOperationWasAbrupt = true;
88832             lastOperationWasCompletion = true;
88833             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88834                 ? [createInstruction(2 /* Return */), expression]
88835                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88836         }
88837         /**
88838          * Writes a Break operation to the current label's statement list.
88839          *
88840          * @param label The label for the Break.
88841          * @param operationLocation The source map location for the operation.
88842          */
88843         function writeBreak(label, operationLocation) {
88844             lastOperationWasAbrupt = true;
88845             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88846                 createInstruction(3 /* Break */),
88847                 createLabel(label)
88848             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88849         }
88850         /**
88851          * Writes a BreakWhenTrue operation to the current label's statement list.
88852          *
88853          * @param label The label for the Break.
88854          * @param condition The condition for the Break.
88855          * @param operationLocation The source map location for the operation.
88856          */
88857         function writeBreakWhenTrue(label, condition, operationLocation) {
88858             writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88859                 createInstruction(3 /* Break */),
88860                 createLabel(label)
88861             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88862         }
88863         /**
88864          * Writes a BreakWhenFalse operation to the current label's statement list.
88865          *
88866          * @param label The label for the Break.
88867          * @param condition The condition for the Break.
88868          * @param operationLocation The source map location for the operation.
88869          */
88870         function writeBreakWhenFalse(label, condition, operationLocation) {
88871             writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88872                 createInstruction(3 /* Break */),
88873                 createLabel(label)
88874             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88875         }
88876         /**
88877          * Writes a Yield operation to the current label's statement list.
88878          *
88879          * @param expression The expression to yield.
88880          * @param operationLocation The source map location for the operation.
88881          */
88882         function writeYield(expression, operationLocation) {
88883             lastOperationWasAbrupt = true;
88884             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88885                 ? [createInstruction(4 /* Yield */), expression]
88886                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88887         }
88888         /**
88889          * Writes a YieldStar instruction to the current label's statement list.
88890          *
88891          * @param expression The expression to yield.
88892          * @param operationLocation The source map location for the operation.
88893          */
88894         function writeYieldStar(expression, operationLocation) {
88895             lastOperationWasAbrupt = true;
88896             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88897                 createInstruction(5 /* YieldStar */),
88898                 expression
88899             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88900         }
88901         /**
88902          * Writes an Endfinally instruction to the current label's statement list.
88903          */
88904         function writeEndfinally() {
88905             lastOperationWasAbrupt = true;
88906             writeStatement(ts.createReturn(ts.createArrayLiteral([
88907                 createInstruction(7 /* Endfinally */)
88908             ])));
88909         }
88910     }
88911     ts.transformGenerators = transformGenerators;
88912     function createGeneratorHelper(context, body) {
88913         context.requestEmitHelper(ts.generatorHelper);
88914         return ts.createCall(ts.getUnscopedHelperName("__generator"), 
88915         /*typeArguments*/ undefined, [ts.createThis(), body]);
88916     }
88917     // The __generator helper is used by down-level transformations to emulate the runtime
88918     // semantics of an ES2015 generator function. When called, this helper returns an
88919     // object that implements the Iterator protocol, in that it has `next`, `return`, and
88920     // `throw` methods that step through the generator when invoked.
88921     //
88922     // parameters:
88923     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
88924     //  @param body     A function that acts as the transformed generator body.
88925     //
88926     // variables:
88927     //  _       Persistent state for the generator that is shared between the helper and the
88928     //          generator body. The state object has the following members:
88929     //            sent() - A method that returns or throws the current completion value.
88930     //            label  - The next point at which to resume evaluation of the generator body.
88931     //            trys   - A stack of protected regions (try/catch/finally blocks).
88932     //            ops    - A stack of pending instructions when inside of a finally block.
88933     //  f       A value indicating whether the generator is executing.
88934     //  y       An iterator to delegate for a yield*.
88935     //  t       A temporary variable that holds one of the following values (note that these
88936     //          cases do not overlap):
88937     //          - The completion value when resuming from a `yield` or `yield*`.
88938     //          - The error value for a catch block.
88939     //          - The current protected region (array of try/catch/finally/end labels).
88940     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
88941     //            of a `yield*`.
88942     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
88943     //
88944     // functions:
88945     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
88946     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
88947     //              completed.
88948     //
88949     // The __generator helper understands a limited set of instructions:
88950     //  0: next(value?)     - Start or resume the generator with the specified value.
88951     //  1: throw(error)     - Resume the generator with an exception. If the generator is
88952     //                        suspended inside of one or more protected regions, evaluates
88953     //                        any intervening finally blocks between the current label and
88954     //                        the nearest catch block or function boundary. If uncaught, the
88955     //                        exception is thrown to the caller.
88956     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
88957     //                        suspended inside of one or more protected regions, evaluates any
88958     //                        intervening finally blocks.
88959     //  3: break(label)     - Jump to the specified label. If the label is outside of the
88960     //                        current protected region, evaluates any intervening finally
88961     //                        blocks.
88962     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
88963     //                        resumed, the generator will continue at the next label.
88964     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
88965     //                        delegation completes, the generator will continue at the next
88966     //                        label.
88967     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
88968     //                        the current label is inside of one or more protected regions,
88969     //                        evaluates any intervening finally blocks between the current
88970     //                        label and the nearest catch block or function boundary. If
88971     //                        uncaught, the exception is thrown to the caller.
88972     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
88973     //                        entering a finally block.
88974     //
88975     // For examples of how these are used, see the comments in ./transformers/generators.ts
88976     ts.generatorHelper = {
88977         name: "typescript:generator",
88978         importName: "__generator",
88979         scoped: false,
88980         priority: 6,
88981         text: "\n            var __generator = (this && this.__generator) || function (thisArg, body) {\n                var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n                return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n                function verb(n) { return function (v) { return step([n, v]); }; }\n                function step(op) {\n                    if (f) throw new TypeError(\"Generator is already executing.\");\n                    while (_) try {\n                        if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n                        if (y = 0, t) op = [op[0] & 2, t.value];\n                        switch (op[0]) {\n                            case 0: case 1: t = op; break;\n                            case 4: _.label++; return { value: op[1], done: false };\n                            case 5: _.label++; y = op[1]; op = [0]; continue;\n                            case 7: op = _.ops.pop(); _.trys.pop(); continue;\n                            default:\n                                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                                if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                                if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                                if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                                if (t[2]) _.ops.pop();\n                                _.trys.pop(); continue;\n                        }\n                        op = body.call(thisArg, _);\n                    } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n                    if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n                }\n            };"
88982     };
88983 })(ts || (ts = {}));
88984 /*@internal*/
88985 var ts;
88986 (function (ts) {
88987     function transformModule(context) {
88988         function getTransformModuleDelegate(moduleKind) {
88989             switch (moduleKind) {
88990                 case ts.ModuleKind.AMD: return transformAMDModule;
88991                 case ts.ModuleKind.UMD: return transformUMDModule;
88992                 default: return transformCommonJSModule;
88993             }
88994         }
88995         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
88996         var compilerOptions = context.getCompilerOptions();
88997         var resolver = context.getEmitResolver();
88998         var host = context.getEmitHost();
88999         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
89000         var moduleKind = ts.getEmitModuleKind(compilerOptions);
89001         var previousOnSubstituteNode = context.onSubstituteNode;
89002         var previousOnEmitNode = context.onEmitNode;
89003         context.onSubstituteNode = onSubstituteNode;
89004         context.onEmitNode = onEmitNode;
89005         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
89006         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
89007         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
89008         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
89009         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
89010         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
89011         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
89012         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
89013         var currentSourceFile; // The current file.
89014         var currentModuleInfo; // The ExternalModuleInfo for the current file.
89015         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
89016         var needUMDDynamicImportHelper;
89017         return ts.chainBundle(transformSourceFile);
89018         /**
89019          * Transforms the module aspects of a SourceFile.
89020          *
89021          * @param node The SourceFile node.
89022          */
89023         function transformSourceFile(node) {
89024             if (node.isDeclarationFile ||
89025                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
89026                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
89027                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
89028                 return node;
89029             }
89030             currentSourceFile = node;
89031             currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
89032             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
89033             // Perform the transformation.
89034             var transformModule = getTransformModuleDelegate(moduleKind);
89035             var updated = transformModule(node);
89036             currentSourceFile = undefined;
89037             currentModuleInfo = undefined;
89038             needUMDDynamicImportHelper = false;
89039             return ts.aggregateTransformFlags(updated);
89040         }
89041         function shouldEmitUnderscoreUnderscoreESModule() {
89042             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
89043                 return true;
89044             }
89045             return false;
89046         }
89047         /**
89048          * Transforms a SourceFile into a CommonJS module.
89049          *
89050          * @param node The SourceFile node.
89051          */
89052         function transformCommonJSModule(node) {
89053             startLexicalEnvironment();
89054             var statements = [];
89055             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
89056             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
89057             if (shouldEmitUnderscoreUnderscoreESModule()) {
89058                 ts.append(statements, createUnderscoreUnderscoreESModule());
89059             }
89060             if (ts.length(currentModuleInfo.exportedNames)) {
89061                 ts.append(statements, ts.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames, function (prev, nextId) { return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(ts.idText(nextId))), prev); }, ts.createVoidZero())));
89062             }
89063             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89064             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89065             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
89066             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89067             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
89068             ts.addEmitHelpers(updated, context.readEmitHelpers());
89069             return updated;
89070         }
89071         /**
89072          * Transforms a SourceFile into an AMD module.
89073          *
89074          * @param node The SourceFile node.
89075          */
89076         function transformAMDModule(node) {
89077             var define = ts.createIdentifier("define");
89078             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89079             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
89080             // An AMD define function has the following shape:
89081             //
89082             //     define(id?, dependencies?, factory);
89083             //
89084             // This has the shape of the following:
89085             //
89086             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
89087             //
89088             // The location of the alias in the parameter list in the factory function needs to
89089             // match the position of the module name in the dependency list.
89090             //
89091             // To ensure this is true in cases of modules with no aliases, e.g.:
89092             //
89093             //     import "module"
89094             //
89095             // or
89096             //
89097             //     /// <amd-dependency path= "a.css" />
89098             //
89099             // we need to add modules without alias names to the end of the dependencies list
89100             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89101             // Create an updated SourceFile:
89102             //
89103             //     define(moduleName?, ["module1", "module2"], function ...
89104             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89105                 ts.createExpressionStatement(ts.createCall(define, 
89106                 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89107                     // Add the dependency array argument:
89108                     //
89109                     //     ["require", "exports", module1", "module2", ...]
89110                     ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : __spreadArrays([
89111                         ts.createLiteral("require"),
89112                         ts.createLiteral("exports")
89113                     ], aliasedModuleNames, unaliasedModuleNames)),
89114                     // Add the module body function argument:
89115                     //
89116                     //     function (require, exports, module1, module2) ...
89117                     jsonSourceFile ?
89118                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
89119                         ts.createFunctionExpression(
89120                         /*modifiers*/ undefined, 
89121                         /*asteriskToken*/ undefined, 
89122                         /*name*/ undefined, 
89123                         /*typeParameters*/ undefined, __spreadArrays([
89124                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89125                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89126                         ], importAliasNames), 
89127                         /*type*/ undefined, transformAsynchronousModuleBody(node))
89128                 ])))
89129             ]), 
89130             /*location*/ node.statements));
89131             ts.addEmitHelpers(updated, context.readEmitHelpers());
89132             return updated;
89133         }
89134         /**
89135          * Transforms a SourceFile into a UMD module.
89136          *
89137          * @param node The SourceFile node.
89138          */
89139         function transformUMDModule(node) {
89140             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89141             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89142             var umdHeader = ts.createFunctionExpression(
89143             /*modifiers*/ undefined, 
89144             /*asteriskToken*/ undefined, 
89145             /*name*/ undefined, 
89146             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
89147             /*type*/ undefined, ts.setTextRange(ts.createBlock([
89148                 ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
89149                     ts.createVariableStatement(
89150                     /*modifiers*/ undefined, [
89151                         ts.createVariableDeclaration("v", 
89152                         /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), 
89153                         /*typeArguments*/ undefined, [
89154                             ts.createIdentifier("require"),
89155                             ts.createIdentifier("exports")
89156                         ]))
89157                     ]),
89158                     ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */)
89159                 ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
89160                     ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), 
89161                     /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89162                         ts.createArrayLiteral(__spreadArrays([
89163                             ts.createLiteral("require"),
89164                             ts.createLiteral("exports")
89165                         ], aliasedModuleNames, unaliasedModuleNames)),
89166                         ts.createIdentifier("factory")
89167                     ])))
89168                 ])))
89169             ], 
89170             /*multiLine*/ true), 
89171             /*location*/ undefined));
89172             // Create an updated SourceFile:
89173             //
89174             //  (function (factory) {
89175             //      if (typeof module === "object" && typeof module.exports === "object") {
89176             //          var v = factory(require, exports);
89177             //          if (v !== undefined) module.exports = v;
89178             //      }
89179             //      else if (typeof define === 'function' && define.amd) {
89180             //          define(["require", "exports"], factory);
89181             //      }
89182             //  })(function ...)
89183             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89184                 ts.createExpressionStatement(ts.createCall(umdHeader, 
89185                 /*typeArguments*/ undefined, [
89186                     // Add the module body function argument:
89187                     //
89188                     //     function (require, exports) ...
89189                     ts.createFunctionExpression(
89190                     /*modifiers*/ undefined, 
89191                     /*asteriskToken*/ undefined, 
89192                     /*name*/ undefined, 
89193                     /*typeParameters*/ undefined, __spreadArrays([
89194                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89195                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89196                     ], importAliasNames), 
89197                     /*type*/ undefined, transformAsynchronousModuleBody(node))
89198                 ]))
89199             ]), 
89200             /*location*/ node.statements));
89201             ts.addEmitHelpers(updated, context.readEmitHelpers());
89202             return updated;
89203         }
89204         /**
89205          * Collect the additional asynchronous dependencies for the module.
89206          *
89207          * @param node The source file.
89208          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
89209          */
89210         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
89211             // names of modules with corresponding parameter in the factory function
89212             var aliasedModuleNames = [];
89213             // names of modules with no corresponding parameters in factory function
89214             var unaliasedModuleNames = [];
89215             // names of the parameters in the factory function; these
89216             // parameters need to match the indexes of the corresponding
89217             // module names in aliasedModuleNames.
89218             var importAliasNames = [];
89219             // Fill in amd-dependency tags
89220             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
89221                 var amdDependency = _a[_i];
89222                 if (amdDependency.name) {
89223                     aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89224                     importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
89225                 }
89226                 else {
89227                     unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89228                 }
89229             }
89230             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
89231                 var importNode = _c[_b];
89232                 // Find the name of the external module
89233                 var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89234                 // Find the name of the module alias, if there is one
89235                 var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
89236                 // It is possible that externalModuleName is undefined if it is not string literal.
89237                 // This can happen in the invalid import syntax.
89238                 // E.g : "import * from alias from 'someLib';"
89239                 if (externalModuleName) {
89240                     if (includeNonAmdDependencies && importAliasName) {
89241                         // Set emitFlags on the name of the classDeclaration
89242                         // This is so that when printer will not substitute the identifier
89243                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
89244                         aliasedModuleNames.push(externalModuleName);
89245                         importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
89246                     }
89247                     else {
89248                         unaliasedModuleNames.push(externalModuleName);
89249                     }
89250                 }
89251             }
89252             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
89253         }
89254         function getAMDImportExpressionForImport(node) {
89255             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
89256                 return undefined;
89257             }
89258             var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
89259             var expr = getHelperExpressionForImport(node, name);
89260             if (expr === name) {
89261                 return undefined;
89262             }
89263             return ts.createExpressionStatement(ts.createAssignment(name, expr));
89264         }
89265         /**
89266          * Transforms a SourceFile into an AMD or UMD module body.
89267          *
89268          * @param node The SourceFile node.
89269          */
89270         function transformAsynchronousModuleBody(node) {
89271             startLexicalEnvironment();
89272             var statements = [];
89273             var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
89274             if (shouldEmitUnderscoreUnderscoreESModule()) {
89275                 ts.append(statements, createUnderscoreUnderscoreESModule());
89276             }
89277             if (ts.length(currentModuleInfo.exportedNames)) {
89278                 ts.append(statements, ts.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames, function (prev, nextId) { return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(ts.idText(nextId))), prev); }, ts.createVoidZero())));
89279             }
89280             // Visit each statement of the module body.
89281             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89282             if (moduleKind === ts.ModuleKind.AMD) {
89283                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
89284             }
89285             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89286             // Append the 'export =' statement if provided.
89287             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
89288             // End the lexical environment for the module body
89289             // and merge any new lexical declarations.
89290             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89291             var body = ts.createBlock(statements, /*multiLine*/ true);
89292             if (needUMDDynamicImportHelper) {
89293                 ts.addEmitHelper(body, dynamicImportUMDHelper);
89294             }
89295             return body;
89296         }
89297         /**
89298          * Adds the down-level representation of `export=` to the statement list if one exists
89299          * in the source file.
89300          *
89301          * @param statements The Statement list to modify.
89302          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
89303          * return statement.
89304          */
89305         function addExportEqualsIfNeeded(statements, emitAsReturn) {
89306             if (currentModuleInfo.exportEquals) {
89307                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
89308                 if (expressionResult) {
89309                     if (emitAsReturn) {
89310                         var statement = ts.createReturn(expressionResult);
89311                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89312                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
89313                         statements.push(statement);
89314                     }
89315                     else {
89316                         var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
89317                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89318                         ts.setEmitFlags(statement, 1536 /* NoComments */);
89319                         statements.push(statement);
89320                     }
89321                 }
89322             }
89323         }
89324         //
89325         // Top-Level Source Element Visitors
89326         //
89327         /**
89328          * Visits a node at the top level of the source file.
89329          *
89330          * @param node The node to visit.
89331          */
89332         function sourceElementVisitor(node) {
89333             switch (node.kind) {
89334                 case 254 /* ImportDeclaration */:
89335                     return visitImportDeclaration(node);
89336                 case 253 /* ImportEqualsDeclaration */:
89337                     return visitImportEqualsDeclaration(node);
89338                 case 260 /* ExportDeclaration */:
89339                     return visitExportDeclaration(node);
89340                 case 259 /* ExportAssignment */:
89341                     return visitExportAssignment(node);
89342                 case 225 /* VariableStatement */:
89343                     return visitVariableStatement(node);
89344                 case 244 /* FunctionDeclaration */:
89345                     return visitFunctionDeclaration(node);
89346                 case 245 /* ClassDeclaration */:
89347                     return visitClassDeclaration(node);
89348                 case 328 /* MergeDeclarationMarker */:
89349                     return visitMergeDeclarationMarker(node);
89350                 case 329 /* EndOfDeclarationMarker */:
89351                     return visitEndOfDeclarationMarker(node);
89352                 default:
89353                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89354             }
89355         }
89356         function moduleExpressionElementVisitor(node) {
89357             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
89358             // as export/import statements are only transformed at the top level of a file.
89359             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
89360                 return node;
89361             }
89362             if (ts.isImportCall(node)) {
89363                 return visitImportCallExpression(node);
89364             }
89365             else if (ts.isDestructuringAssignment(node)) {
89366                 return visitDestructuringAssignment(node);
89367             }
89368             else {
89369                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89370             }
89371         }
89372         function destructuringNeedsFlattening(node) {
89373             if (ts.isObjectLiteralExpression(node)) {
89374                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
89375                     var elem = _a[_i];
89376                     switch (elem.kind) {
89377                         case 281 /* PropertyAssignment */:
89378                             if (destructuringNeedsFlattening(elem.initializer)) {
89379                                 return true;
89380                             }
89381                             break;
89382                         case 282 /* ShorthandPropertyAssignment */:
89383                             if (destructuringNeedsFlattening(elem.name)) {
89384                                 return true;
89385                             }
89386                             break;
89387                         case 283 /* SpreadAssignment */:
89388                             if (destructuringNeedsFlattening(elem.expression)) {
89389                                 return true;
89390                             }
89391                             break;
89392                         case 161 /* MethodDeclaration */:
89393                         case 163 /* GetAccessor */:
89394                         case 164 /* SetAccessor */:
89395                             return false;
89396                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
89397                     }
89398                 }
89399             }
89400             else if (ts.isArrayLiteralExpression(node)) {
89401                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
89402                     var elem = _c[_b];
89403                     if (ts.isSpreadElement(elem)) {
89404                         if (destructuringNeedsFlattening(elem.expression)) {
89405                             return true;
89406                         }
89407                     }
89408                     else if (destructuringNeedsFlattening(elem)) {
89409                         return true;
89410                     }
89411                 }
89412             }
89413             else if (ts.isIdentifier(node)) {
89414                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
89415             }
89416             return false;
89417         }
89418         function visitDestructuringAssignment(node) {
89419             if (destructuringNeedsFlattening(node.left)) {
89420                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
89421             }
89422             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89423         }
89424         function visitImportCallExpression(node) {
89425             var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
89426             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
89427             switch (compilerOptions.module) {
89428                 case ts.ModuleKind.AMD:
89429                     return createImportCallExpressionAMD(argument, containsLexicalThis);
89430                 case ts.ModuleKind.UMD:
89431                     return createImportCallExpressionUMD(argument, containsLexicalThis);
89432                 case ts.ModuleKind.CommonJS:
89433                 default:
89434                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
89435             }
89436         }
89437         function createImportCallExpressionUMD(arg, containsLexicalThis) {
89438             // (function (factory) {
89439             //      ... (regular UMD)
89440             // }
89441             // })(function (require, exports, useSyncRequire) {
89442             //      "use strict";
89443             //      Object.defineProperty(exports, "__esModule", { value: true });
89444             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
89445             //      var __resolved = new Promise(function (resolve) { resolve(); });
89446             //      .....
89447             //      __syncRequire
89448             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
89449             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89450             // });
89451             needUMDDynamicImportHelper = true;
89452             if (ts.isSimpleCopiableExpression(arg)) {
89453                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
89454                 return ts.createConditional(
89455                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89456                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
89457                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
89458             }
89459             else {
89460                 var temp = ts.createTempVariable(hoistVariableDeclaration);
89461                 return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
89462                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89463                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
89464                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
89465             }
89466         }
89467         function createImportCallExpressionAMD(arg, containsLexicalThis) {
89468             // improt("./blah")
89469             // emit as
89470             // define(["require", "exports", "blah"], function (require, exports) {
89471             //     ...
89472             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89473             // });
89474             var resolve = ts.createUniqueName("resolve");
89475             var reject = ts.createUniqueName("reject");
89476             var parameters = [
89477                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
89478                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
89479             ];
89480             var body = ts.createBlock([
89481                 ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), 
89482                 /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
89483             ]);
89484             var func;
89485             if (languageVersion >= 2 /* ES2015 */) {
89486                 func = ts.createArrowFunction(
89487                 /*modifiers*/ undefined, 
89488                 /*typeParameters*/ undefined, parameters, 
89489                 /*type*/ undefined, 
89490                 /*equalsGreaterThanToken*/ undefined, body);
89491             }
89492             else {
89493                 func = ts.createFunctionExpression(
89494                 /*modifiers*/ undefined, 
89495                 /*asteriskToken*/ undefined, 
89496                 /*name*/ undefined, 
89497                 /*typeParameters*/ undefined, parameters, 
89498                 /*type*/ undefined, body);
89499                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89500                 // that this new function expression indicates it captures 'this' so that the
89501                 // es2015 transformer will properly substitute 'this' with '_this'.
89502                 if (containsLexicalThis) {
89503                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89504                 }
89505             }
89506             var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
89507             if (compilerOptions.esModuleInterop) {
89508                 context.requestEmitHelper(ts.importStarHelper);
89509                 return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getUnscopedHelperName("__importStar")]);
89510             }
89511             return promise;
89512         }
89513         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
89514             // import("./blah")
89515             // emit as
89516             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
89517             // We have to wrap require in then callback so that require is done in asynchronously
89518             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
89519             var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
89520             var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
89521             if (compilerOptions.esModuleInterop) {
89522                 context.requestEmitHelper(ts.importStarHelper);
89523                 requireCall = ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
89524             }
89525             var func;
89526             if (languageVersion >= 2 /* ES2015 */) {
89527                 func = ts.createArrowFunction(
89528                 /*modifiers*/ undefined, 
89529                 /*typeParameters*/ undefined, 
89530                 /*parameters*/ [], 
89531                 /*type*/ undefined, 
89532                 /*equalsGreaterThanToken*/ undefined, requireCall);
89533             }
89534             else {
89535                 func = ts.createFunctionExpression(
89536                 /*modifiers*/ undefined, 
89537                 /*asteriskToken*/ undefined, 
89538                 /*name*/ undefined, 
89539                 /*typeParameters*/ undefined, 
89540                 /*parameters*/ [], 
89541                 /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
89542                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89543                 // that this new function expression indicates it captures 'this' so that the
89544                 // es2015 transformer will properly substitute 'this' with '_this'.
89545                 if (containsLexicalThis) {
89546                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89547                 }
89548             }
89549             return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
89550         }
89551         function getHelperExpressionForExport(node, innerExpr) {
89552             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89553                 return innerExpr;
89554             }
89555             if (ts.getExportNeedsImportStarHelper(node)) {
89556                 context.requestEmitHelper(ts.importStarHelper);
89557                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89558             }
89559             return innerExpr;
89560         }
89561         function getHelperExpressionForImport(node, innerExpr) {
89562             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89563                 return innerExpr;
89564             }
89565             if (ts.getImportNeedsImportStarHelper(node)) {
89566                 context.requestEmitHelper(ts.importStarHelper);
89567                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89568             }
89569             if (ts.getImportNeedsImportDefaultHelper(node)) {
89570                 context.requestEmitHelper(ts.importDefaultHelper);
89571                 return ts.createCall(ts.getUnscopedHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
89572             }
89573             return innerExpr;
89574         }
89575         /**
89576          * Visits an ImportDeclaration node.
89577          *
89578          * @param node The node to visit.
89579          */
89580         function visitImportDeclaration(node) {
89581             var statements;
89582             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
89583             if (moduleKind !== ts.ModuleKind.AMD) {
89584                 if (!node.importClause) {
89585                     // import "mod";
89586                     return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
89587                 }
89588                 else {
89589                     var variables = [];
89590                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
89591                         // import * as n from "mod";
89592                         variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89593                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89594                     }
89595                     else {
89596                         // import d from "mod";
89597                         // import { x, y } from "mod";
89598                         // import d, { x, y } from "mod";
89599                         // import d, * as n from "mod";
89600                         variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), 
89601                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89602                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
89603                             variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89604                             /*type*/ undefined, ts.getGeneratedNameForNode(node)));
89605                         }
89606                     }
89607                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89608                     /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
89609                     /*location*/ node), 
89610                     /*original*/ node));
89611                 }
89612             }
89613             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
89614                 // import d, * as n from "mod";
89615                 statements = ts.append(statements, ts.createVariableStatement(
89616                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
89617                     ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89618                     /*type*/ undefined, ts.getGeneratedNameForNode(node)), 
89619                     /*location*/ node), 
89620                     /*original*/ node)
89621                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
89622             }
89623             if (hasAssociatedEndOfDeclarationMarker(node)) {
89624                 // Defer exports until we encounter an EndOfDeclarationMarker node
89625                 var id = ts.getOriginalNodeId(node);
89626                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
89627             }
89628             else {
89629                 statements = appendExportsOfImportDeclaration(statements, node);
89630             }
89631             return ts.singleOrMany(statements);
89632         }
89633         /**
89634          * Creates a `require()` call to import an external module.
89635          *
89636          * @param importNode The declararation to import.
89637          */
89638         function createRequireCall(importNode) {
89639             var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89640             var args = [];
89641             if (moduleName) {
89642                 args.push(moduleName);
89643             }
89644             return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
89645         }
89646         /**
89647          * Visits an ImportEqualsDeclaration node.
89648          *
89649          * @param node The node to visit.
89650          */
89651         function visitImportEqualsDeclaration(node) {
89652             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
89653             var statements;
89654             if (moduleKind !== ts.ModuleKind.AMD) {
89655                 if (ts.hasModifier(node, 1 /* Export */)) {
89656                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
89657                 }
89658                 else {
89659                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89660                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89661                         ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), 
89662                         /*type*/ undefined, createRequireCall(node))
89663                     ], 
89664                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
89665                 }
89666             }
89667             else {
89668                 if (ts.hasModifier(node, 1 /* Export */)) {
89669                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
89670                 }
89671             }
89672             if (hasAssociatedEndOfDeclarationMarker(node)) {
89673                 // Defer exports until we encounter an EndOfDeclarationMarker node
89674                 var id = ts.getOriginalNodeId(node);
89675                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
89676             }
89677             else {
89678                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
89679             }
89680             return ts.singleOrMany(statements);
89681         }
89682         /**
89683          * Visits an ExportDeclaration node.
89684          *
89685          * @param The node to visit.
89686          */
89687         function visitExportDeclaration(node) {
89688             if (!node.moduleSpecifier) {
89689                 // Elide export declarations with no module specifier as they are handled
89690                 // elsewhere.
89691                 return undefined;
89692             }
89693             var generatedName = ts.getGeneratedNameForNode(node);
89694             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
89695                 var statements = [];
89696                 // export { x, y } from "mod";
89697                 if (moduleKind !== ts.ModuleKind.AMD) {
89698                     statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89699                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89700                         ts.createVariableDeclaration(generatedName, 
89701                         /*type*/ undefined, createRequireCall(node))
89702                     ])), 
89703                     /*location*/ node), 
89704                     /* original */ node));
89705                 }
89706                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
89707                     var specifier = _a[_i];
89708                     if (languageVersion === 0 /* ES3 */) {
89709                         statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createCreateBindingHelper(context, generatedName, ts.createLiteral(specifier.propertyName || specifier.name), specifier.propertyName ? ts.createLiteral(specifier.name) : undefined)), specifier), specifier));
89710                     }
89711                     else {
89712                         var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
89713                         statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
89714                     }
89715                 }
89716                 return ts.singleOrMany(statements);
89717             }
89718             else if (node.exportClause) {
89719                 var statements = [];
89720                 // export * as ns from "mod";
89721                 statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getSynthesizedClone(node.exportClause.name), moduleKind !== ts.ModuleKind.AMD ?
89722                     getHelperExpressionForExport(node, createRequireCall(node)) :
89723                     ts.createIdentifier(ts.idText(node.exportClause.name)))), node), node));
89724                 return ts.singleOrMany(statements);
89725             }
89726             else {
89727                 // export * from "mod";
89728                 return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
89729             }
89730         }
89731         /**
89732          * Visits an ExportAssignment node.
89733          *
89734          * @param node The node to visit.
89735          */
89736         function visitExportAssignment(node) {
89737             if (node.isExportEquals) {
89738                 return undefined;
89739             }
89740             var statements;
89741             var original = node.original;
89742             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
89743                 // Defer exports until we encounter an EndOfDeclarationMarker node
89744                 var id = ts.getOriginalNodeId(node);
89745                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89746             }
89747             else {
89748                 statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89749             }
89750             return ts.singleOrMany(statements);
89751         }
89752         /**
89753          * Visits a FunctionDeclaration node.
89754          *
89755          * @param node The node to visit.
89756          */
89757         function visitFunctionDeclaration(node) {
89758             var statements;
89759             if (ts.hasModifier(node, 1 /* Export */)) {
89760                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
89761                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89762                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
89763                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
89764                 /*location*/ node), 
89765                 /*original*/ node));
89766             }
89767             else {
89768                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89769             }
89770             if (hasAssociatedEndOfDeclarationMarker(node)) {
89771                 // Defer exports until we encounter an EndOfDeclarationMarker node
89772                 var id = ts.getOriginalNodeId(node);
89773                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89774             }
89775             else {
89776                 statements = appendExportsOfHoistedDeclaration(statements, node);
89777             }
89778             return ts.singleOrMany(statements);
89779         }
89780         /**
89781          * Visits a ClassDeclaration node.
89782          *
89783          * @param node The node to visit.
89784          */
89785         function visitClassDeclaration(node) {
89786             var statements;
89787             if (ts.hasModifier(node, 1 /* Export */)) {
89788                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
89789                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89790                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
89791             }
89792             else {
89793                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89794             }
89795             if (hasAssociatedEndOfDeclarationMarker(node)) {
89796                 // Defer exports until we encounter an EndOfDeclarationMarker node
89797                 var id = ts.getOriginalNodeId(node);
89798                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89799             }
89800             else {
89801                 statements = appendExportsOfHoistedDeclaration(statements, node);
89802             }
89803             return ts.singleOrMany(statements);
89804         }
89805         /**
89806          * Visits a VariableStatement node.
89807          *
89808          * @param node The node to visit.
89809          */
89810         function visitVariableStatement(node) {
89811             var statements;
89812             var variables;
89813             var expressions;
89814             if (ts.hasModifier(node, 1 /* Export */)) {
89815                 var modifiers = void 0;
89816                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
89817                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89818                     var variable = _a[_i];
89819                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
89820                         if (!modifiers) {
89821                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
89822                         }
89823                         variables = ts.append(variables, variable);
89824                     }
89825                     else if (variable.initializer) {
89826                         expressions = ts.append(expressions, transformInitializedVariable(variable));
89827                     }
89828                 }
89829                 if (variables) {
89830                     statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
89831                 }
89832                 if (expressions) {
89833                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
89834                 }
89835             }
89836             else {
89837                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89838             }
89839             if (hasAssociatedEndOfDeclarationMarker(node)) {
89840                 // Defer exports until we encounter an EndOfDeclarationMarker node
89841                 var id = ts.getOriginalNodeId(node);
89842                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
89843             }
89844             else {
89845                 statements = appendExportsOfVariableStatement(statements, node);
89846             }
89847             return ts.singleOrMany(statements);
89848         }
89849         function createAllExportExpressions(name, value, location) {
89850             var exportedNames = getExports(name);
89851             if (exportedNames) {
89852                 // For each additional export of the declaration, apply an export assignment.
89853                 var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
89854                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
89855                     var exportName = exportedNames_1[_i];
89856                     // Mark the node to prevent triggering substitution.
89857                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
89858                     expression = createExportExpression(exportName, expression, /*location*/ location);
89859                 }
89860                 return expression;
89861             }
89862             return ts.createAssignment(name, value);
89863         }
89864         /**
89865          * Transforms an exported variable with an initializer into an expression.
89866          *
89867          * @param node The node to transform.
89868          */
89869         function transformInitializedVariable(node) {
89870             if (ts.isBindingPattern(node.name)) {
89871                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
89872                 /*visitor*/ undefined, context, 0 /* All */, 
89873                 /*needsValue*/ false, createAllExportExpressions);
89874             }
89875             else {
89876                 return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), 
89877                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : ts.createVoidZero());
89878             }
89879         }
89880         /**
89881          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
89882          * and transformed declaration.
89883          *
89884          * @param node The node to visit.
89885          */
89886         function visitMergeDeclarationMarker(node) {
89887             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
89888             // declaration we do not emit a leading variable declaration. To preserve the
89889             // begin/end semantics of the declararation and to properly handle exports
89890             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
89891             //
89892             // To balance the declaration, add the exports of the elided variable
89893             // statement.
89894             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
89895                 var id = ts.getOriginalNodeId(node);
89896                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
89897             }
89898             return node;
89899         }
89900         /**
89901          * Determines whether a node has an associated EndOfDeclarationMarker.
89902          *
89903          * @param node The node to test.
89904          */
89905         function hasAssociatedEndOfDeclarationMarker(node) {
89906             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
89907         }
89908         /**
89909          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
89910          * declaration.
89911          *
89912          * @param node The node to visit.
89913          */
89914         function visitEndOfDeclarationMarker(node) {
89915             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
89916             // end of the transformed declaration. We use this marker to emit any deferred exports
89917             // of the declaration.
89918             var id = ts.getOriginalNodeId(node);
89919             var statements = deferredExports[id];
89920             if (statements) {
89921                 delete deferredExports[id];
89922                 return ts.append(statements, node);
89923             }
89924             return node;
89925         }
89926         /**
89927          * Appends the exports of an ImportDeclaration to a statement list, returning the
89928          * statement list.
89929          *
89930          * @param statements A statement list to which the down-level export statements are to be
89931          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89932          * appended.
89933          * @param decl The declaration whose exports are to be recorded.
89934          */
89935         function appendExportsOfImportDeclaration(statements, decl) {
89936             if (currentModuleInfo.exportEquals) {
89937                 return statements;
89938             }
89939             var importClause = decl.importClause;
89940             if (!importClause) {
89941                 return statements;
89942             }
89943             if (importClause.name) {
89944                 statements = appendExportsOfDeclaration(statements, importClause);
89945             }
89946             var namedBindings = importClause.namedBindings;
89947             if (namedBindings) {
89948                 switch (namedBindings.kind) {
89949                     case 256 /* NamespaceImport */:
89950                         statements = appendExportsOfDeclaration(statements, namedBindings);
89951                         break;
89952                     case 257 /* NamedImports */:
89953                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
89954                             var importBinding = _a[_i];
89955                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
89956                         }
89957                         break;
89958                 }
89959             }
89960             return statements;
89961         }
89962         /**
89963          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
89964          * statement list.
89965          *
89966          * @param statements A statement list to which the down-level export statements are to be
89967          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89968          * appended.
89969          * @param decl The declaration whose exports are to be recorded.
89970          */
89971         function appendExportsOfImportEqualsDeclaration(statements, decl) {
89972             if (currentModuleInfo.exportEquals) {
89973                 return statements;
89974             }
89975             return appendExportsOfDeclaration(statements, decl);
89976         }
89977         /**
89978          * Appends the exports of a VariableStatement to a statement list, returning the statement
89979          * list.
89980          *
89981          * @param statements A statement list to which the down-level export statements are to be
89982          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89983          * appended.
89984          * @param node The VariableStatement whose exports are to be recorded.
89985          */
89986         function appendExportsOfVariableStatement(statements, node) {
89987             if (currentModuleInfo.exportEquals) {
89988                 return statements;
89989             }
89990             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89991                 var decl = _a[_i];
89992                 statements = appendExportsOfBindingElement(statements, decl);
89993             }
89994             return statements;
89995         }
89996         /**
89997          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
89998          * returning the statement list.
89999          *
90000          * @param statements A statement list to which the down-level export statements are to be
90001          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90002          * appended.
90003          * @param decl The declaration whose exports are to be recorded.
90004          */
90005         function appendExportsOfBindingElement(statements, decl) {
90006             if (currentModuleInfo.exportEquals) {
90007                 return statements;
90008             }
90009             if (ts.isBindingPattern(decl.name)) {
90010                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
90011                     var element = _a[_i];
90012                     if (!ts.isOmittedExpression(element)) {
90013                         statements = appendExportsOfBindingElement(statements, element);
90014                     }
90015                 }
90016             }
90017             else if (!ts.isGeneratedIdentifier(decl.name)) {
90018                 statements = appendExportsOfDeclaration(statements, decl);
90019             }
90020             return statements;
90021         }
90022         /**
90023          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
90024          * returning the statement list.
90025          *
90026          * @param statements A statement list to which the down-level export statements are to be
90027          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90028          * appended.
90029          * @param decl The declaration whose exports are to be recorded.
90030          */
90031         function appendExportsOfHoistedDeclaration(statements, decl) {
90032             if (currentModuleInfo.exportEquals) {
90033                 return statements;
90034             }
90035             if (ts.hasModifier(decl, 1 /* Export */)) {
90036                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
90037                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
90038             }
90039             if (decl.name) {
90040                 statements = appendExportsOfDeclaration(statements, decl);
90041             }
90042             return statements;
90043         }
90044         /**
90045          * Appends the exports of a declaration to a statement list, returning the statement list.
90046          *
90047          * @param statements A statement list to which the down-level export statements are to be
90048          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90049          * appended.
90050          * @param decl The declaration to export.
90051          */
90052         function appendExportsOfDeclaration(statements, decl, liveBinding) {
90053             var name = ts.getDeclarationName(decl);
90054             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
90055             if (exportSpecifiers) {
90056                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
90057                     var exportSpecifier = exportSpecifiers_1[_i];
90058                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
90059                 }
90060             }
90061             return statements;
90062         }
90063         /**
90064          * Appends the down-level representation of an export to a statement list, returning the
90065          * statement list.
90066          *
90067          * @param statements A statement list to which the down-level export statements are to be
90068          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90069          * appended.
90070          * @param exportName The name of the export.
90071          * @param expression The expression to export.
90072          * @param location The location to use for source maps and comments for the export.
90073          * @param allowComments Whether to allow comments on the export.
90074          */
90075         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
90076             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
90077             return statements;
90078         }
90079         function createUnderscoreUnderscoreESModule() {
90080             var statement;
90081             if (languageVersion === 0 /* ES3 */) {
90082                 statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
90083             }
90084             else {
90085                 statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90086                 /*typeArguments*/ undefined, [
90087                     ts.createIdentifier("exports"),
90088                     ts.createLiteral("__esModule"),
90089                     ts.createObjectLiteral([
90090                         ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
90091                     ])
90092                 ]));
90093             }
90094             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
90095             return statement;
90096         }
90097         /**
90098          * Creates a call to the current file's export function to export a value.
90099          *
90100          * @param name The bound name of the export.
90101          * @param value The exported value.
90102          * @param location The location to use for source maps and comments for the export.
90103          * @param allowComments An optional value indicating whether to emit comments for the statement.
90104          */
90105         function createExportStatement(name, value, location, allowComments, liveBinding) {
90106             var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
90107             ts.startOnNewLine(statement);
90108             if (!allowComments) {
90109                 ts.setEmitFlags(statement, 1536 /* NoComments */);
90110             }
90111             return statement;
90112         }
90113         /**
90114          * Creates a call to the current file's export function to export a value.
90115          *
90116          * @param name The bound name of the export.
90117          * @param value The exported value.
90118          * @param location The location to use for source maps and comments for the export.
90119          */
90120         function createExportExpression(name, value, location, liveBinding) {
90121             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90122             /*typeArguments*/ undefined, [
90123                 ts.createIdentifier("exports"),
90124                 ts.createLiteral(name),
90125                 ts.createObjectLiteral([
90126                     ts.createPropertyAssignment("enumerable", ts.createLiteral(/*value*/ true)),
90127                     ts.createPropertyAssignment("get", ts.createFunctionExpression(
90128                     /*modifiers*/ undefined, 
90129                     /*asteriskToken*/ undefined, 
90130                     /*name*/ undefined, 
90131                     /*typeParameters*/ undefined, 
90132                     /*parameters*/ [], 
90133                     /*type*/ undefined, ts.createBlock([ts.createReturn(value)])))
90134                 ])
90135             ]) : ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
90136         }
90137         //
90138         // Modifier Visitors
90139         //
90140         /**
90141          * Visit nodes to elide module-specific modifiers.
90142          *
90143          * @param node The node to visit.
90144          */
90145         function modifierVisitor(node) {
90146             // Elide module-specific modifiers.
90147             switch (node.kind) {
90148                 case 89 /* ExportKeyword */:
90149                 case 84 /* DefaultKeyword */:
90150                     return undefined;
90151             }
90152             return node;
90153         }
90154         //
90155         // Emit Notification
90156         //
90157         /**
90158          * Hook for node emit notifications.
90159          *
90160          * @param hint A hint as to the intended usage of the node.
90161          * @param node The node to emit.
90162          * @param emit A callback used to emit the node in the printer.
90163          */
90164         function onEmitNode(hint, node, emitCallback) {
90165             if (node.kind === 290 /* SourceFile */) {
90166                 currentSourceFile = node;
90167                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
90168                 noSubstitution = [];
90169                 previousOnEmitNode(hint, node, emitCallback);
90170                 currentSourceFile = undefined;
90171                 currentModuleInfo = undefined;
90172                 noSubstitution = undefined;
90173             }
90174             else {
90175                 previousOnEmitNode(hint, node, emitCallback);
90176             }
90177         }
90178         //
90179         // Substitutions
90180         //
90181         /**
90182          * Hooks node substitutions.
90183          *
90184          * @param hint A hint as to the intended usage of the node.
90185          * @param node The node to substitute.
90186          */
90187         function onSubstituteNode(hint, node) {
90188             node = previousOnSubstituteNode(hint, node);
90189             if (node.id && noSubstitution[node.id]) {
90190                 return node;
90191             }
90192             if (hint === 1 /* Expression */) {
90193                 return substituteExpression(node);
90194             }
90195             else if (ts.isShorthandPropertyAssignment(node)) {
90196                 return substituteShorthandPropertyAssignment(node);
90197             }
90198             return node;
90199         }
90200         /**
90201          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
90202          * or exported symbol.
90203          *
90204          * @param node The node to substitute.
90205          */
90206         function substituteShorthandPropertyAssignment(node) {
90207             var name = node.name;
90208             var exportedOrImportedName = substituteExpressionIdentifier(name);
90209             if (exportedOrImportedName !== name) {
90210                 // A shorthand property with an assignment initializer is probably part of a
90211                 // destructuring assignment
90212                 if (node.objectAssignmentInitializer) {
90213                     var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
90214                     return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
90215                 }
90216                 return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
90217             }
90218             return node;
90219         }
90220         /**
90221          * Substitution for an Expression that may contain an imported or exported symbol.
90222          *
90223          * @param node The node to substitute.
90224          */
90225         function substituteExpression(node) {
90226             switch (node.kind) {
90227                 case 75 /* Identifier */:
90228                     return substituteExpressionIdentifier(node);
90229                 case 209 /* BinaryExpression */:
90230                     return substituteBinaryExpression(node);
90231                 case 208 /* PostfixUnaryExpression */:
90232                 case 207 /* PrefixUnaryExpression */:
90233                     return substituteUnaryExpression(node);
90234             }
90235             return node;
90236         }
90237         /**
90238          * Substitution for an Identifier expression that may contain an imported or exported
90239          * symbol.
90240          *
90241          * @param node The node to substitute.
90242          */
90243         function substituteExpressionIdentifier(node) {
90244             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
90245                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
90246                 if (externalHelpersModuleName) {
90247                     return ts.createPropertyAccess(externalHelpersModuleName, node);
90248                 }
90249                 return node;
90250             }
90251             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
90252                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
90253                 if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
90254                     return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), 
90255                     /*location*/ node);
90256                 }
90257                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
90258                 if (importDeclaration) {
90259                     if (ts.isImportClause(importDeclaration)) {
90260                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
90261                         /*location*/ node);
90262                     }
90263                     else if (ts.isImportSpecifier(importDeclaration)) {
90264                         var name = importDeclaration.propertyName || importDeclaration.name;
90265                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), 
90266                         /*location*/ node);
90267                     }
90268                 }
90269             }
90270             return node;
90271         }
90272         /**
90273          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
90274          *
90275          * @param node The node to substitute.
90276          */
90277         function substituteBinaryExpression(node) {
90278             // When we see an assignment expression whose left-hand side is an exported symbol,
90279             // we should ensure all exports of that symbol are updated with the correct value.
90280             //
90281             // - We do not substitute generated identifiers for any reason.
90282             // - We do not substitute identifiers tagged with the LocalName flag.
90283             // - We do not substitute identifiers that were originally the name of an enum or
90284             //   namespace due to how they are transformed in TypeScript.
90285             // - We only substitute identifiers that are exported at the top level.
90286             if (ts.isAssignmentOperator(node.operatorToken.kind)
90287                 && ts.isIdentifier(node.left)
90288                 && !ts.isGeneratedIdentifier(node.left)
90289                 && !ts.isLocalName(node.left)
90290                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
90291                 var exportedNames = getExports(node.left);
90292                 if (exportedNames) {
90293                     // For each additional export of the declaration, apply an export assignment.
90294                     var expression = node;
90295                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
90296                         var exportName = exportedNames_2[_i];
90297                         // Mark the node to prevent triggering this rule again.
90298                         noSubstitution[ts.getNodeId(expression)] = true;
90299                         expression = createExportExpression(exportName, expression, /*location*/ node);
90300                     }
90301                     return expression;
90302                 }
90303             }
90304             return node;
90305         }
90306         /**
90307          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
90308          *
90309          * @param node The node to substitute.
90310          */
90311         function substituteUnaryExpression(node) {
90312             // When we see a prefix or postfix increment expression whose operand is an exported
90313             // symbol, we should ensure all exports of that symbol are updated with the correct
90314             // value.
90315             //
90316             // - We do not substitute generated identifiers for any reason.
90317             // - We do not substitute identifiers tagged with the LocalName flag.
90318             // - We do not substitute identifiers that were originally the name of an enum or
90319             //   namespace due to how they are transformed in TypeScript.
90320             // - We only substitute identifiers that are exported at the top level.
90321             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
90322                 && ts.isIdentifier(node.operand)
90323                 && !ts.isGeneratedIdentifier(node.operand)
90324                 && !ts.isLocalName(node.operand)
90325                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
90326                 var exportedNames = getExports(node.operand);
90327                 if (exportedNames) {
90328                     var expression = node.kind === 208 /* PostfixUnaryExpression */
90329                         ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), ts.createLiteral(1)), 
90330                         /*location*/ node)
90331                         : node;
90332                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
90333                         var exportName = exportedNames_3[_i];
90334                         // Mark the node to prevent triggering this rule again.
90335                         noSubstitution[ts.getNodeId(expression)] = true;
90336                         expression = createExportExpression(exportName, expression);
90337                     }
90338                     return expression;
90339                 }
90340             }
90341             return node;
90342         }
90343         /**
90344          * Gets the additional exports of a name.
90345          *
90346          * @param name The name.
90347          */
90348         function getExports(name) {
90349             if (!ts.isGeneratedIdentifier(name)) {
90350                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
90351                     || resolver.getReferencedValueDeclaration(name);
90352                 if (valueDeclaration) {
90353                     return currentModuleInfo
90354                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
90355                 }
90356             }
90357         }
90358     }
90359     ts.transformModule = transformModule;
90360     ts.createBindingHelper = {
90361         name: "typescript:commonjscreatebinding",
90362         importName: "__createBinding",
90363         scoped: false,
90364         priority: 1,
90365         text: "\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));"
90366     };
90367     function createCreateBindingHelper(context, module, inputName, outputName) {
90368         context.requestEmitHelper(ts.createBindingHelper);
90369         return ts.createCall(ts.getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, __spreadArrays([ts.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
90370     }
90371     ts.setModuleDefaultHelper = {
90372         name: "typescript:commonjscreatevalue",
90373         importName: "__setModuleDefault",
90374         scoped: false,
90375         priority: 1,
90376         text: "\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n    o[\"default\"] = v;\n});"
90377     };
90378     // emit output for the __export helper function
90379     var exportStarHelper = {
90380         name: "typescript:export-star",
90381         importName: "__exportStar",
90382         scoped: false,
90383         dependencies: [ts.createBindingHelper],
90384         priority: 2,
90385         text: "\n            var __exportStar = (this && this.__exportStar) || function(m, exports) {\n                for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n            };"
90386     };
90387     function createExportStarHelper(context, module) {
90388         context.requestEmitHelper(exportStarHelper);
90389         return ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]);
90390     }
90391     // emit helper for dynamic import
90392     var dynamicImportUMDHelper = {
90393         name: "typescript:dynamicimport-sync-require",
90394         scoped: true,
90395         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
90396     };
90397     // emit helper for `import * as Name from "foo"`
90398     ts.importStarHelper = {
90399         name: "typescript:commonjsimportstar",
90400         importName: "__importStar",
90401         scoped: false,
90402         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
90403         priority: 2,
90404         text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n    if (mod && mod.__esModule) return mod;\n    var result = {};\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n    __setModuleDefault(result, mod);\n    return result;\n};"
90405     };
90406     // emit helper for `import Name from "foo"`
90407     ts.importDefaultHelper = {
90408         name: "typescript:commonjsimportdefault",
90409         importName: "__importDefault",
90410         scoped: false,
90411         text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
90412     };
90413 })(ts || (ts = {}));
90414 /*@internal*/
90415 var ts;
90416 (function (ts) {
90417     function transformSystemModule(context) {
90418         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
90419         var compilerOptions = context.getCompilerOptions();
90420         var resolver = context.getEmitResolver();
90421         var host = context.getEmitHost();
90422         var previousOnSubstituteNode = context.onSubstituteNode;
90423         var previousOnEmitNode = context.onEmitNode;
90424         context.onSubstituteNode = onSubstituteNode;
90425         context.onEmitNode = onEmitNode;
90426         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers for imported symbols.
90427         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
90428         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
90429         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
90430         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
90431         context.enableSubstitution(219 /* MetaProperty */); // Substitutes 'import.meta'
90432         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
90433         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
90434         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
90435         var exportFunctionsMap = []; // The export function associated with a source file.
90436         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
90437         var contextObjectMap = []; // The context object associated with a source file.
90438         var currentSourceFile; // The current file.
90439         var moduleInfo; // ExternalModuleInfo for the current file.
90440         var exportFunction; // The export function for the current file.
90441         var contextObject; // The context object for the current file.
90442         var hoistedStatements;
90443         var enclosingBlockScopedContainer;
90444         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
90445         return ts.chainBundle(transformSourceFile);
90446         /**
90447          * Transforms the module aspects of a SourceFile.
90448          *
90449          * @param node The SourceFile node.
90450          */
90451         function transformSourceFile(node) {
90452             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
90453                 return node;
90454             }
90455             var id = ts.getOriginalNodeId(node);
90456             currentSourceFile = node;
90457             enclosingBlockScopedContainer = node;
90458             // System modules have the following shape:
90459             //
90460             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
90461             //
90462             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
90463             // is used to publish exported values. 'exports' returns its 'value' argument so in
90464             // most cases expressions that mutate exported values can be rewritten as:
90465             //
90466             //     expr -> exports('name', expr)
90467             //
90468             // The only exception in this rule is postfix unary operators,
90469             // see comment to 'substitutePostfixUnaryExpression' for more details
90470             // Collect information about the external module and dependency groups.
90471             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
90472             // Make sure that the name of the 'exports' function does not conflict with
90473             // existing identifiers.
90474             exportFunction = ts.createUniqueName("exports");
90475             exportFunctionsMap[id] = exportFunction;
90476             contextObject = contextObjectMap[id] = ts.createUniqueName("context");
90477             // Add the body of the module.
90478             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
90479             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
90480             var moduleBodyFunction = ts.createFunctionExpression(
90481             /*modifiers*/ undefined, 
90482             /*asteriskToken*/ undefined, 
90483             /*name*/ undefined, 
90484             /*typeParameters*/ undefined, [
90485                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
90486                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
90487             ], 
90488             /*type*/ undefined, moduleBodyBlock);
90489             // Write the call to `System.register`
90490             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
90491             // So the helper will be emit at the correct position instead of at the top of the source-file
90492             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
90493             var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
90494             var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
90495                 ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), 
90496                 /*typeArguments*/ undefined, moduleName
90497                     ? [moduleName, dependencies, moduleBodyFunction]
90498                     : [dependencies, moduleBodyFunction]))
90499             ]), node.statements)), 1024 /* NoTrailingComments */);
90500             if (!(compilerOptions.outFile || compilerOptions.out)) {
90501                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
90502             }
90503             if (noSubstitution) {
90504                 noSubstitutionMap[id] = noSubstitution;
90505                 noSubstitution = undefined;
90506             }
90507             currentSourceFile = undefined;
90508             moduleInfo = undefined;
90509             exportFunction = undefined;
90510             contextObject = undefined;
90511             hoistedStatements = undefined;
90512             enclosingBlockScopedContainer = undefined;
90513             return ts.aggregateTransformFlags(updated);
90514         }
90515         /**
90516          * Collects the dependency groups for this files imports.
90517          *
90518          * @param externalImports The imports for the file.
90519          */
90520         function collectDependencyGroups(externalImports) {
90521             var groupIndices = ts.createMap();
90522             var dependencyGroups = [];
90523             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
90524                 var externalImport = externalImports_1[_i];
90525                 var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
90526                 if (externalModuleName) {
90527                     var text = externalModuleName.text;
90528                     var groupIndex = groupIndices.get(text);
90529                     if (groupIndex !== undefined) {
90530                         // deduplicate/group entries in dependency list by the dependency name
90531                         dependencyGroups[groupIndex].externalImports.push(externalImport);
90532                     }
90533                     else {
90534                         groupIndices.set(text, dependencyGroups.length);
90535                         dependencyGroups.push({
90536                             name: externalModuleName,
90537                             externalImports: [externalImport]
90538                         });
90539                     }
90540                 }
90541             }
90542             return dependencyGroups;
90543         }
90544         /**
90545          * Adds the statements for the module body function for the source file.
90546          *
90547          * @param node The source file for the module.
90548          * @param dependencyGroups The grouped dependencies of the module.
90549          */
90550         function createSystemModuleBody(node, dependencyGroups) {
90551             // Shape of the body in system modules:
90552             //
90553             //  function (exports) {
90554             //      <list of local aliases for imports>
90555             //      <hoisted variable declarations>
90556             //      <hoisted function declarations>
90557             //      return {
90558             //          setters: [
90559             //              <list of setter function for imports>
90560             //          ],
90561             //          execute: function() {
90562             //              <module statements>
90563             //          }
90564             //      }
90565             //      <temp declarations>
90566             //  }
90567             //
90568             // i.e:
90569             //
90570             //   import {x} from 'file1'
90571             //   var y = 1;
90572             //   export function foo() { return y + x(); }
90573             //   console.log(y);
90574             //
90575             // Will be transformed to:
90576             //
90577             //  function(exports) {
90578             //      function foo() { return y + file_1.x(); }
90579             //      exports("foo", foo);
90580             //      var file_1, y;
90581             //      return {
90582             //          setters: [
90583             //              function(v) { file_1 = v }
90584             //          ],
90585             //          execute(): function() {
90586             //              y = 1;
90587             //              console.log(y);
90588             //          }
90589             //      };
90590             //  }
90591             var statements = [];
90592             // We start a new lexical environment in this function body, but *not* in the
90593             // body of the execute function. This allows us to emit temporary declarations
90594             // only in the outer module body and not in the inner one.
90595             startLexicalEnvironment();
90596             // Add any prologue directives.
90597             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
90598             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
90599             // var __moduleName = context_1 && context_1.id;
90600             statements.push(ts.createVariableStatement(
90601             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90602                 ts.createVariableDeclaration("__moduleName", 
90603                 /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
90604             ])));
90605             // Visit the synthetic external helpers import declaration if present
90606             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
90607             // Visit the statements of the source file, emitting any transformations into
90608             // the `executeStatements` array. We do this *before* we fill the `setters` array
90609             // as we both emit transformations as well as aggregate some data used when creating
90610             // setters. This allows us to reduce the number of times we need to loop through the
90611             // statements of the source file.
90612             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
90613             // Emit early exports for function declarations.
90614             ts.addRange(statements, hoistedStatements);
90615             // We emit hoisted variables early to align roughly with our previous emit output.
90616             // Two key differences in this approach are:
90617             // - Temporary variables will appear at the top rather than at the bottom of the file
90618             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
90619             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
90620             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
90621                 ts.createModifiersFromModifierFlags(256 /* Async */) :
90622                 undefined;
90623             var moduleObject = ts.createObjectLiteral([
90624                 ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
90625                 ts.createPropertyAssignment("execute", ts.createFunctionExpression(modifiers, 
90626                 /*asteriskToken*/ undefined, 
90627                 /*name*/ undefined, 
90628                 /*typeParameters*/ undefined, 
90629                 /*parameters*/ [], 
90630                 /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
90631             ]);
90632             moduleObject.multiLine = true;
90633             statements.push(ts.createReturn(moduleObject));
90634             return ts.createBlock(statements, /*multiLine*/ true);
90635         }
90636         /**
90637          * Adds an exportStar function to a statement list if it is needed for the file.
90638          *
90639          * @param statements A statement list.
90640          */
90641         function addExportStarIfNeeded(statements) {
90642             if (!moduleInfo.hasExportStarsToExportValues) {
90643                 return;
90644             }
90645             // when resolving exports local exported entries/indirect exported entries in the module
90646             // should always win over entries with similar names that were added via star exports
90647             // to support this we store names of local/indirect exported entries in a set.
90648             // this set is used to filter names brought by star expors.
90649             // local names set should only be added if we have anything exported
90650             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
90651                 // no exported declarations (export var ...) or export specifiers (export {x})
90652                 // check if we have any non star export declarations.
90653                 var hasExportDeclarationWithExportClause = false;
90654                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
90655                     var externalImport = _a[_i];
90656                     if (externalImport.kind === 260 /* ExportDeclaration */ && externalImport.exportClause) {
90657                         hasExportDeclarationWithExportClause = true;
90658                         break;
90659                     }
90660                 }
90661                 if (!hasExportDeclarationWithExportClause) {
90662                     // we still need to emit exportStar helper
90663                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
90664                     statements.push(exportStarFunction_1);
90665                     return exportStarFunction_1.name;
90666                 }
90667             }
90668             var exportedNames = [];
90669             if (moduleInfo.exportedNames) {
90670                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
90671                     var exportedLocalName = _c[_b];
90672                     if (exportedLocalName.escapedText === "default") {
90673                         continue;
90674                     }
90675                     // write name of exported declaration, i.e 'export var x...'
90676                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
90677                 }
90678             }
90679             for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
90680                 var externalImport = _e[_d];
90681                 if (externalImport.kind !== 260 /* ExportDeclaration */) {
90682                     continue;
90683                 }
90684                 if (!externalImport.exportClause) {
90685                     // export * from ...
90686                     continue;
90687                 }
90688                 if (ts.isNamedExports(externalImport.exportClause)) {
90689                     for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
90690                         var element = _g[_f];
90691                         // write name of indirectly exported entry, i.e. 'export {x} from ...'
90692                         exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
90693                     }
90694                 }
90695                 else {
90696                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(externalImport.exportClause.name)), ts.createTrue()));
90697                 }
90698             }
90699             var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
90700             statements.push(ts.createVariableStatement(
90701             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90702                 ts.createVariableDeclaration(exportedNamesStorageRef, 
90703                 /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
90704             ])));
90705             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
90706             statements.push(exportStarFunction);
90707             return exportStarFunction.name;
90708         }
90709         /**
90710          * Creates an exportStar function for the file, with an optional set of excluded local
90711          * names.
90712          *
90713          * @param localNames An optional reference to an object containing a set of excluded local
90714          * names.
90715          */
90716         function createExportStarFunction(localNames) {
90717             var exportStarFunction = ts.createUniqueName("exportStar");
90718             var m = ts.createIdentifier("m");
90719             var n = ts.createIdentifier("n");
90720             var exports = ts.createIdentifier("exports");
90721             var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
90722             if (localNames) {
90723                 condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), 
90724                 /*typeArguments*/ undefined, [n])));
90725             }
90726             return ts.createFunctionDeclaration(
90727             /*decorators*/ undefined, 
90728             /*modifiers*/ undefined, 
90729             /*asteriskToken*/ undefined, exportStarFunction, 
90730             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
90731             /*type*/ undefined, ts.createBlock([
90732                 ts.createVariableStatement(
90733                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
90734                     ts.createVariableDeclaration(exports, 
90735                     /*type*/ undefined, ts.createObjectLiteral([]))
90736                 ])),
90737                 ts.createForIn(ts.createVariableDeclarationList([
90738                     ts.createVariableDeclaration(n, /*type*/ undefined)
90739                 ]), m, ts.createBlock([
90740                     ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
90741                 ])),
90742                 ts.createExpressionStatement(ts.createCall(exportFunction, 
90743                 /*typeArguments*/ undefined, [exports]))
90744             ], /*multiline*/ true));
90745         }
90746         /**
90747          * Creates an array setter callbacks for each dependency group.
90748          *
90749          * @param exportStarFunction A reference to an exportStarFunction for the file.
90750          * @param dependencyGroups An array of grouped dependencies.
90751          */
90752         function createSettersArray(exportStarFunction, dependencyGroups) {
90753             var setters = [];
90754             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
90755                 var group_2 = dependencyGroups_1[_i];
90756                 // derive a unique name for parameter from the first named entry in the group
90757                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
90758                 var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
90759                 var statements = [];
90760                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
90761                     var entry = _b[_a];
90762                     var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
90763                     switch (entry.kind) {
90764                         case 254 /* ImportDeclaration */:
90765                             if (!entry.importClause) {
90766                                 // 'import "..."' case
90767                                 // module is imported only for side-effects, no emit required
90768                                 break;
90769                             }
90770                         // falls through
90771                         case 253 /* ImportEqualsDeclaration */:
90772                             ts.Debug.assert(importVariableName !== undefined);
90773                             // save import into the local
90774                             statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
90775                             break;
90776                         case 260 /* ExportDeclaration */:
90777                             ts.Debug.assert(importVariableName !== undefined);
90778                             if (entry.exportClause) {
90779                                 if (ts.isNamedExports(entry.exportClause)) {
90780                                     //  export {a, b as c} from 'foo'
90781                                     //
90782                                     // emit as:
90783                                     //
90784                                     //  exports_({
90785                                     //     "a": _["a"],
90786                                     //     "c": _["b"]
90787                                     //  });
90788                                     var properties = [];
90789                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
90790                                         var e = _d[_c];
90791                                         properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
90792                                     }
90793                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90794                                     /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
90795                                 }
90796                                 else {
90797                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90798                                     /*typeArguments*/ undefined, [
90799                                         ts.createLiteral(ts.idText(entry.exportClause.name)),
90800                                         parameterName
90801                                     ])));
90802                                 }
90803                             }
90804                             else {
90805                                 //  export * from 'foo'
90806                                 //
90807                                 // emit as:
90808                                 //
90809                                 //  exportStar(foo_1_1);
90810                                 statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, 
90811                                 /*typeArguments*/ undefined, [parameterName])));
90812                             }
90813                             break;
90814                     }
90815                 }
90816                 setters.push(ts.createFunctionExpression(
90817                 /*modifiers*/ undefined, 
90818                 /*asteriskToken*/ undefined, 
90819                 /*name*/ undefined, 
90820                 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
90821                 /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
90822             }
90823             return ts.createArrayLiteral(setters, /*multiLine*/ true);
90824         }
90825         //
90826         // Top-level Source Element Visitors
90827         //
90828         /**
90829          * Visit source elements at the top-level of a module.
90830          *
90831          * @param node The node to visit.
90832          */
90833         function sourceElementVisitor(node) {
90834             switch (node.kind) {
90835                 case 254 /* ImportDeclaration */:
90836                     return visitImportDeclaration(node);
90837                 case 253 /* ImportEqualsDeclaration */:
90838                     return visitImportEqualsDeclaration(node);
90839                 case 260 /* ExportDeclaration */:
90840                     return visitExportDeclaration(node);
90841                 case 259 /* ExportAssignment */:
90842                     return visitExportAssignment(node);
90843                 default:
90844                     return nestedElementVisitor(node);
90845             }
90846         }
90847         /**
90848          * Visits an ImportDeclaration node.
90849          *
90850          * @param node The node to visit.
90851          */
90852         function visitImportDeclaration(node) {
90853             var statements;
90854             if (node.importClause) {
90855                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90856             }
90857             if (hasAssociatedEndOfDeclarationMarker(node)) {
90858                 // Defer exports until we encounter an EndOfDeclarationMarker node
90859                 var id = ts.getOriginalNodeId(node);
90860                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
90861             }
90862             else {
90863                 statements = appendExportsOfImportDeclaration(statements, node);
90864             }
90865             return ts.singleOrMany(statements);
90866         }
90867         function visitExportDeclaration(node) {
90868             ts.Debug.assertIsDefined(node);
90869             return undefined;
90870         }
90871         /**
90872          * Visits an ImportEqualsDeclaration node.
90873          *
90874          * @param node The node to visit.
90875          */
90876         function visitImportEqualsDeclaration(node) {
90877             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
90878             var statements;
90879             hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90880             if (hasAssociatedEndOfDeclarationMarker(node)) {
90881                 // Defer exports until we encounter an EndOfDeclarationMarker node
90882                 var id = ts.getOriginalNodeId(node);
90883                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
90884             }
90885             else {
90886                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
90887             }
90888             return ts.singleOrMany(statements);
90889         }
90890         /**
90891          * Visits an ExportAssignment node.
90892          *
90893          * @param node The node to visit.
90894          */
90895         function visitExportAssignment(node) {
90896             if (node.isExportEquals) {
90897                 // Elide `export=` as it is illegal in a SystemJS module.
90898                 return undefined;
90899             }
90900             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
90901             var original = node.original;
90902             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
90903                 // Defer exports until we encounter an EndOfDeclarationMarker node
90904                 var id = ts.getOriginalNodeId(node);
90905                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
90906             }
90907             else {
90908                 return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
90909             }
90910         }
90911         /**
90912          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
90913          *
90914          * @param node The node to visit.
90915          */
90916         function visitFunctionDeclaration(node) {
90917             if (ts.hasModifier(node, 1 /* Export */)) {
90918                 hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
90919                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
90920                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
90921             }
90922             else {
90923                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
90924             }
90925             if (hasAssociatedEndOfDeclarationMarker(node)) {
90926                 // Defer exports until we encounter an EndOfDeclarationMarker node
90927                 var id = ts.getOriginalNodeId(node);
90928                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90929             }
90930             else {
90931                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
90932             }
90933             return undefined;
90934         }
90935         /**
90936          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
90937          *
90938          * @param node The node to visit.
90939          */
90940         function visitClassDeclaration(node) {
90941             var statements;
90942             // Hoist the name of the class declaration to the outer module body function.
90943             var name = ts.getLocalName(node);
90944             hoistVariableDeclaration(name);
90945             // Rewrite the class declaration into an assignment of a class expression.
90946             statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
90947             /*modifiers*/ undefined, node.name, 
90948             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
90949             if (hasAssociatedEndOfDeclarationMarker(node)) {
90950                 // Defer exports until we encounter an EndOfDeclarationMarker node
90951                 var id = ts.getOriginalNodeId(node);
90952                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90953             }
90954             else {
90955                 statements = appendExportsOfHoistedDeclaration(statements, node);
90956             }
90957             return ts.singleOrMany(statements);
90958         }
90959         /**
90960          * Visits a variable statement, hoisting declared names to the top-level module body.
90961          * Each declaration is rewritten into an assignment expression.
90962          *
90963          * @param node The node to visit.
90964          */
90965         function visitVariableStatement(node) {
90966             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
90967                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
90968             }
90969             var expressions;
90970             var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
90971             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
90972             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
90973                 var variable = _a[_i];
90974                 if (variable.initializer) {
90975                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
90976                 }
90977                 else {
90978                     hoistBindingElement(variable);
90979                 }
90980             }
90981             var statements;
90982             if (expressions) {
90983                 statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
90984             }
90985             if (isMarkedDeclaration) {
90986                 // Defer exports until we encounter an EndOfDeclarationMarker node
90987                 var id = ts.getOriginalNodeId(node);
90988                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
90989             }
90990             else {
90991                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
90992             }
90993             return ts.singleOrMany(statements);
90994         }
90995         /**
90996          * Hoists the declared names of a VariableDeclaration or BindingElement.
90997          *
90998          * @param node The declaration to hoist.
90999          */
91000         function hoistBindingElement(node) {
91001             if (ts.isBindingPattern(node.name)) {
91002                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
91003                     var element = _a[_i];
91004                     if (!ts.isOmittedExpression(element)) {
91005                         hoistBindingElement(element);
91006                     }
91007                 }
91008             }
91009             else {
91010                 hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
91011             }
91012         }
91013         /**
91014          * Determines whether a VariableDeclarationList should be hoisted.
91015          *
91016          * @param node The node to test.
91017          */
91018         function shouldHoistVariableDeclarationList(node) {
91019             // hoist only non-block scoped declarations or block scoped declarations parented by source file
91020             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
91021                 && (enclosingBlockScopedContainer.kind === 290 /* SourceFile */
91022                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
91023         }
91024         /**
91025          * Transform an initialized variable declaration into an expression.
91026          *
91027          * @param node The node to transform.
91028          * @param isExportedDeclaration A value indicating whether the variable is exported.
91029          */
91030         function transformInitializedVariable(node, isExportedDeclaration) {
91031             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
91032             return ts.isBindingPattern(node.name)
91033                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91034                 /*needsValue*/ false, createAssignment)
91035                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
91036         }
91037         /**
91038          * Creates an assignment expression for an exported variable declaration.
91039          *
91040          * @param name The name of the variable.
91041          * @param value The value of the variable's initializer.
91042          * @param location The source map location for the assignment.
91043          */
91044         function createExportedVariableAssignment(name, value, location) {
91045             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
91046         }
91047         /**
91048          * Creates an assignment expression for a non-exported variable declaration.
91049          *
91050          * @param name The name of the variable.
91051          * @param value The value of the variable's initializer.
91052          * @param location The source map location for the assignment.
91053          */
91054         function createNonExportedVariableAssignment(name, value, location) {
91055             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
91056         }
91057         /**
91058          * Creates an assignment expression for a variable declaration.
91059          *
91060          * @param name The name of the variable.
91061          * @param value The value of the variable's initializer.
91062          * @param location The source map location for the assignment.
91063          * @param isExportedDeclaration A value indicating whether the variable is exported.
91064          */
91065         function createVariableAssignment(name, value, location, isExportedDeclaration) {
91066             hoistVariableDeclaration(ts.getSynthesizedClone(name));
91067             return isExportedDeclaration
91068                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
91069                 : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
91070         }
91071         /**
91072          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
91073          * and transformed declaration.
91074          *
91075          * @param node The node to visit.
91076          */
91077         function visitMergeDeclarationMarker(node) {
91078             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
91079             // declaration we do not emit a leading variable declaration. To preserve the
91080             // begin/end semantics of the declararation and to properly handle exports
91081             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
91082             //
91083             // To balance the declaration, we defer the exports of the elided variable
91084             // statement until we visit this declaration's `EndOfDeclarationMarker`.
91085             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
91086                 var id = ts.getOriginalNodeId(node);
91087                 var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
91088                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
91089             }
91090             return node;
91091         }
91092         /**
91093          * Determines whether a node has an associated EndOfDeclarationMarker.
91094          *
91095          * @param node The node to test.
91096          */
91097         function hasAssociatedEndOfDeclarationMarker(node) {
91098             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
91099         }
91100         /**
91101          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
91102          * declaration.
91103          *
91104          * @param node The node to visit.
91105          */
91106         function visitEndOfDeclarationMarker(node) {
91107             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
91108             // end of the transformed declaration. We use this marker to emit any deferred exports
91109             // of the declaration.
91110             var id = ts.getOriginalNodeId(node);
91111             var statements = deferredExports[id];
91112             if (statements) {
91113                 delete deferredExports[id];
91114                 return ts.append(statements, node);
91115             }
91116             else {
91117                 var original = ts.getOriginalNode(node);
91118                 if (ts.isModuleOrEnumDeclaration(original)) {
91119                     return ts.append(appendExportsOfDeclaration(statements, original), node);
91120                 }
91121             }
91122             return node;
91123         }
91124         /**
91125          * Appends the exports of an ImportDeclaration to a statement list, returning the
91126          * statement list.
91127          *
91128          * @param statements A statement list to which the down-level export statements are to be
91129          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91130          * appended.
91131          * @param decl The declaration whose exports are to be recorded.
91132          */
91133         function appendExportsOfImportDeclaration(statements, decl) {
91134             if (moduleInfo.exportEquals) {
91135                 return statements;
91136             }
91137             var importClause = decl.importClause;
91138             if (!importClause) {
91139                 return statements;
91140             }
91141             if (importClause.name) {
91142                 statements = appendExportsOfDeclaration(statements, importClause);
91143             }
91144             var namedBindings = importClause.namedBindings;
91145             if (namedBindings) {
91146                 switch (namedBindings.kind) {
91147                     case 256 /* NamespaceImport */:
91148                         statements = appendExportsOfDeclaration(statements, namedBindings);
91149                         break;
91150                     case 257 /* NamedImports */:
91151                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
91152                             var importBinding = _a[_i];
91153                             statements = appendExportsOfDeclaration(statements, importBinding);
91154                         }
91155                         break;
91156                 }
91157             }
91158             return statements;
91159         }
91160         /**
91161          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
91162          * statement list.
91163          *
91164          * @param statements A statement list to which the down-level export statements are to be
91165          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91166          * appended.
91167          * @param decl The declaration whose exports are to be recorded.
91168          */
91169         function appendExportsOfImportEqualsDeclaration(statements, decl) {
91170             if (moduleInfo.exportEquals) {
91171                 return statements;
91172             }
91173             return appendExportsOfDeclaration(statements, decl);
91174         }
91175         /**
91176          * Appends the exports of a VariableStatement to a statement list, returning the statement
91177          * list.
91178          *
91179          * @param statements A statement list to which the down-level export statements are to be
91180          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91181          * appended.
91182          * @param node The VariableStatement whose exports are to be recorded.
91183          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
91184          * `nodes` declaration list.
91185          */
91186         function appendExportsOfVariableStatement(statements, node, exportSelf) {
91187             if (moduleInfo.exportEquals) {
91188                 return statements;
91189             }
91190             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91191                 var decl = _a[_i];
91192                 if (decl.initializer || exportSelf) {
91193                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
91194                 }
91195             }
91196             return statements;
91197         }
91198         /**
91199          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
91200          * returning the statement list.
91201          *
91202          * @param statements A statement list to which the down-level export statements are to be
91203          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91204          * appended.
91205          * @param decl The declaration whose exports are to be recorded.
91206          * @param exportSelf A value indicating whether to also export the declaration itself.
91207          */
91208         function appendExportsOfBindingElement(statements, decl, exportSelf) {
91209             if (moduleInfo.exportEquals) {
91210                 return statements;
91211             }
91212             if (ts.isBindingPattern(decl.name)) {
91213                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
91214                     var element = _a[_i];
91215                     if (!ts.isOmittedExpression(element)) {
91216                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
91217                     }
91218                 }
91219             }
91220             else if (!ts.isGeneratedIdentifier(decl.name)) {
91221                 var excludeName = void 0;
91222                 if (exportSelf) {
91223                     statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
91224                     excludeName = ts.idText(decl.name);
91225                 }
91226                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91227             }
91228             return statements;
91229         }
91230         /**
91231          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
91232          * returning the statement list.
91233          *
91234          * @param statements A statement list to which the down-level export statements are to be
91235          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91236          * appended.
91237          * @param decl The declaration whose exports are to be recorded.
91238          */
91239         function appendExportsOfHoistedDeclaration(statements, decl) {
91240             if (moduleInfo.exportEquals) {
91241                 return statements;
91242             }
91243             var excludeName;
91244             if (ts.hasModifier(decl, 1 /* Export */)) {
91245                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
91246                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
91247                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
91248             }
91249             if (decl.name) {
91250                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91251             }
91252             return statements;
91253         }
91254         /**
91255          * Appends the exports of a declaration to a statement list, returning the statement list.
91256          *
91257          * @param statements A statement list to which the down-level export statements are to be
91258          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91259          * appended.
91260          * @param decl The declaration to export.
91261          * @param excludeName An optional name to exclude from exports.
91262          */
91263         function appendExportsOfDeclaration(statements, decl, excludeName) {
91264             if (moduleInfo.exportEquals) {
91265                 return statements;
91266             }
91267             var name = ts.getDeclarationName(decl);
91268             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
91269             if (exportSpecifiers) {
91270                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
91271                     var exportSpecifier = exportSpecifiers_2[_i];
91272                     if (exportSpecifier.name.escapedText !== excludeName) {
91273                         statements = appendExportStatement(statements, exportSpecifier.name, name);
91274                     }
91275                 }
91276             }
91277             return statements;
91278         }
91279         /**
91280          * Appends the down-level representation of an export to a statement list, returning the
91281          * statement list.
91282          *
91283          * @param statements A statement list to which the down-level export statements are to be
91284          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91285          * appended.
91286          * @param exportName The name of the export.
91287          * @param expression The expression to export.
91288          * @param allowComments Whether to allow comments on the export.
91289          */
91290         function appendExportStatement(statements, exportName, expression, allowComments) {
91291             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
91292             return statements;
91293         }
91294         /**
91295          * Creates a call to the current file's export function to export a value.
91296          *
91297          * @param name The bound name of the export.
91298          * @param value The exported value.
91299          * @param allowComments An optional value indicating whether to emit comments for the statement.
91300          */
91301         function createExportStatement(name, value, allowComments) {
91302             var statement = ts.createExpressionStatement(createExportExpression(name, value));
91303             ts.startOnNewLine(statement);
91304             if (!allowComments) {
91305                 ts.setEmitFlags(statement, 1536 /* NoComments */);
91306             }
91307             return statement;
91308         }
91309         /**
91310          * Creates a call to the current file's export function to export a value.
91311          *
91312          * @param name The bound name of the export.
91313          * @param value The exported value.
91314          */
91315         function createExportExpression(name, value) {
91316             var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
91317             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
91318             return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
91319         }
91320         //
91321         // Top-Level or Nested Source Element Visitors
91322         //
91323         /**
91324          * Visit nested elements at the top-level of a module.
91325          *
91326          * @param node The node to visit.
91327          */
91328         function nestedElementVisitor(node) {
91329             switch (node.kind) {
91330                 case 225 /* VariableStatement */:
91331                     return visitVariableStatement(node);
91332                 case 244 /* FunctionDeclaration */:
91333                     return visitFunctionDeclaration(node);
91334                 case 245 /* ClassDeclaration */:
91335                     return visitClassDeclaration(node);
91336                 case 230 /* ForStatement */:
91337                     return visitForStatement(node);
91338                 case 231 /* ForInStatement */:
91339                     return visitForInStatement(node);
91340                 case 232 /* ForOfStatement */:
91341                     return visitForOfStatement(node);
91342                 case 228 /* DoStatement */:
91343                     return visitDoStatement(node);
91344                 case 229 /* WhileStatement */:
91345                     return visitWhileStatement(node);
91346                 case 238 /* LabeledStatement */:
91347                     return visitLabeledStatement(node);
91348                 case 236 /* WithStatement */:
91349                     return visitWithStatement(node);
91350                 case 237 /* SwitchStatement */:
91351                     return visitSwitchStatement(node);
91352                 case 251 /* CaseBlock */:
91353                     return visitCaseBlock(node);
91354                 case 277 /* CaseClause */:
91355                     return visitCaseClause(node);
91356                 case 278 /* DefaultClause */:
91357                     return visitDefaultClause(node);
91358                 case 240 /* TryStatement */:
91359                     return visitTryStatement(node);
91360                 case 280 /* CatchClause */:
91361                     return visitCatchClause(node);
91362                 case 223 /* Block */:
91363                     return visitBlock(node);
91364                 case 328 /* MergeDeclarationMarker */:
91365                     return visitMergeDeclarationMarker(node);
91366                 case 329 /* EndOfDeclarationMarker */:
91367                     return visitEndOfDeclarationMarker(node);
91368                 default:
91369                     return destructuringAndImportCallVisitor(node);
91370             }
91371         }
91372         /**
91373          * Visits the body of a ForStatement to hoist declarations.
91374          *
91375          * @param node The node to visit.
91376          */
91377         function visitForStatement(node) {
91378             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91379             enclosingBlockScopedContainer = node;
91380             node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement));
91381             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91382             return node;
91383         }
91384         /**
91385          * Visits the body of a ForInStatement to hoist declarations.
91386          *
91387          * @param node The node to visit.
91388          */
91389         function visitForInStatement(node) {
91390             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91391             enclosingBlockScopedContainer = node;
91392             node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91393             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91394             return node;
91395         }
91396         /**
91397          * Visits the body of a ForOfStatement to hoist declarations.
91398          *
91399          * @param node The node to visit.
91400          */
91401         function visitForOfStatement(node) {
91402             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91403             enclosingBlockScopedContainer = node;
91404             node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91405             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91406             return node;
91407         }
91408         /**
91409          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
91410          * ForOfStatement.
91411          *
91412          * @param node The node to test.
91413          */
91414         function shouldHoistForInitializer(node) {
91415             return ts.isVariableDeclarationList(node)
91416                 && shouldHoistVariableDeclarationList(node);
91417         }
91418         /**
91419          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
91420          *
91421          * @param node The node to visit.
91422          */
91423         function visitForInitializer(node) {
91424             if (shouldHoistForInitializer(node)) {
91425                 var expressions = void 0;
91426                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
91427                     var variable = _a[_i];
91428                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
91429                     if (!variable.initializer) {
91430                         hoistBindingElement(variable);
91431                     }
91432                 }
91433                 return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
91434             }
91435             else {
91436                 return ts.visitEachChild(node, nestedElementVisitor, context);
91437             }
91438         }
91439         /**
91440          * Visits the body of a DoStatement to hoist declarations.
91441          *
91442          * @param node The node to visit.
91443          */
91444         function visitDoStatement(node) {
91445             return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
91446         }
91447         /**
91448          * Visits the body of a WhileStatement to hoist declarations.
91449          *
91450          * @param node The node to visit.
91451          */
91452         function visitWhileStatement(node) {
91453             return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91454         }
91455         /**
91456          * Visits the body of a LabeledStatement to hoist declarations.
91457          *
91458          * @param node The node to visit.
91459          */
91460         function visitLabeledStatement(node) {
91461             return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91462         }
91463         /**
91464          * Visits the body of a WithStatement to hoist declarations.
91465          *
91466          * @param node The node to visit.
91467          */
91468         function visitWithStatement(node) {
91469             return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91470         }
91471         /**
91472          * Visits the body of a SwitchStatement to hoist declarations.
91473          *
91474          * @param node The node to visit.
91475          */
91476         function visitSwitchStatement(node) {
91477             return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
91478         }
91479         /**
91480          * Visits the body of a CaseBlock to hoist declarations.
91481          *
91482          * @param node The node to visit.
91483          */
91484         function visitCaseBlock(node) {
91485             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91486             enclosingBlockScopedContainer = node;
91487             node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
91488             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91489             return node;
91490         }
91491         /**
91492          * Visits the body of a CaseClause to hoist declarations.
91493          *
91494          * @param node The node to visit.
91495          */
91496         function visitCaseClause(node) {
91497             return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
91498         }
91499         /**
91500          * Visits the body of a DefaultClause to hoist declarations.
91501          *
91502          * @param node The node to visit.
91503          */
91504         function visitDefaultClause(node) {
91505             return ts.visitEachChild(node, nestedElementVisitor, context);
91506         }
91507         /**
91508          * Visits the body of a TryStatement to hoist declarations.
91509          *
91510          * @param node The node to visit.
91511          */
91512         function visitTryStatement(node) {
91513             return ts.visitEachChild(node, nestedElementVisitor, context);
91514         }
91515         /**
91516          * Visits the body of a CatchClause to hoist declarations.
91517          *
91518          * @param node The node to visit.
91519          */
91520         function visitCatchClause(node) {
91521             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91522             enclosingBlockScopedContainer = node;
91523             node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
91524             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91525             return node;
91526         }
91527         /**
91528          * Visits the body of a Block to hoist declarations.
91529          *
91530          * @param node The node to visit.
91531          */
91532         function visitBlock(node) {
91533             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91534             enclosingBlockScopedContainer = node;
91535             node = ts.visitEachChild(node, nestedElementVisitor, context);
91536             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91537             return node;
91538         }
91539         //
91540         // Destructuring Assignment Visitors
91541         //
91542         /**
91543          * Visit nodes to flatten destructuring assignments to exported symbols.
91544          *
91545          * @param node The node to visit.
91546          */
91547         function destructuringAndImportCallVisitor(node) {
91548             if (ts.isDestructuringAssignment(node)) {
91549                 return visitDestructuringAssignment(node);
91550             }
91551             else if (ts.isImportCall(node)) {
91552                 return visitImportCallExpression(node);
91553             }
91554             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
91555                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91556             }
91557             else {
91558                 return node;
91559             }
91560         }
91561         function visitImportCallExpression(node) {
91562             // import("./blah")
91563             // emit as
91564             // System.register([], function (_export, _context) {
91565             //     return {
91566             //         setters: [],
91567             //         execute: () => {
91568             //             _context.import('./blah');
91569             //         }
91570             //     };
91571             // });
91572             return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), 
91573             /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
91574         }
91575         /**
91576          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
91577          *
91578          * @param node The node to visit.
91579          */
91580         function visitDestructuringAssignment(node) {
91581             if (hasExportedReferenceInDestructuringTarget(node.left)) {
91582                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91583                 /*needsValue*/ true);
91584             }
91585             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91586         }
91587         /**
91588          * Determines whether the target of a destructuring assigment refers to an exported symbol.
91589          *
91590          * @param node The destructuring target.
91591          */
91592         function hasExportedReferenceInDestructuringTarget(node) {
91593             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
91594                 return hasExportedReferenceInDestructuringTarget(node.left);
91595             }
91596             else if (ts.isSpreadElement(node)) {
91597                 return hasExportedReferenceInDestructuringTarget(node.expression);
91598             }
91599             else if (ts.isObjectLiteralExpression(node)) {
91600                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
91601             }
91602             else if (ts.isArrayLiteralExpression(node)) {
91603                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
91604             }
91605             else if (ts.isShorthandPropertyAssignment(node)) {
91606                 return hasExportedReferenceInDestructuringTarget(node.name);
91607             }
91608             else if (ts.isPropertyAssignment(node)) {
91609                 return hasExportedReferenceInDestructuringTarget(node.initializer);
91610             }
91611             else if (ts.isIdentifier(node)) {
91612                 var container = resolver.getReferencedExportContainer(node);
91613                 return container !== undefined && container.kind === 290 /* SourceFile */;
91614             }
91615             else {
91616                 return false;
91617             }
91618         }
91619         //
91620         // Modifier Visitors
91621         //
91622         /**
91623          * Visit nodes to elide module-specific modifiers.
91624          *
91625          * @param node The node to visit.
91626          */
91627         function modifierVisitor(node) {
91628             switch (node.kind) {
91629                 case 89 /* ExportKeyword */:
91630                 case 84 /* DefaultKeyword */:
91631                     return undefined;
91632             }
91633             return node;
91634         }
91635         //
91636         // Emit Notification
91637         //
91638         /**
91639          * Hook for node emit notifications.
91640          *
91641          * @param hint A hint as to the intended usage of the node.
91642          * @param node The node to emit.
91643          * @param emitCallback A callback used to emit the node in the printer.
91644          */
91645         function onEmitNode(hint, node, emitCallback) {
91646             if (node.kind === 290 /* SourceFile */) {
91647                 var id = ts.getOriginalNodeId(node);
91648                 currentSourceFile = node;
91649                 moduleInfo = moduleInfoMap[id];
91650                 exportFunction = exportFunctionsMap[id];
91651                 noSubstitution = noSubstitutionMap[id];
91652                 contextObject = contextObjectMap[id];
91653                 if (noSubstitution) {
91654                     delete noSubstitutionMap[id];
91655                 }
91656                 previousOnEmitNode(hint, node, emitCallback);
91657                 currentSourceFile = undefined;
91658                 moduleInfo = undefined;
91659                 exportFunction = undefined;
91660                 contextObject = undefined;
91661                 noSubstitution = undefined;
91662             }
91663             else {
91664                 previousOnEmitNode(hint, node, emitCallback);
91665             }
91666         }
91667         //
91668         // Substitutions
91669         //
91670         /**
91671          * Hooks node substitutions.
91672          *
91673          * @param hint A hint as to the intended usage of the node.
91674          * @param node The node to substitute.
91675          */
91676         function onSubstituteNode(hint, node) {
91677             node = previousOnSubstituteNode(hint, node);
91678             if (isSubstitutionPrevented(node)) {
91679                 return node;
91680             }
91681             if (hint === 1 /* Expression */) {
91682                 return substituteExpression(node);
91683             }
91684             else if (hint === 4 /* Unspecified */) {
91685                 return substituteUnspecified(node);
91686             }
91687             return node;
91688         }
91689         /**
91690          * Substitute the node, if necessary.
91691          *
91692          * @param node The node to substitute.
91693          */
91694         function substituteUnspecified(node) {
91695             switch (node.kind) {
91696                 case 282 /* ShorthandPropertyAssignment */:
91697                     return substituteShorthandPropertyAssignment(node);
91698             }
91699             return node;
91700         }
91701         /**
91702          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
91703          *
91704          * @param node The node to substitute.
91705          */
91706         function substituteShorthandPropertyAssignment(node) {
91707             var name = node.name;
91708             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
91709                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
91710                 if (importDeclaration) {
91711                     if (ts.isImportClause(importDeclaration)) {
91712                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), 
91713                         /*location*/ node);
91714                     }
91715                     else if (ts.isImportSpecifier(importDeclaration)) {
91716                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), 
91717                         /*location*/ node);
91718                     }
91719                 }
91720             }
91721             return node;
91722         }
91723         /**
91724          * Substitute the expression, if necessary.
91725          *
91726          * @param node The node to substitute.
91727          */
91728         function substituteExpression(node) {
91729             switch (node.kind) {
91730                 case 75 /* Identifier */:
91731                     return substituteExpressionIdentifier(node);
91732                 case 209 /* BinaryExpression */:
91733                     return substituteBinaryExpression(node);
91734                 case 207 /* PrefixUnaryExpression */:
91735                 case 208 /* PostfixUnaryExpression */:
91736                     return substituteUnaryExpression(node);
91737                 case 219 /* MetaProperty */:
91738                     return substituteMetaProperty(node);
91739             }
91740             return node;
91741         }
91742         /**
91743          * Substitution for an Identifier expression that may contain an imported or exported symbol.
91744          *
91745          * @param node The node to substitute.
91746          */
91747         function substituteExpressionIdentifier(node) {
91748             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
91749                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
91750                 if (externalHelpersModuleName) {
91751                     return ts.createPropertyAccess(externalHelpersModuleName, node);
91752                 }
91753                 return node;
91754             }
91755             // When we see an identifier in an expression position that
91756             // points to an imported symbol, we should substitute a qualified
91757             // reference to the imported symbol if one is needed.
91758             //
91759             // - We do not substitute generated identifiers for any reason.
91760             // - We do not substitute identifiers tagged with the LocalName flag.
91761             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
91762                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
91763                 if (importDeclaration) {
91764                     if (ts.isImportClause(importDeclaration)) {
91765                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
91766                         /*location*/ node);
91767                     }
91768                     else if (ts.isImportSpecifier(importDeclaration)) {
91769                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), 
91770                         /*location*/ node);
91771                     }
91772                 }
91773             }
91774             return node;
91775         }
91776         /**
91777          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
91778          *
91779          * @param node The node to substitute.
91780          */
91781         function substituteBinaryExpression(node) {
91782             // When we see an assignment expression whose left-hand side is an exported symbol,
91783             // we should ensure all exports of that symbol are updated with the correct value.
91784             //
91785             // - We do not substitute generated identifiers for any reason.
91786             // - We do not substitute identifiers tagged with the LocalName flag.
91787             // - We do not substitute identifiers that were originally the name of an enum or
91788             //   namespace due to how they are transformed in TypeScript.
91789             // - We only substitute identifiers that are exported at the top level.
91790             if (ts.isAssignmentOperator(node.operatorToken.kind)
91791                 && ts.isIdentifier(node.left)
91792                 && !ts.isGeneratedIdentifier(node.left)
91793                 && !ts.isLocalName(node.left)
91794                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
91795                 var exportedNames = getExports(node.left);
91796                 if (exportedNames) {
91797                     // For each additional export of the declaration, apply an export assignment.
91798                     var expression = node;
91799                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
91800                         var exportName = exportedNames_4[_i];
91801                         expression = createExportExpression(exportName, preventSubstitution(expression));
91802                     }
91803                     return expression;
91804                 }
91805             }
91806             return node;
91807         }
91808         /**
91809          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
91810          *
91811          * @param node The node to substitute.
91812          */
91813         function substituteUnaryExpression(node) {
91814             // When we see a prefix or postfix increment expression whose operand is an exported
91815             // symbol, we should ensure all exports of that symbol are updated with the correct
91816             // value.
91817             //
91818             // - We do not substitute generated identifiers for any reason.
91819             // - We do not substitute identifiers tagged with the LocalName flag.
91820             // - We do not substitute identifiers that were originally the name of an enum or
91821             //   namespace due to how they are transformed in TypeScript.
91822             // - We only substitute identifiers that are exported at the top level.
91823             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
91824                 && ts.isIdentifier(node.operand)
91825                 && !ts.isGeneratedIdentifier(node.operand)
91826                 && !ts.isLocalName(node.operand)
91827                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
91828                 var exportedNames = getExports(node.operand);
91829                 if (exportedNames) {
91830                     var expression = node.kind === 208 /* PostfixUnaryExpression */
91831                         ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
91832                         : node;
91833                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
91834                         var exportName = exportedNames_5[_i];
91835                         expression = createExportExpression(exportName, preventSubstitution(expression));
91836                     }
91837                     if (node.kind === 208 /* PostfixUnaryExpression */) {
91838                         expression = node.operator === 45 /* PlusPlusToken */
91839                             ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
91840                             : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
91841                     }
91842                     return expression;
91843                 }
91844             }
91845             return node;
91846         }
91847         function substituteMetaProperty(node) {
91848             if (ts.isImportMeta(node)) {
91849                 return ts.createPropertyAccess(contextObject, ts.createIdentifier("meta"));
91850             }
91851             return node;
91852         }
91853         /**
91854          * Gets the exports of a name.
91855          *
91856          * @param name The name.
91857          */
91858         function getExports(name) {
91859             var exportedNames;
91860             if (!ts.isGeneratedIdentifier(name)) {
91861                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
91862                     || resolver.getReferencedValueDeclaration(name);
91863                 if (valueDeclaration) {
91864                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
91865                     if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
91866                         exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
91867                     }
91868                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
91869                 }
91870             }
91871             return exportedNames;
91872         }
91873         /**
91874          * Prevent substitution of a node for this transformer.
91875          *
91876          * @param node The node which should not be substituted.
91877          */
91878         function preventSubstitution(node) {
91879             if (noSubstitution === undefined)
91880                 noSubstitution = [];
91881             noSubstitution[ts.getNodeId(node)] = true;
91882             return node;
91883         }
91884         /**
91885          * Determines whether a node should not be substituted.
91886          *
91887          * @param node The node to test.
91888          */
91889         function isSubstitutionPrevented(node) {
91890             return noSubstitution && node.id && noSubstitution[node.id];
91891         }
91892     }
91893     ts.transformSystemModule = transformSystemModule;
91894 })(ts || (ts = {}));
91895 /*@internal*/
91896 var ts;
91897 (function (ts) {
91898     function transformECMAScriptModule(context) {
91899         var compilerOptions = context.getCompilerOptions();
91900         var previousOnEmitNode = context.onEmitNode;
91901         var previousOnSubstituteNode = context.onSubstituteNode;
91902         context.onEmitNode = onEmitNode;
91903         context.onSubstituteNode = onSubstituteNode;
91904         context.enableEmitNotification(290 /* SourceFile */);
91905         context.enableSubstitution(75 /* Identifier */);
91906         var helperNameSubstitutions;
91907         return ts.chainBundle(transformSourceFile);
91908         function transformSourceFile(node) {
91909             if (node.isDeclarationFile) {
91910                 return node;
91911             }
91912             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
91913                 var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(node, compilerOptions);
91914                 if (externalHelpersImportDeclaration) {
91915                     var statements = [];
91916                     var statementOffset = ts.addPrologue(statements, node.statements);
91917                     ts.append(statements, externalHelpersImportDeclaration);
91918                     ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
91919                     return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
91920                 }
91921                 else {
91922                     return ts.visitEachChild(node, visitor, context);
91923                 }
91924             }
91925             return node;
91926         }
91927         function visitor(node) {
91928             switch (node.kind) {
91929                 case 253 /* ImportEqualsDeclaration */:
91930                     // Elide `import=` as it is not legal with --module ES6
91931                     return undefined;
91932                 case 259 /* ExportAssignment */:
91933                     return visitExportAssignment(node);
91934                 case 260 /* ExportDeclaration */:
91935                     var exportDecl = node;
91936                     return visitExportDeclaration(exportDecl);
91937             }
91938             return node;
91939         }
91940         function visitExportAssignment(node) {
91941             // Elide `export=` as it is not legal with --module ES6
91942             return node.isExportEquals ? undefined : node;
91943         }
91944         function visitExportDeclaration(node) {
91945             // `export * as ns` only needs to be transformed in ES2015
91946             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
91947                 return node;
91948             }
91949             // Either ill-formed or don't need to be tranformed.
91950             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
91951                 return node;
91952             }
91953             var oldIdentifier = node.exportClause.name;
91954             var synthName = ts.getGeneratedNameForNode(oldIdentifier);
91955             var importDecl = ts.createImportDeclaration(
91956             /*decorators*/ undefined, 
91957             /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(synthName)), node.moduleSpecifier);
91958             ts.setOriginalNode(importDecl, node.exportClause);
91959             var exportDecl = ts.createExportDeclaration(
91960             /*decorators*/ undefined, 
91961             /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(synthName, oldIdentifier)]));
91962             ts.setOriginalNode(exportDecl, node);
91963             return [importDecl, exportDecl];
91964         }
91965         //
91966         // Emit Notification
91967         //
91968         /**
91969          * Hook for node emit.
91970          *
91971          * @param hint A hint as to the intended usage of the node.
91972          * @param node The node to emit.
91973          * @param emit A callback used to emit the node in the printer.
91974          */
91975         function onEmitNode(hint, node, emitCallback) {
91976             if (ts.isSourceFile(node)) {
91977                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
91978                     helperNameSubstitutions = ts.createMap();
91979                 }
91980                 previousOnEmitNode(hint, node, emitCallback);
91981                 helperNameSubstitutions = undefined;
91982             }
91983             else {
91984                 previousOnEmitNode(hint, node, emitCallback);
91985             }
91986         }
91987         //
91988         // Substitutions
91989         //
91990         /**
91991          * Hooks node substitutions.
91992          *
91993          * @param hint A hint as to the intended usage of the node.
91994          * @param node The node to substitute.
91995          */
91996         function onSubstituteNode(hint, node) {
91997             node = previousOnSubstituteNode(hint, node);
91998             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
91999                 return substituteHelperName(node);
92000             }
92001             return node;
92002         }
92003         function substituteHelperName(node) {
92004             var name = ts.idText(node);
92005             var substitution = helperNameSubstitutions.get(name);
92006             if (!substitution) {
92007                 helperNameSubstitutions.set(name, substitution = ts.createFileLevelUniqueName(name));
92008             }
92009             return substitution;
92010         }
92011     }
92012     ts.transformECMAScriptModule = transformECMAScriptModule;
92013 })(ts || (ts = {}));
92014 /* @internal */
92015 var ts;
92016 (function (ts) {
92017     function canProduceDiagnostics(node) {
92018         return ts.isVariableDeclaration(node) ||
92019             ts.isPropertyDeclaration(node) ||
92020             ts.isPropertySignature(node) ||
92021             ts.isBindingElement(node) ||
92022             ts.isSetAccessor(node) ||
92023             ts.isGetAccessor(node) ||
92024             ts.isConstructSignatureDeclaration(node) ||
92025             ts.isCallSignatureDeclaration(node) ||
92026             ts.isMethodDeclaration(node) ||
92027             ts.isMethodSignature(node) ||
92028             ts.isFunctionDeclaration(node) ||
92029             ts.isParameter(node) ||
92030             ts.isTypeParameterDeclaration(node) ||
92031             ts.isExpressionWithTypeArguments(node) ||
92032             ts.isImportEqualsDeclaration(node) ||
92033             ts.isTypeAliasDeclaration(node) ||
92034             ts.isConstructorDeclaration(node) ||
92035             ts.isIndexSignatureDeclaration(node) ||
92036             ts.isPropertyAccessExpression(node);
92037     }
92038     ts.canProduceDiagnostics = canProduceDiagnostics;
92039     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
92040         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92041             return getAccessorNameVisibilityError;
92042         }
92043         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
92044             return getMethodNameVisibilityError;
92045         }
92046         else {
92047             return createGetSymbolAccessibilityDiagnosticForNode(node);
92048         }
92049         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
92050             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92051             return diagnosticMessage !== undefined ? {
92052                 diagnosticMessage: diagnosticMessage,
92053                 errorNode: node,
92054                 typeName: node.name
92055             } : undefined;
92056         }
92057         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92058             if (ts.hasModifier(node, 32 /* Static */)) {
92059                 return symbolAccessibilityResult.errorModuleName ?
92060                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92061                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92062                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92063                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92064             }
92065             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92066                 return symbolAccessibilityResult.errorModuleName ?
92067                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92068                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92069                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92070                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92071             }
92072             else {
92073                 return symbolAccessibilityResult.errorModuleName ?
92074                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92075                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92076             }
92077         }
92078         function getMethodNameVisibilityError(symbolAccessibilityResult) {
92079             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92080             return diagnosticMessage !== undefined ? {
92081                 diagnosticMessage: diagnosticMessage,
92082                 errorNode: node,
92083                 typeName: node.name
92084             } : undefined;
92085         }
92086         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92087             if (ts.hasModifier(node, 32 /* Static */)) {
92088                 return symbolAccessibilityResult.errorModuleName ?
92089                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92090                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92091                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92092                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
92093             }
92094             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92095                 return symbolAccessibilityResult.errorModuleName ?
92096                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92097                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92098                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92099                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
92100             }
92101             else {
92102                 return symbolAccessibilityResult.errorModuleName ?
92103                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92104                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
92105             }
92106         }
92107     }
92108     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
92109     function createGetSymbolAccessibilityDiagnosticForNode(node) {
92110         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
92111             return getVariableDeclarationTypeVisibilityError;
92112         }
92113         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92114             return getAccessorDeclarationTypeVisibilityError;
92115         }
92116         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
92117             return getReturnTypeVisibilityError;
92118         }
92119         else if (ts.isParameter(node)) {
92120             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasModifier(node.parent, 8 /* Private */)) {
92121                 return getVariableDeclarationTypeVisibilityError;
92122             }
92123             return getParameterDeclarationTypeVisibilityError;
92124         }
92125         else if (ts.isTypeParameterDeclaration(node)) {
92126             return getTypeParameterConstraintVisibilityError;
92127         }
92128         else if (ts.isExpressionWithTypeArguments(node)) {
92129             return getHeritageClauseVisibilityError;
92130         }
92131         else if (ts.isImportEqualsDeclaration(node)) {
92132             return getImportEntityNameVisibilityError;
92133         }
92134         else if (ts.isTypeAliasDeclaration(node)) {
92135             return getTypeAliasDeclarationVisibilityError;
92136         }
92137         else {
92138             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
92139         }
92140         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92141             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92142                 return symbolAccessibilityResult.errorModuleName ?
92143                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92144                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92145                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
92146                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
92147             }
92148             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
92149             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
92150             else if (node.kind === 159 /* PropertyDeclaration */ || node.kind === 194 /* PropertyAccessExpression */ || node.kind === 158 /* PropertySignature */ ||
92151                 (node.kind === 156 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
92152                 // TODO(jfreeman): Deal with computed properties in error reporting.
92153                 if (ts.hasModifier(node, 32 /* Static */)) {
92154                     return symbolAccessibilityResult.errorModuleName ?
92155                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92156                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92157                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92158                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92159                 }
92160                 else if (node.parent.kind === 245 /* ClassDeclaration */ || node.kind === 156 /* Parameter */) {
92161                     return symbolAccessibilityResult.errorModuleName ?
92162                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92163                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92164                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92165                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92166                 }
92167                 else {
92168                     // Interfaces cannot have types that cannot be named
92169                     return symbolAccessibilityResult.errorModuleName ?
92170                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92171                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92172                 }
92173             }
92174         }
92175         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92176             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92177             return diagnosticMessage !== undefined ? {
92178                 diagnosticMessage: diagnosticMessage,
92179                 errorNode: node,
92180                 typeName: node.name
92181             } : undefined;
92182         }
92183         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92184             var diagnosticMessage;
92185             if (node.kind === 164 /* SetAccessor */) {
92186                 // Getters can infer the return type from the returned expression, but setters cannot, so the
92187                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
92188                 if (ts.hasModifier(node, 32 /* Static */)) {
92189                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92190                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92191                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
92192                 }
92193                 else {
92194                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92195                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92196                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
92197                 }
92198             }
92199             else {
92200                 if (ts.hasModifier(node, 32 /* Static */)) {
92201                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92202                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92203                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92204                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92205                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
92206                 }
92207                 else {
92208                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92209                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92210                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92211                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92212                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
92213                 }
92214             }
92215             return {
92216                 diagnosticMessage: diagnosticMessage,
92217                 errorNode: node.name,
92218                 typeName: node.name
92219             };
92220         }
92221         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
92222             var diagnosticMessage;
92223             switch (node.kind) {
92224                 case 166 /* ConstructSignature */:
92225                     // Interfaces cannot have return types that cannot be named
92226                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92227                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92228                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
92229                     break;
92230                 case 165 /* CallSignature */:
92231                     // Interfaces cannot have return types that cannot be named
92232                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92233                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92234                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
92235                     break;
92236                 case 167 /* IndexSignature */:
92237                     // Interfaces cannot have return types that cannot be named
92238                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92239                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92240                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
92241                     break;
92242                 case 161 /* MethodDeclaration */:
92243                 case 160 /* MethodSignature */:
92244                     if (ts.hasModifier(node, 32 /* Static */)) {
92245                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92246                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92247                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92248                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92249                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
92250                     }
92251                     else if (node.parent.kind === 245 /* ClassDeclaration */) {
92252                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92253                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92254                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92255                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92256                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
92257                     }
92258                     else {
92259                         // Interfaces cannot have return types that cannot be named
92260                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92261                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92262                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
92263                     }
92264                     break;
92265                 case 244 /* FunctionDeclaration */:
92266                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92267                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92268                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92269                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
92270                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
92271                     break;
92272                 default:
92273                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
92274             }
92275             return {
92276                 diagnosticMessage: diagnosticMessage,
92277                 errorNode: node.name || node
92278             };
92279         }
92280         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92281             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92282             return diagnosticMessage !== undefined ? {
92283                 diagnosticMessage: diagnosticMessage,
92284                 errorNode: node,
92285                 typeName: node.name
92286             } : undefined;
92287         }
92288         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92289             switch (node.parent.kind) {
92290                 case 162 /* Constructor */:
92291                     return symbolAccessibilityResult.errorModuleName ?
92292                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92293                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92294                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92295                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
92296                 case 166 /* ConstructSignature */:
92297                 case 171 /* ConstructorType */:
92298                     // Interfaces cannot have parameter types that cannot be named
92299                     return symbolAccessibilityResult.errorModuleName ?
92300                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92301                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92302                 case 165 /* CallSignature */:
92303                     // Interfaces cannot have parameter types that cannot be named
92304                     return symbolAccessibilityResult.errorModuleName ?
92305                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92306                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92307                 case 167 /* IndexSignature */:
92308                     // Interfaces cannot have parameter types that cannot be named
92309                     return symbolAccessibilityResult.errorModuleName ?
92310                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92311                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
92312                 case 161 /* MethodDeclaration */:
92313                 case 160 /* MethodSignature */:
92314                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92315                         return symbolAccessibilityResult.errorModuleName ?
92316                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92317                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92318                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92319                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92320                     }
92321                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92322                         return symbolAccessibilityResult.errorModuleName ?
92323                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92324                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92325                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92326                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92327                     }
92328                     else {
92329                         // Interfaces cannot have parameter types that cannot be named
92330                         return symbolAccessibilityResult.errorModuleName ?
92331                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92332                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92333                     }
92334                 case 244 /* FunctionDeclaration */:
92335                 case 170 /* FunctionType */:
92336                     return symbolAccessibilityResult.errorModuleName ?
92337                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92338                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92339                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
92340                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
92341                 case 164 /* SetAccessor */:
92342                 case 163 /* GetAccessor */:
92343                     return symbolAccessibilityResult.errorModuleName ?
92344                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92345                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92346                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
92347                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
92348                 default:
92349                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
92350             }
92351         }
92352         function getTypeParameterConstraintVisibilityError() {
92353             // Type parameter constraints are named by user so we should always be able to name it
92354             var diagnosticMessage;
92355             switch (node.parent.kind) {
92356                 case 245 /* ClassDeclaration */:
92357                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
92358                     break;
92359                 case 246 /* InterfaceDeclaration */:
92360                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
92361                     break;
92362                 case 186 /* MappedType */:
92363                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
92364                     break;
92365                 case 171 /* ConstructorType */:
92366                 case 166 /* ConstructSignature */:
92367                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92368                     break;
92369                 case 165 /* CallSignature */:
92370                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92371                     break;
92372                 case 161 /* MethodDeclaration */:
92373                 case 160 /* MethodSignature */:
92374                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92375                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92376                     }
92377                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92378                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92379                     }
92380                     else {
92381                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92382                     }
92383                     break;
92384                 case 170 /* FunctionType */:
92385                 case 244 /* FunctionDeclaration */:
92386                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
92387                     break;
92388                 case 247 /* TypeAliasDeclaration */:
92389                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
92390                     break;
92391                 default:
92392                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
92393             }
92394             return {
92395                 diagnosticMessage: diagnosticMessage,
92396                 errorNode: node,
92397                 typeName: node.name
92398             };
92399         }
92400         function getHeritageClauseVisibilityError() {
92401             var diagnosticMessage;
92402             // Heritage clause is written by user so it can always be named
92403             if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92404                 // Class or Interface implemented/extended is inaccessible
92405                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 113 /* ImplementsKeyword */ ?
92406                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
92407                     ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
92408             }
92409             else {
92410                 // interface is inaccessible
92411                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
92412             }
92413             return {
92414                 diagnosticMessage: diagnosticMessage,
92415                 errorNode: node,
92416                 typeName: ts.getNameOfDeclaration(node.parent.parent)
92417             };
92418         }
92419         function getImportEntityNameVisibilityError() {
92420             return {
92421                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
92422                 errorNode: node,
92423                 typeName: node.name
92424             };
92425         }
92426         function getTypeAliasDeclarationVisibilityError() {
92427             return {
92428                 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
92429                 errorNode: node.type,
92430                 typeName: node.name
92431             };
92432         }
92433     }
92434     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
92435 })(ts || (ts = {}));
92436 /*@internal*/
92437 var ts;
92438 (function (ts) {
92439     function getDeclarationDiagnostics(host, resolver, file) {
92440         if (file && ts.isJsonSourceFile(file)) {
92441             return []; // No declaration diagnostics for json for now
92442         }
92443         var compilerOptions = host.getCompilerOptions();
92444         var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
92445         return result.diagnostics;
92446     }
92447     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
92448     function hasInternalAnnotation(range, currentSourceFile) {
92449         var comment = currentSourceFile.text.substring(range.pos, range.end);
92450         return ts.stringContains(comment, "@internal");
92451     }
92452     function isInternalDeclaration(node, currentSourceFile) {
92453         var parseTreeNode = ts.getParseTreeNode(node);
92454         if (parseTreeNode && parseTreeNode.kind === 156 /* Parameter */) {
92455             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
92456             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
92457             var text = currentSourceFile.text;
92458             var commentRanges = previousSibling
92459                 ? ts.concatenate(
92460                 // to handle
92461                 // ... parameters, /* @internal */
92462                 // public param: string
92463                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
92464                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
92465             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
92466         }
92467         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
92468         return !!ts.forEach(leadingCommentRanges, function (range) {
92469             return hasInternalAnnotation(range, currentSourceFile);
92470         });
92471     }
92472     ts.isInternalDeclaration = isInternalDeclaration;
92473     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
92474         2048 /* WriteClassExpressionAsTypeLiteral */ |
92475         4096 /* UseTypeOfFunction */ |
92476         8 /* UseStructuralFallback */ |
92477         524288 /* AllowEmptyTuple */ |
92478         4 /* GenerateNamesForShadowedTypeParams */ |
92479         1 /* NoTruncation */;
92480     /**
92481      * Transforms a ts file into a .d.ts file
92482      * This process requires type information, which is retrieved through the emit resolver. Because of this,
92483      * in many places this transformer assumes it will be operating on parse tree nodes directly.
92484      * This means that _no transforms should be allowed to occur before this one_.
92485      */
92486     function transformDeclarations(context) {
92487         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
92488         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
92489         var needsDeclare = true;
92490         var isBundledEmit = false;
92491         var resultHasExternalModuleIndicator = false;
92492         var needsScopeFixMarker = false;
92493         var resultHasScopeMarker = false;
92494         var enclosingDeclaration;
92495         var necessaryTypeReferences;
92496         var lateMarkedStatements;
92497         var lateStatementReplacementMap;
92498         var suppressNewDiagnosticContexts;
92499         var exportedModulesFromDeclarationEmit;
92500         var host = context.getEmitHost();
92501         var symbolTracker = {
92502             trackSymbol: trackSymbol,
92503             reportInaccessibleThisError: reportInaccessibleThisError,
92504             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
92505             reportCyclicStructureError: reportCyclicStructureError,
92506             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
92507             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
92508             moduleResolverHost: host,
92509             trackReferencedAmbientModule: trackReferencedAmbientModule,
92510             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
92511             reportNonlocalAugmentation: reportNonlocalAugmentation
92512         };
92513         var errorNameNode;
92514         var currentSourceFile;
92515         var refs;
92516         var libs;
92517         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
92518         var resolver = context.getEmitResolver();
92519         var options = context.getCompilerOptions();
92520         var noResolve = options.noResolve, stripInternal = options.stripInternal;
92521         return transformRoot;
92522         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
92523             if (!typeReferenceDirectives) {
92524                 return;
92525             }
92526             necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
92527             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
92528                 var ref = typeReferenceDirectives_2[_i];
92529                 necessaryTypeReferences.set(ref, true);
92530             }
92531         }
92532         function trackReferencedAmbientModule(node, symbol) {
92533             // If it is visible via `// <reference types="..."/>`, then we should just use that
92534             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
92535             if (ts.length(directives)) {
92536                 return recordTypeReferenceDirectivesIfNecessary(directives);
92537             }
92538             // Otherwise we should emit a path-based reference
92539             var container = ts.getSourceFileOfNode(node);
92540             refs.set("" + ts.getOriginalNodeId(container), container);
92541         }
92542         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
92543             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
92544                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
92545                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
92546                     if (!lateMarkedStatements) {
92547                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
92548                     }
92549                     else {
92550                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
92551                             var ref = _a[_i];
92552                             ts.pushIfUnique(lateMarkedStatements, ref);
92553                         }
92554                     }
92555                 }
92556                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
92557             }
92558             else {
92559                 // Report error
92560                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
92561                 if (errorInfo) {
92562                     if (errorInfo.typeName) {
92563                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92564                     }
92565                     else {
92566                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92567                     }
92568                 }
92569             }
92570         }
92571         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
92572             if (!isBundledEmit) {
92573                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92574             }
92575         }
92576         function trackSymbol(symbol, enclosingDeclaration, meaning) {
92577             if (symbol.flags & 262144 /* TypeParameter */)
92578                 return;
92579             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
92580             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
92581         }
92582         function reportPrivateInBaseOfClassExpression(propertyName) {
92583             if (errorNameNode) {
92584                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
92585             }
92586         }
92587         function reportInaccessibleUniqueSymbolError() {
92588             if (errorNameNode) {
92589                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol"));
92590             }
92591         }
92592         function reportCyclicStructureError() {
92593             if (errorNameNode) {
92594                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode)));
92595             }
92596         }
92597         function reportInaccessibleThisError() {
92598             if (errorNameNode) {
92599                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
92600             }
92601         }
92602         function reportLikelyUnsafeImportRequiredError(specifier) {
92603             if (errorNameNode) {
92604                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
92605             }
92606         }
92607         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
92608             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
92609             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
92610             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
92611                 var augmentations = augmentingDeclarations_1[_i];
92612                 context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file)));
92613             }
92614         }
92615         function transformDeclarationsForJS(sourceFile, bundled) {
92616             var oldDiag = getSymbolAccessibilityDiagnostic;
92617             getSymbolAccessibilityDiagnostic = function (s) { return ({
92618                 diagnosticMessage: s.errorModuleName
92619                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
92620                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
92621                 errorNode: s.errorNode || sourceFile
92622             }); };
92623             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
92624             getSymbolAccessibilityDiagnostic = oldDiag;
92625             return result;
92626         }
92627         function transformRoot(node) {
92628             if (node.kind === 290 /* SourceFile */ && node.isDeclarationFile) {
92629                 return node;
92630             }
92631             if (node.kind === 291 /* Bundle */) {
92632                 isBundledEmit = true;
92633                 refs = ts.createMap();
92634                 libs = ts.createMap();
92635                 var hasNoDefaultLib_1 = false;
92636                 var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
92637                     if (sourceFile.isDeclarationFile)
92638                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
92639                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
92640                     currentSourceFile = sourceFile;
92641                     enclosingDeclaration = sourceFile;
92642                     lateMarkedStatements = undefined;
92643                     suppressNewDiagnosticContexts = false;
92644                     lateStatementReplacementMap = ts.createMap();
92645                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
92646                     needsScopeFixMarker = false;
92647                     resultHasScopeMarker = false;
92648                     collectReferences(sourceFile, refs);
92649                     collectLibs(sourceFile, libs);
92650                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
92651                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
92652                         needsDeclare = false;
92653                         var statements = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92654                         var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(130 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
92655                         return newFile;
92656                     }
92657                     needsDeclare = true;
92658                     var updated = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92659                     return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
92660                 }), ts.mapDefined(node.prepends, function (prepend) {
92661                     if (prepend.kind === 293 /* InputFiles */) {
92662                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
92663                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
92664                         collectReferences(sourceFile, refs);
92665                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
92666                         collectLibs(sourceFile, libs);
92667                         return sourceFile;
92668                     }
92669                     return prepend;
92670                 }));
92671                 bundle.syntheticFileReferences = [];
92672                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
92673                 bundle.syntheticLibReferences = getLibReferences();
92674                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
92675                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92676                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
92677                 refs.forEach(referenceVisitor_1);
92678                 return bundle;
92679             }
92680             // Single source file
92681             needsDeclare = true;
92682             needsScopeFixMarker = false;
92683             resultHasScopeMarker = false;
92684             enclosingDeclaration = node;
92685             currentSourceFile = node;
92686             getSymbolAccessibilityDiagnostic = throwDiagnostic;
92687             isBundledEmit = false;
92688             resultHasExternalModuleIndicator = false;
92689             suppressNewDiagnosticContexts = false;
92690             lateMarkedStatements = undefined;
92691             lateStatementReplacementMap = ts.createMap();
92692             necessaryTypeReferences = undefined;
92693             refs = collectReferences(currentSourceFile, ts.createMap());
92694             libs = collectLibs(currentSourceFile, ts.createMap());
92695             var references = [];
92696             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92697             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
92698             var combinedStatements;
92699             if (ts.isSourceFileJS(currentSourceFile)) {
92700                 combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node));
92701                 refs.forEach(referenceVisitor);
92702                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92703             }
92704             else {
92705                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
92706                 combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
92707                 refs.forEach(referenceVisitor);
92708                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92709                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
92710                     combinedStatements = ts.setTextRange(ts.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports()])), combinedStatements);
92711                 }
92712             }
92713             var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
92714             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
92715             return updated;
92716             function getLibReferences() {
92717                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
92718             }
92719             function getFileReferencesForUsedTypeReferences() {
92720                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
92721             }
92722             function getFileReferenceForTypeName(typeName) {
92723                 // Elide type references for which we have imports
92724                 if (emittedImports) {
92725                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
92726                         var importStatement = emittedImports_1[_i];
92727                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
92728                             var expr = importStatement.moduleReference.expression;
92729                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
92730                                 return undefined;
92731                             }
92732                         }
92733                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
92734                             return undefined;
92735                         }
92736                     }
92737                 }
92738                 return { fileName: typeName, pos: -1, end: -1 };
92739             }
92740             function mapReferencesIntoArray(references, outputFilePath) {
92741                 return function (file) {
92742                     var declFileName;
92743                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
92744                         declFileName = file.fileName;
92745                     }
92746                     else {
92747                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
92748                             return; // Omit references to files which are being merged
92749                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
92750                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
92751                     }
92752                     if (declFileName) {
92753                         var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, 
92754                         /*preferences*/ undefined);
92755                         if (!ts.pathIsRelative(specifier)) {
92756                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
92757                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
92758                             // a relative path to the declaration file
92759                             recordTypeReferenceDirectivesIfNecessary([specifier]);
92760                             return;
92761                         }
92762                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
92763                         /*isAbsolutePathAnUrl*/ false);
92764                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
92765                             fileName = fileName.substring(2);
92766                         }
92767                         // omit references to files from node_modules (npm may disambiguate module
92768                         // references when installing this package, making the path is unreliable).
92769                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
92770                             return;
92771                         }
92772                         references.push({ pos: -1, end: -1, fileName: fileName });
92773                     }
92774                 };
92775             }
92776         }
92777         function collectReferences(sourceFile, ret) {
92778             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
92779                 return ret;
92780             ts.forEach(sourceFile.referencedFiles, function (f) {
92781                 var elem = host.getSourceFileFromReference(sourceFile, f);
92782                 if (elem) {
92783                     ret.set("" + ts.getOriginalNodeId(elem), elem);
92784                 }
92785             });
92786             return ret;
92787         }
92788         function collectLibs(sourceFile, ret) {
92789             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
92790                 var lib = host.getLibFileFromReference(ref);
92791                 if (lib) {
92792                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
92793                 }
92794             });
92795             return ret;
92796         }
92797         function filterBindingPatternInitializers(name) {
92798             if (name.kind === 75 /* Identifier */) {
92799                 return name;
92800             }
92801             else {
92802                 if (name.kind === 190 /* ArrayBindingPattern */) {
92803                     return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92804                 }
92805                 else {
92806                     return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92807                 }
92808             }
92809             function visitBindingElement(elem) {
92810                 if (elem.kind === 215 /* OmittedExpression */) {
92811                     return elem;
92812                 }
92813                 return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
92814             }
92815         }
92816         function ensureParameter(p, modifierMask, type) {
92817             var oldDiag;
92818             if (!suppressNewDiagnosticContexts) {
92819                 oldDiag = getSymbolAccessibilityDiagnostic;
92820                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
92821             }
92822             var newParam = ts.updateParameter(p, 
92823             /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(57 /* QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param
92824             ensureNoInitializer(p));
92825             if (!suppressNewDiagnosticContexts) {
92826                 getSymbolAccessibilityDiagnostic = oldDiag;
92827             }
92828             return newParam;
92829         }
92830         function shouldPrintWithInitializer(node) {
92831             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
92832         }
92833         function ensureNoInitializer(node) {
92834             if (shouldPrintWithInitializer(node)) {
92835                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
92836             }
92837             return undefined;
92838         }
92839         function ensureType(node, type, ignorePrivate) {
92840             if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
92841                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
92842                 return;
92843             }
92844             if (shouldPrintWithInitializer(node)) {
92845                 // Literal const declarations will have an initializer ensured rather than a type
92846                 return;
92847             }
92848             var shouldUseResolverType = node.kind === 156 /* Parameter */ &&
92849                 (resolver.isRequiredInitializedParameter(node) ||
92850                     resolver.isOptionalUninitializedParameterProperty(node));
92851             if (type && !shouldUseResolverType) {
92852                 return ts.visitNode(type, visitDeclarationSubtree);
92853             }
92854             if (!ts.getParseTreeNode(node)) {
92855                 return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
92856             }
92857             if (node.kind === 164 /* SetAccessor */) {
92858                 // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now
92859                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
92860                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
92861             }
92862             errorNameNode = node.name;
92863             var oldDiag;
92864             if (!suppressNewDiagnosticContexts) {
92865                 oldDiag = getSymbolAccessibilityDiagnostic;
92866                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
92867             }
92868             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92869                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92870             }
92871             if (node.kind === 156 /* Parameter */
92872                 || node.kind === 159 /* PropertyDeclaration */
92873                 || node.kind === 158 /* PropertySignature */) {
92874                 if (!node.initializer)
92875                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
92876                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92877             }
92878             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92879             function cleanup(returnValue) {
92880                 errorNameNode = undefined;
92881                 if (!suppressNewDiagnosticContexts) {
92882                     getSymbolAccessibilityDiagnostic = oldDiag;
92883                 }
92884                 return returnValue || ts.createKeywordTypeNode(125 /* AnyKeyword */);
92885             }
92886         }
92887         function isDeclarationAndNotVisible(node) {
92888             node = ts.getParseTreeNode(node);
92889             switch (node.kind) {
92890                 case 244 /* FunctionDeclaration */:
92891                 case 249 /* ModuleDeclaration */:
92892                 case 246 /* InterfaceDeclaration */:
92893                 case 245 /* ClassDeclaration */:
92894                 case 247 /* TypeAliasDeclaration */:
92895                 case 248 /* EnumDeclaration */:
92896                     return !resolver.isDeclarationVisible(node);
92897                 // The following should be doing their own visibility checks based on filtering their members
92898                 case 242 /* VariableDeclaration */:
92899                     return !getBindingNameVisible(node);
92900                 case 253 /* ImportEqualsDeclaration */:
92901                 case 254 /* ImportDeclaration */:
92902                 case 260 /* ExportDeclaration */:
92903                 case 259 /* ExportAssignment */:
92904                     return false;
92905             }
92906             return false;
92907         }
92908         function getBindingNameVisible(elem) {
92909             if (ts.isOmittedExpression(elem)) {
92910                 return false;
92911             }
92912             if (ts.isBindingPattern(elem.name)) {
92913                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
92914                 return ts.some(elem.name.elements, getBindingNameVisible);
92915             }
92916             else {
92917                 return resolver.isDeclarationVisible(elem);
92918             }
92919         }
92920         function updateParamsList(node, params, modifierMask) {
92921             if (ts.hasModifier(node, 8 /* Private */)) {
92922                 return undefined; // TODO: GH#18217
92923             }
92924             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
92925             if (!newParams) {
92926                 return undefined; // TODO: GH#18217
92927             }
92928             return ts.createNodeArray(newParams, params.hasTrailingComma);
92929         }
92930         function updateAccessorParamsList(input, isPrivate) {
92931             var newParams;
92932             if (!isPrivate) {
92933                 var thisParameter = ts.getThisParameter(input);
92934                 if (thisParameter) {
92935                     newParams = [ensureParameter(thisParameter)];
92936                 }
92937             }
92938             if (ts.isSetAccessorDeclaration(input)) {
92939                 var newValueParameter = void 0;
92940                 if (!isPrivate) {
92941                     var valueParameter = ts.getSetAccessorValueParameter(input);
92942                     if (valueParameter) {
92943                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
92944                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
92945                     }
92946                 }
92947                 if (!newValueParameter) {
92948                     newValueParameter = ts.createParameter(
92949                     /*decorators*/ undefined, 
92950                     /*modifiers*/ undefined, 
92951                     /*dotDotDotToken*/ undefined, "value");
92952                 }
92953                 newParams = ts.append(newParams, newValueParameter);
92954             }
92955             return ts.createNodeArray(newParams || ts.emptyArray);
92956         }
92957         function ensureTypeParams(node, params) {
92958             return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
92959         }
92960         function isEnclosingDeclaration(node) {
92961             return ts.isSourceFile(node)
92962                 || ts.isTypeAliasDeclaration(node)
92963                 || ts.isModuleDeclaration(node)
92964                 || ts.isClassDeclaration(node)
92965                 || ts.isInterfaceDeclaration(node)
92966                 || ts.isFunctionLike(node)
92967                 || ts.isIndexSignatureDeclaration(node)
92968                 || ts.isMappedTypeNode(node);
92969         }
92970         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
92971             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
92972             handleSymbolAccessibilityError(visibilityResult);
92973             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
92974         }
92975         function preserveJsDoc(updated, original) {
92976             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
92977                 updated.jsDoc = original.jsDoc;
92978             }
92979             return ts.setCommentRange(updated, ts.getCommentRange(original));
92980         }
92981         function rewriteModuleSpecifier(parent, input) {
92982             if (!input)
92983                 return undefined; // TODO: GH#18217
92984             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 249 /* ModuleDeclaration */ && parent.kind !== 188 /* ImportType */);
92985             if (ts.isStringLiteralLike(input)) {
92986                 if (isBundledEmit) {
92987                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
92988                     if (newName) {
92989                         return ts.createLiteral(newName);
92990                     }
92991                 }
92992                 else {
92993                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
92994                     if (symbol) {
92995                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92996                     }
92997                 }
92998             }
92999             return input;
93000         }
93001         function transformImportEqualsDeclaration(decl) {
93002             if (!resolver.isDeclarationVisible(decl))
93003                 return;
93004             if (decl.moduleReference.kind === 265 /* ExternalModuleReference */) {
93005                 // Rewrite external module names if necessary
93006                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
93007                 return ts.updateImportEqualsDeclaration(decl, 
93008                 /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
93009             }
93010             else {
93011                 var oldDiag = getSymbolAccessibilityDiagnostic;
93012                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
93013                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
93014                 getSymbolAccessibilityDiagnostic = oldDiag;
93015                 return decl;
93016             }
93017         }
93018         function transformImportDeclaration(decl) {
93019             if (!decl.importClause) {
93020                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
93021                 return ts.updateImportDeclaration(decl, 
93022                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93023             }
93024             // The `importClause` visibility corresponds to the default's visibility.
93025             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
93026             if (!decl.importClause.namedBindings) {
93027                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
93028                 return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, 
93029                 /*namedBindings*/ undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93030             }
93031             if (decl.importClause.namedBindings.kind === 256 /* NamespaceImport */) {
93032                 // Namespace import (optionally with visible default)
93033                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
93034                 return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
93035             }
93036             // Named imports (optionally with visible default)
93037             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
93038             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
93039                 return ts.updateImportDeclaration(decl, 
93040                 /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93041             }
93042             // Augmentation of export depends on import
93043             if (resolver.isImportRequiredByAugmentation(decl)) {
93044                 return ts.updateImportDeclaration(decl, 
93045                 /*decorators*/ undefined, decl.modifiers, 
93046                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93047             }
93048             // Nothing visible
93049         }
93050         function transformAndReplaceLatePaintedStatements(statements) {
93051             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
93052             // error handling which must now be included in the output and themselves checked for errors.
93053             // For example:
93054             // ```
93055             // module A {
93056             //   export module Q {}
93057             //   import B = Q;
93058             //   import C = B;
93059             //   export import D = C;
93060             // }
93061             // ```
93062             // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must
93063             // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
93064             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
93065             while (ts.length(lateMarkedStatements)) {
93066                 var i = lateMarkedStatements.shift();
93067                 if (!ts.isLateVisibilityPaintedStatement(i)) {
93068                     return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
93069                 }
93070                 var priorNeedsDeclare = needsDeclare;
93071                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
93072                 var result = transformTopLevelDeclaration(i);
93073                 needsDeclare = priorNeedsDeclare;
93074                 lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
93075             }
93076             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
93077             // (and remove them from the set to examine for outter declarations)
93078             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
93079             function visitLateVisibilityMarkedStatements(statement) {
93080                 if (ts.isLateVisibilityPaintedStatement(statement)) {
93081                     var key = "" + ts.getOriginalNodeId(statement);
93082                     if (lateStatementReplacementMap.has(key)) {
93083                         var result = lateStatementReplacementMap.get(key);
93084                         lateStatementReplacementMap.delete(key);
93085                         if (result) {
93086                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
93087                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
93088                                 needsScopeFixMarker = true;
93089                             }
93090                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
93091                                 resultHasExternalModuleIndicator = true;
93092                             }
93093                         }
93094                         return result;
93095                     }
93096                 }
93097                 return statement;
93098             }
93099         }
93100         function visitDeclarationSubtree(input) {
93101             if (shouldStripInternal(input))
93102                 return;
93103             if (ts.isDeclaration(input)) {
93104                 if (isDeclarationAndNotVisible(input))
93105                     return;
93106                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
93107                     return;
93108                 }
93109             }
93110             // Elide implementation signatures from overload sets
93111             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93112                 return;
93113             // Elide semicolon class statements
93114             if (ts.isSemicolonClassElement(input))
93115                 return;
93116             var previousEnclosingDeclaration;
93117             if (isEnclosingDeclaration(input)) {
93118                 previousEnclosingDeclaration = enclosingDeclaration;
93119                 enclosingDeclaration = input;
93120             }
93121             var oldDiag = getSymbolAccessibilityDiagnostic;
93122             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
93123             // We'd see a TDZ violation at runtime
93124             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
93125             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
93126             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 173 /* TypeLiteral */ || input.kind === 186 /* MappedType */) && input.parent.kind !== 247 /* TypeAliasDeclaration */);
93127             // Emit methods which are private as properties with no type information
93128             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
93129                 if (ts.hasModifier(input, 8 /* Private */)) {
93130                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
93131                         return; // Elide all but the first overload
93132                     return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
93133                 }
93134             }
93135             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93136                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93137             }
93138             if (ts.isTypeQueryNode(input)) {
93139                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
93140             }
93141             if (shouldEnterSuppressNewDiagnosticsContextContext) {
93142                 // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do.
93143                 suppressNewDiagnosticContexts = true;
93144             }
93145             if (isProcessedComponent(input)) {
93146                 switch (input.kind) {
93147                     case 216 /* ExpressionWithTypeArguments */: {
93148                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
93149                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
93150                         }
93151                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93152                         return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
93153                     }
93154                     case 169 /* TypeReference */: {
93155                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
93156                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93157                         return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
93158                     }
93159                     case 166 /* ConstructSignature */:
93160                         return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93161                     case 162 /* Constructor */: {
93162                         // A constructor declaration may not have a type annotation
93163                         var ctor = ts.createSignatureDeclaration(162 /* Constructor */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters, 0 /* None */), 
93164                         /*type*/ undefined);
93165                         ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
93166                         return cleanup(ctor);
93167                     }
93168                     case 161 /* MethodDeclaration */: {
93169                         if (ts.isPrivateIdentifier(input.name)) {
93170                             return cleanup(/*returnValue*/ undefined);
93171                         }
93172                         var sig = ts.createSignatureDeclaration(160 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
93173                         sig.name = input.name;
93174                         sig.modifiers = ts.createNodeArray(ensureModifiers(input));
93175                         sig.questionToken = input.questionToken;
93176                         return cleanup(sig);
93177                     }
93178                     case 163 /* GetAccessor */: {
93179                         if (ts.isPrivateIdentifier(input.name)) {
93180                             return cleanup(/*returnValue*/ undefined);
93181                         }
93182                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
93183                         return cleanup(ts.updateGetAccessor(input, 
93184                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
93185                         /*body*/ undefined));
93186                     }
93187                     case 164 /* SetAccessor */: {
93188                         if (ts.isPrivateIdentifier(input.name)) {
93189                             return cleanup(/*returnValue*/ undefined);
93190                         }
93191                         return cleanup(ts.updateSetAccessor(input, 
93192                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), 
93193                         /*body*/ undefined));
93194                     }
93195                     case 159 /* PropertyDeclaration */:
93196                         if (ts.isPrivateIdentifier(input.name)) {
93197                             return cleanup(/*returnValue*/ undefined);
93198                         }
93199                         return cleanup(ts.updateProperty(input, 
93200                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93201                     case 158 /* PropertySignature */:
93202                         if (ts.isPrivateIdentifier(input.name)) {
93203                             return cleanup(/*returnValue*/ undefined);
93204                         }
93205                         return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93206                     case 160 /* MethodSignature */: {
93207                         if (ts.isPrivateIdentifier(input.name)) {
93208                             return cleanup(/*returnValue*/ undefined);
93209                         }
93210                         return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
93211                     }
93212                     case 165 /* CallSignature */: {
93213                         return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93214                     }
93215                     case 167 /* IndexSignature */: {
93216                         return cleanup(ts.updateIndexSignature(input, 
93217                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(125 /* AnyKeyword */)));
93218                     }
93219                     case 242 /* VariableDeclaration */: {
93220                         if (ts.isBindingPattern(input.name)) {
93221                             return recreateBindingPattern(input.name);
93222                         }
93223                         shouldEnterSuppressNewDiagnosticsContextContext = true;
93224                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
93225                         return cleanup(ts.updateTypeScriptVariableDeclaration(input, input.name, /*exclaimationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
93226                     }
93227                     case 155 /* TypeParameter */: {
93228                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
93229                             return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
93230                         }
93231                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93232                     }
93233                     case 180 /* ConditionalType */: {
93234                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
93235                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
93236                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
93237                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
93238                         var oldEnclosingDecl = enclosingDeclaration;
93239                         enclosingDeclaration = input.trueType;
93240                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
93241                         enclosingDeclaration = oldEnclosingDecl;
93242                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
93243                         return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
93244                     }
93245                     case 170 /* FunctionType */: {
93246                         return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93247                     }
93248                     case 171 /* ConstructorType */: {
93249                         return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93250                     }
93251                     case 188 /* ImportType */: {
93252                         if (!ts.isLiteralImportTypeNode(input))
93253                             return cleanup(input);
93254                         return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf));
93255                     }
93256                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
93257                 }
93258             }
93259             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93260             function cleanup(returnValue) {
93261                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
93262                     checkName(input);
93263                 }
93264                 if (isEnclosingDeclaration(input)) {
93265                     enclosingDeclaration = previousEnclosingDeclaration;
93266                 }
93267                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93268                     getSymbolAccessibilityDiagnostic = oldDiag;
93269                 }
93270                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
93271                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
93272                 }
93273                 if (returnValue === input) {
93274                     return returnValue;
93275                 }
93276                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
93277             }
93278         }
93279         function isPrivateMethodTypeParameter(node) {
93280             return node.parent.kind === 161 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
93281         }
93282         function visitDeclarationStatements(input) {
93283             if (!isPreservedDeclarationStatement(input)) {
93284                 // return undefined for unmatched kinds to omit them from the tree
93285                 return;
93286             }
93287             if (shouldStripInternal(input))
93288                 return;
93289             switch (input.kind) {
93290                 case 260 /* ExportDeclaration */: {
93291                     if (ts.isSourceFile(input.parent)) {
93292                         resultHasExternalModuleIndicator = true;
93293                     }
93294                     resultHasScopeMarker = true;
93295                     // Always visible if the parent node isn't dropped for being not visible
93296                     // Rewrite external module names if necessary
93297                     return ts.updateExportDeclaration(input, 
93298                     /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), input.isTypeOnly);
93299                 }
93300                 case 259 /* ExportAssignment */: {
93301                     // Always visible if the parent node isn't dropped for being not visible
93302                     if (ts.isSourceFile(input.parent)) {
93303                         resultHasExternalModuleIndicator = true;
93304                     }
93305                     resultHasScopeMarker = true;
93306                     if (input.expression.kind === 75 /* Identifier */) {
93307                         return input;
93308                     }
93309                     else {
93310                         var newId = ts.createOptimisticUniqueName("_default");
93311                         getSymbolAccessibilityDiagnostic = function () { return ({
93312                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
93313                             errorNode: input
93314                         }); };
93315                         var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93316                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93317                         return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
93318                     }
93319                 }
93320             }
93321             var result = transformTopLevelDeclaration(input);
93322             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
93323             lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
93324             return input;
93325         }
93326         function stripExportModifiers(statement) {
93327             if (ts.isImportEqualsDeclaration(statement) || ts.hasModifier(statement, 512 /* Default */)) {
93328                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
93329                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
93330                 return statement;
93331             }
93332             var clone = ts.getMutableClone(statement);
93333             var modifiers = ts.createModifiersFromModifierFlags(ts.getModifierFlags(statement) & (3071 /* All */ ^ 1 /* Export */));
93334             clone.modifiers = modifiers.length ? ts.createNodeArray(modifiers) : undefined;
93335             return clone;
93336         }
93337         function transformTopLevelDeclaration(input) {
93338             if (shouldStripInternal(input))
93339                 return;
93340             switch (input.kind) {
93341                 case 253 /* ImportEqualsDeclaration */: {
93342                     return transformImportEqualsDeclaration(input);
93343                 }
93344                 case 254 /* ImportDeclaration */: {
93345                     return transformImportDeclaration(input);
93346                 }
93347             }
93348             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
93349                 return;
93350             // Elide implementation signatures from overload sets
93351             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93352                 return;
93353             var previousEnclosingDeclaration;
93354             if (isEnclosingDeclaration(input)) {
93355                 previousEnclosingDeclaration = enclosingDeclaration;
93356                 enclosingDeclaration = input;
93357             }
93358             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
93359             var oldDiag = getSymbolAccessibilityDiagnostic;
93360             if (canProdiceDiagnostic) {
93361                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93362             }
93363             var previousNeedsDeclare = needsDeclare;
93364             switch (input.kind) {
93365                 case 247 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
93366                     return cleanup(ts.updateTypeAliasDeclaration(input, 
93367                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
93368                 case 246 /* InterfaceDeclaration */: {
93369                     return cleanup(ts.updateInterfaceDeclaration(input, 
93370                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
93371                 }
93372                 case 244 /* FunctionDeclaration */: {
93373                     // Generators lose their generator-ness, excepting their return type
93374                     var clean = cleanup(ts.updateFunctionDeclaration(input, 
93375                     /*decorators*/ undefined, ensureModifiers(input), 
93376                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
93377                     /*body*/ undefined));
93378                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
93379                         var props = resolver.getPropertiesOfContainerFunction(input);
93380                         var fakespace_1 = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || ts.createIdentifier("_default"), ts.createModuleBlock([]), 16 /* Namespace */);
93381                         fakespace_1.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
93382                         fakespace_1.parent = enclosingDeclaration;
93383                         fakespace_1.locals = ts.createSymbolTable(props);
93384                         fakespace_1.symbol = props[0].parent;
93385                         var declarations = ts.mapDefined(props, function (p) {
93386                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
93387                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
93388                             }
93389                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
93390                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
93391                             getSymbolAccessibilityDiagnostic = oldDiag;
93392                             var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
93393                             return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
93394                         });
93395                         var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
93396                         if (!ts.hasModifier(clean, 512 /* Default */)) {
93397                             return [clean, namespaceDecl];
93398                         }
93399                         var modifiers = ts.createModifiersFromModifierFlags((ts.getModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
93400                         var cleanDeclaration = ts.updateFunctionDeclaration(clean, 
93401                         /*decorators*/ undefined, modifiers, 
93402                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
93403                         /*body*/ undefined);
93404                         var namespaceDeclaration = ts.updateModuleDeclaration(namespaceDecl, 
93405                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
93406                         var exportDefaultDeclaration = ts.createExportAssignment(
93407                         /*decorators*/ undefined, 
93408                         /*modifiers*/ undefined, 
93409                         /*isExportEquals*/ false, namespaceDecl.name);
93410                         if (ts.isSourceFile(input.parent)) {
93411                             resultHasExternalModuleIndicator = true;
93412                         }
93413                         resultHasScopeMarker = true;
93414                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
93415                     }
93416                     else {
93417                         return clean;
93418                     }
93419                 }
93420                 case 249 /* ModuleDeclaration */: {
93421                     needsDeclare = false;
93422                     var inner = input.body;
93423                     if (inner && inner.kind === 250 /* ModuleBlock */) {
93424                         var oldNeedsScopeFix = needsScopeFixMarker;
93425                         var oldHasScopeFix = resultHasScopeMarker;
93426                         resultHasScopeMarker = false;
93427                         needsScopeFixMarker = false;
93428                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
93429                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
93430                         if (input.flags & 8388608 /* Ambient */) {
93431                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
93432                         }
93433                         // With the final list of statements, there are 3 possibilities:
93434                         // 1. There's an export assignment or export declaration in the namespace - do nothing
93435                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
93436                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
93437                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
93438                             if (needsScopeFixMarker) {
93439                                 lateStatements = ts.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports()]));
93440                             }
93441                             else {
93442                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
93443                             }
93444                         }
93445                         var body = ts.updateModuleBlock(inner, lateStatements);
93446                         needsDeclare = previousNeedsDeclare;
93447                         needsScopeFixMarker = oldNeedsScopeFix;
93448                         resultHasScopeMarker = oldHasScopeFix;
93449                         var mods = ensureModifiers(input);
93450                         return cleanup(ts.updateModuleDeclaration(input, 
93451                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
93452                     }
93453                     else {
93454                         needsDeclare = previousNeedsDeclare;
93455                         var mods = ensureModifiers(input);
93456                         needsDeclare = false;
93457                         ts.visitNode(inner, visitDeclarationStatements);
93458                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
93459                         var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
93460                         var body = lateStatementReplacementMap.get(id);
93461                         lateStatementReplacementMap.delete(id);
93462                         return cleanup(ts.updateModuleDeclaration(input, 
93463                         /*decorators*/ undefined, mods, input.name, body));
93464                     }
93465                 }
93466                 case 245 /* ClassDeclaration */: {
93467                     var modifiers = ts.createNodeArray(ensureModifiers(input));
93468                     var typeParameters = ensureTypeParams(input, input.typeParameters);
93469                     var ctor = ts.getFirstConstructorWithBody(input);
93470                     var parameterProperties = void 0;
93471                     if (ctor) {
93472                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
93473                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
93474                             if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
93475                                 return;
93476                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
93477                             if (param.name.kind === 75 /* Identifier */) {
93478                                 return preserveJsDoc(ts.createProperty(
93479                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
93480                             }
93481                             else {
93482                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
93483                                 return walkBindingPattern(param.name);
93484                             }
93485                             function walkBindingPattern(pattern) {
93486                                 var elems;
93487                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
93488                                     var elem = _a[_i];
93489                                     if (ts.isOmittedExpression(elem))
93490                                         continue;
93491                                     if (ts.isBindingPattern(elem.name)) {
93492                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
93493                                     }
93494                                     elems = elems || [];
93495                                     elems.push(ts.createProperty(
93496                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
93497                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
93498                                     /*initializer*/ undefined));
93499                                 }
93500                                 return elems;
93501                             }
93502                         }));
93503                         getSymbolAccessibilityDiagnostic = oldDiag_1;
93504                     }
93505                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
93506                     var privateIdentifier = hasPrivateIdentifier ? [
93507                         ts.createProperty(
93508                         /*decorators*/ undefined, 
93509                         /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
93510                         /*questionToken*/ undefined, 
93511                         /*type*/ undefined, 
93512                         /*initializer*/ undefined)
93513                     ] : undefined;
93514                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
93515                     var members = ts.createNodeArray(memberNodes);
93516                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
93517                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 100 /* NullKeyword */) {
93518                         // We must add a temporary declaration for the extends clause expression
93519                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
93520                         var newId_1 = ts.createOptimisticUniqueName(oldId + "_base");
93521                         getSymbolAccessibilityDiagnostic = function () { return ({
93522                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
93523                             errorNode: extendsClause_1,
93524                             typeName: input.name
93525                         }); };
93526                         var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93527                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93528                         var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
93529                             if (clause.token === 90 /* ExtendsKeyword */) {
93530                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
93531                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
93532                                 var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
93533                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
93534                                 return newClause;
93535                             }
93536                             return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 100 /* NullKeyword */; })), visitDeclarationSubtree));
93537                         }));
93538                         return [statement, cleanup(ts.updateClassDeclaration(input, 
93539                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
93540                     }
93541                     else {
93542                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
93543                         return cleanup(ts.updateClassDeclaration(input, 
93544                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
93545                     }
93546                 }
93547                 case 225 /* VariableStatement */: {
93548                     return cleanup(transformVariableStatement(input));
93549                 }
93550                 case 248 /* EnumDeclaration */: {
93551                     return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
93552                         if (shouldStripInternal(m))
93553                             return;
93554                         // Rewrite enum values to their constants, if available
93555                         var constValue = resolver.getConstantValue(m);
93556                         return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
93557                     }))));
93558                 }
93559             }
93560             // Anything left unhandled is an error, so this should be unreachable
93561             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
93562             function cleanup(node) {
93563                 if (isEnclosingDeclaration(input)) {
93564                     enclosingDeclaration = previousEnclosingDeclaration;
93565                 }
93566                 if (canProdiceDiagnostic) {
93567                     getSymbolAccessibilityDiagnostic = oldDiag;
93568                 }
93569                 if (input.kind === 249 /* ModuleDeclaration */) {
93570                     needsDeclare = previousNeedsDeclare;
93571                 }
93572                 if (node === input) {
93573                     return node;
93574                 }
93575                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
93576             }
93577         }
93578         function transformVariableStatement(input) {
93579             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
93580                 return;
93581             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
93582             if (!ts.length(nodes))
93583                 return;
93584             return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes));
93585         }
93586         function recreateBindingPattern(d) {
93587             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
93588         }
93589         function recreateBindingElement(e) {
93590             if (e.kind === 215 /* OmittedExpression */) {
93591                 return;
93592             }
93593             if (e.name) {
93594                 if (!getBindingNameVisible(e))
93595                     return;
93596                 if (ts.isBindingPattern(e.name)) {
93597                     return recreateBindingPattern(e.name);
93598                 }
93599                 else {
93600                     return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
93601                 }
93602             }
93603         }
93604         function checkName(node) {
93605             var oldDiag;
93606             if (!suppressNewDiagnosticContexts) {
93607                 oldDiag = getSymbolAccessibilityDiagnostic;
93608                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
93609             }
93610             errorNameNode = node.name;
93611             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
93612             var decl = node;
93613             var entityName = decl.name.expression;
93614             checkEntityNameVisibility(entityName, enclosingDeclaration);
93615             if (!suppressNewDiagnosticContexts) {
93616                 getSymbolAccessibilityDiagnostic = oldDiag;
93617             }
93618             errorNameNode = undefined;
93619         }
93620         function shouldStripInternal(node) {
93621             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
93622         }
93623         function isScopeMarker(node) {
93624             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
93625         }
93626         function hasScopeMarker(statements) {
93627             return ts.some(statements, isScopeMarker);
93628         }
93629         function ensureModifiers(node) {
93630             var currentFlags = ts.getModifierFlags(node);
93631             var newFlags = ensureModifierFlags(node);
93632             if (currentFlags === newFlags) {
93633                 return node.modifiers;
93634             }
93635             return ts.createModifiersFromModifierFlags(newFlags);
93636         }
93637         function ensureModifierFlags(node) {
93638             var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
93639             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
93640             var parentIsFile = node.parent.kind === 290 /* SourceFile */;
93641             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
93642                 mask ^= 2 /* Ambient */;
93643                 additions = 0 /* None */;
93644             }
93645             return maskModifierFlags(node, mask, additions);
93646         }
93647         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
93648             var accessorType = getTypeAnnotationFromAccessor(node);
93649             if (!accessorType && node !== accessors.firstAccessor) {
93650                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
93651                 // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message
93652                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
93653             }
93654             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
93655                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
93656                 // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message
93657                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
93658             }
93659             return accessorType;
93660         }
93661         function transformHeritageClauses(nodes) {
93662             return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
93663                 return ts.isEntityNameExpression(t.expression) || (clause.token === 90 /* ExtendsKeyword */ && t.expression.kind === 100 /* NullKeyword */);
93664             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
93665         }
93666     }
93667     ts.transformDeclarations = transformDeclarations;
93668     function isAlwaysType(node) {
93669         if (node.kind === 246 /* InterfaceDeclaration */) {
93670             return true;
93671         }
93672         return false;
93673     }
93674     // Elide "public" modifier, as it is the default
93675     function maskModifiers(node, modifierMask, modifierAdditions) {
93676         return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
93677     }
93678     function maskModifierFlags(node, modifierMask, modifierAdditions) {
93679         if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; }
93680         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
93681         var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
93682         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
93683             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
93684             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
93685             flags ^= 1 /* Export */;
93686         }
93687         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
93688             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
93689         }
93690         return flags;
93691     }
93692     function getTypeAnnotationFromAccessor(accessor) {
93693         if (accessor) {
93694             return accessor.kind === 163 /* GetAccessor */
93695                 ? accessor.type // Getter - return type
93696                 : accessor.parameters.length > 0
93697                     ? accessor.parameters[0].type // Setter parameter type
93698                     : undefined;
93699         }
93700     }
93701     function canHaveLiteralInitializer(node) {
93702         switch (node.kind) {
93703             case 159 /* PropertyDeclaration */:
93704             case 158 /* PropertySignature */:
93705                 return !ts.hasModifier(node, 8 /* Private */);
93706             case 156 /* Parameter */:
93707             case 242 /* VariableDeclaration */:
93708                 return true;
93709         }
93710         return false;
93711     }
93712     function isPreservedDeclarationStatement(node) {
93713         switch (node.kind) {
93714             case 244 /* FunctionDeclaration */:
93715             case 249 /* ModuleDeclaration */:
93716             case 253 /* ImportEqualsDeclaration */:
93717             case 246 /* InterfaceDeclaration */:
93718             case 245 /* ClassDeclaration */:
93719             case 247 /* TypeAliasDeclaration */:
93720             case 248 /* EnumDeclaration */:
93721             case 225 /* VariableStatement */:
93722             case 254 /* ImportDeclaration */:
93723             case 260 /* ExportDeclaration */:
93724             case 259 /* ExportAssignment */:
93725                 return true;
93726         }
93727         return false;
93728     }
93729     function isProcessedComponent(node) {
93730         switch (node.kind) {
93731             case 166 /* ConstructSignature */:
93732             case 162 /* Constructor */:
93733             case 161 /* MethodDeclaration */:
93734             case 163 /* GetAccessor */:
93735             case 164 /* SetAccessor */:
93736             case 159 /* PropertyDeclaration */:
93737             case 158 /* PropertySignature */:
93738             case 160 /* MethodSignature */:
93739             case 165 /* CallSignature */:
93740             case 167 /* IndexSignature */:
93741             case 242 /* VariableDeclaration */:
93742             case 155 /* TypeParameter */:
93743             case 216 /* ExpressionWithTypeArguments */:
93744             case 169 /* TypeReference */:
93745             case 180 /* ConditionalType */:
93746             case 170 /* FunctionType */:
93747             case 171 /* ConstructorType */:
93748             case 188 /* ImportType */:
93749                 return true;
93750         }
93751         return false;
93752     }
93753 })(ts || (ts = {}));
93754 /* @internal */
93755 var ts;
93756 (function (ts) {
93757     function getModuleTransformer(moduleKind) {
93758         switch (moduleKind) {
93759             case ts.ModuleKind.ESNext:
93760             case ts.ModuleKind.ES2020:
93761             case ts.ModuleKind.ES2015:
93762                 return ts.transformECMAScriptModule;
93763             case ts.ModuleKind.System:
93764                 return ts.transformSystemModule;
93765             default:
93766                 return ts.transformModule;
93767         }
93768     }
93769     var TransformationState;
93770     (function (TransformationState) {
93771         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
93772         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
93773         TransformationState[TransformationState["Completed"] = 2] = "Completed";
93774         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
93775     })(TransformationState || (TransformationState = {}));
93776     var SyntaxKindFeatureFlags;
93777     (function (SyntaxKindFeatureFlags) {
93778         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
93779         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
93780     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
93781     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
93782     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93783         return {
93784             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
93785             declarationTransformers: getDeclarationTransformers(customTransformers),
93786         };
93787     }
93788     ts.getTransformers = getTransformers;
93789     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93790         if (emitOnlyDtsFiles)
93791             return ts.emptyArray;
93792         var jsx = compilerOptions.jsx;
93793         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93794         var moduleKind = ts.getEmitModuleKind(compilerOptions);
93795         var transformers = [];
93796         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
93797         transformers.push(ts.transformTypeScript);
93798         transformers.push(ts.transformClassFields);
93799         if (jsx === 2 /* React */) {
93800             transformers.push(ts.transformJsx);
93801         }
93802         if (languageVersion < 99 /* ESNext */) {
93803             transformers.push(ts.transformESNext);
93804         }
93805         if (languageVersion < 7 /* ES2020 */) {
93806             transformers.push(ts.transformES2020);
93807         }
93808         if (languageVersion < 6 /* ES2019 */) {
93809             transformers.push(ts.transformES2019);
93810         }
93811         if (languageVersion < 5 /* ES2018 */) {
93812             transformers.push(ts.transformES2018);
93813         }
93814         if (languageVersion < 4 /* ES2017 */) {
93815             transformers.push(ts.transformES2017);
93816         }
93817         if (languageVersion < 3 /* ES2016 */) {
93818             transformers.push(ts.transformES2016);
93819         }
93820         if (languageVersion < 2 /* ES2015 */) {
93821             transformers.push(ts.transformES2015);
93822             transformers.push(ts.transformGenerators);
93823         }
93824         transformers.push(getModuleTransformer(moduleKind));
93825         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
93826         // for ES3.
93827         if (languageVersion < 1 /* ES5 */) {
93828             transformers.push(ts.transformES5);
93829         }
93830         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
93831         return transformers;
93832     }
93833     function getDeclarationTransformers(customTransformers) {
93834         var transformers = [];
93835         transformers.push(ts.transformDeclarations);
93836         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
93837         return transformers;
93838     }
93839     /**
93840      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
93841      */
93842     function wrapCustomTransformer(transformer) {
93843         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
93844     }
93845     /**
93846      * Wrap a transformer factory that may return a custom script or declaration transformer object.
93847      */
93848     function wrapCustomTransformerFactory(transformer, handleDefault) {
93849         return function (context) {
93850             var customTransformer = transformer(context);
93851             return typeof customTransformer === "function"
93852                 ? handleDefault(customTransformer)
93853                 : wrapCustomTransformer(customTransformer);
93854         };
93855     }
93856     function wrapScriptTransformerFactory(transformer) {
93857         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
93858     }
93859     function wrapDeclarationTransformerFactory(transformer) {
93860         return wrapCustomTransformerFactory(transformer, ts.identity);
93861     }
93862     function noEmitSubstitution(_hint, node) {
93863         return node;
93864     }
93865     ts.noEmitSubstitution = noEmitSubstitution;
93866     function noEmitNotification(hint, node, callback) {
93867         callback(hint, node);
93868     }
93869     ts.noEmitNotification = noEmitNotification;
93870     /**
93871      * Transforms an array of SourceFiles by passing them through each transformer.
93872      *
93873      * @param resolver The emit resolver provided by the checker.
93874      * @param host The emit host object used to interact with the file system.
93875      * @param options Compiler options to surface in the `TransformationContext`.
93876      * @param nodes An array of nodes to transform.
93877      * @param transforms An array of `TransformerFactory` callbacks.
93878      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
93879      */
93880     function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
93881         var enabledSyntaxKindFeatures = new Array(331 /* Count */);
93882         var lexicalEnvironmentVariableDeclarations;
93883         var lexicalEnvironmentFunctionDeclarations;
93884         var lexicalEnvironmentStatements;
93885         var lexicalEnvironmentFlags = 0 /* None */;
93886         var lexicalEnvironmentVariableDeclarationsStack = [];
93887         var lexicalEnvironmentFunctionDeclarationsStack = [];
93888         var lexicalEnvironmentStatementsStack = [];
93889         var lexicalEnvironmentFlagsStack = [];
93890         var lexicalEnvironmentStackOffset = 0;
93891         var lexicalEnvironmentSuspended = false;
93892         var emitHelpers;
93893         var onSubstituteNode = noEmitSubstitution;
93894         var onEmitNode = noEmitNotification;
93895         var state = 0 /* Uninitialized */;
93896         var diagnostics = [];
93897         // The transformation context is provided to each transformer as part of transformer
93898         // initialization.
93899         var context = {
93900             getCompilerOptions: function () { return options; },
93901             getEmitResolver: function () { return resolver; },
93902             getEmitHost: function () { return host; },
93903             startLexicalEnvironment: startLexicalEnvironment,
93904             suspendLexicalEnvironment: suspendLexicalEnvironment,
93905             resumeLexicalEnvironment: resumeLexicalEnvironment,
93906             endLexicalEnvironment: endLexicalEnvironment,
93907             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
93908             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
93909             hoistVariableDeclaration: hoistVariableDeclaration,
93910             hoistFunctionDeclaration: hoistFunctionDeclaration,
93911             addInitializationStatement: addInitializationStatement,
93912             requestEmitHelper: requestEmitHelper,
93913             readEmitHelpers: readEmitHelpers,
93914             enableSubstitution: enableSubstitution,
93915             enableEmitNotification: enableEmitNotification,
93916             isSubstitutionEnabled: isSubstitutionEnabled,
93917             isEmitNotificationEnabled: isEmitNotificationEnabled,
93918             get onSubstituteNode() { return onSubstituteNode; },
93919             set onSubstituteNode(value) {
93920                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93921                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93922                 onSubstituteNode = value;
93923             },
93924             get onEmitNode() { return onEmitNode; },
93925             set onEmitNode(value) {
93926                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93927                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93928                 onEmitNode = value;
93929             },
93930             addDiagnostic: function (diag) {
93931                 diagnostics.push(diag);
93932             }
93933         };
93934         // Ensure the parse tree is clean before applying transformations
93935         for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
93936             var node = nodes_4[_i];
93937             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
93938         }
93939         ts.performance.mark("beforeTransform");
93940         // Chain together and initialize each transformer.
93941         var transformersWithContext = transformers.map(function (t) { return t(context); });
93942         var transformation = function (node) {
93943             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
93944                 var transform = transformersWithContext_1[_i];
93945                 node = transform(node);
93946             }
93947             return node;
93948         };
93949         // prevent modification of transformation hooks.
93950         state = 1 /* Initialized */;
93951         // Transform each node.
93952         var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
93953         // prevent modification of the lexical environment.
93954         state = 2 /* Completed */;
93955         ts.performance.mark("afterTransform");
93956         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
93957         return {
93958             transformed: transformed,
93959             substituteNode: substituteNode,
93960             emitNodeWithNotification: emitNodeWithNotification,
93961             isEmitNotificationEnabled: isEmitNotificationEnabled,
93962             dispose: dispose,
93963             diagnostics: diagnostics
93964         };
93965         function transformRoot(node) {
93966             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
93967         }
93968         /**
93969          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
93970          */
93971         function enableSubstitution(kind) {
93972             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93973             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
93974         }
93975         /**
93976          * Determines whether expression substitutions are enabled for the provided node.
93977          */
93978         function isSubstitutionEnabled(node) {
93979             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
93980                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
93981         }
93982         /**
93983          * Emits a node with possible substitution.
93984          *
93985          * @param hint A hint as to the intended usage of the node.
93986          * @param node The node to emit.
93987          * @param emitCallback The callback used to emit the node or its substitute.
93988          */
93989         function substituteNode(hint, node) {
93990             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
93991             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
93992         }
93993         /**
93994          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
93995          */
93996         function enableEmitNotification(kind) {
93997             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93998             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
93999         }
94000         /**
94001          * Determines whether before/after emit notifications should be raised in the pretty
94002          * printer when it emits a node.
94003          */
94004         function isEmitNotificationEnabled(node) {
94005             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
94006                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
94007         }
94008         /**
94009          * Emits a node with possible emit notification.
94010          *
94011          * @param hint A hint as to the intended usage of the node.
94012          * @param node The node to emit.
94013          * @param emitCallback The callback used to emit the node.
94014          */
94015         function emitNodeWithNotification(hint, node, emitCallback) {
94016             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
94017             if (node) {
94018                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
94019                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
94020                 if (isEmitNotificationEnabled(node)) {
94021                     onEmitNode(hint, node, emitCallback);
94022                 }
94023                 else {
94024                     emitCallback(hint, node);
94025                 }
94026             }
94027         }
94028         /**
94029          * Records a hoisted variable declaration for the provided name within a lexical environment.
94030          */
94031         function hoistVariableDeclaration(name) {
94032             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94033             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94034             var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
94035             if (!lexicalEnvironmentVariableDeclarations) {
94036                 lexicalEnvironmentVariableDeclarations = [decl];
94037             }
94038             else {
94039                 lexicalEnvironmentVariableDeclarations.push(decl);
94040             }
94041             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
94042                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
94043             }
94044         }
94045         /**
94046          * Records a hoisted function declaration within a lexical environment.
94047          */
94048         function hoistFunctionDeclaration(func) {
94049             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94050             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94051             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
94052             if (!lexicalEnvironmentFunctionDeclarations) {
94053                 lexicalEnvironmentFunctionDeclarations = [func];
94054             }
94055             else {
94056                 lexicalEnvironmentFunctionDeclarations.push(func);
94057             }
94058         }
94059         /**
94060          * Adds an initialization statement to the top of the lexical environment.
94061          */
94062         function addInitializationStatement(node) {
94063             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94064             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94065             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
94066             if (!lexicalEnvironmentStatements) {
94067                 lexicalEnvironmentStatements = [node];
94068             }
94069             else {
94070                 lexicalEnvironmentStatements.push(node);
94071             }
94072         }
94073         /**
94074          * Starts a new lexical environment. Any existing hoisted variable or function declarations
94075          * are pushed onto a stack, and the related storage variables are reset.
94076          */
94077         function startLexicalEnvironment() {
94078             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94079             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94080             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94081             // Save the current lexical environment. Rather than resizing the array we adjust the
94082             // stack size variable. This allows us to reuse existing array slots we've
94083             // already allocated between transformations to avoid allocation and GC overhead during
94084             // transformation.
94085             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
94086             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
94087             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
94088             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
94089             lexicalEnvironmentStackOffset++;
94090             lexicalEnvironmentVariableDeclarations = undefined;
94091             lexicalEnvironmentFunctionDeclarations = undefined;
94092             lexicalEnvironmentStatements = undefined;
94093             lexicalEnvironmentFlags = 0 /* None */;
94094         }
94095         /** Suspends the current lexical environment, usually after visiting a parameter list. */
94096         function suspendLexicalEnvironment() {
94097             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94098             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94099             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
94100             lexicalEnvironmentSuspended = true;
94101         }
94102         /** Resumes a suspended lexical environment, usually before visiting a function body. */
94103         function resumeLexicalEnvironment() {
94104             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94105             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94106             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
94107             lexicalEnvironmentSuspended = false;
94108         }
94109         /**
94110          * Ends a lexical environment. The previous set of hoisted declarations are restored and
94111          * any hoisted declarations added in this environment are returned.
94112          */
94113         function endLexicalEnvironment() {
94114             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94115             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94116             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94117             var statements;
94118             if (lexicalEnvironmentVariableDeclarations ||
94119                 lexicalEnvironmentFunctionDeclarations ||
94120                 lexicalEnvironmentStatements) {
94121                 if (lexicalEnvironmentFunctionDeclarations) {
94122                     statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
94123                 }
94124                 if (lexicalEnvironmentVariableDeclarations) {
94125                     var statement = ts.createVariableStatement(
94126                     /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
94127                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
94128                     if (!statements) {
94129                         statements = [statement];
94130                     }
94131                     else {
94132                         statements.push(statement);
94133                     }
94134                 }
94135                 if (lexicalEnvironmentStatements) {
94136                     if (!statements) {
94137                         statements = __spreadArrays(lexicalEnvironmentStatements);
94138                     }
94139                     else {
94140                         statements = __spreadArrays(statements, lexicalEnvironmentStatements);
94141                     }
94142                 }
94143             }
94144             // Restore the previous lexical environment.
94145             lexicalEnvironmentStackOffset--;
94146             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
94147             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
94148             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
94149             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
94150             if (lexicalEnvironmentStackOffset === 0) {
94151                 lexicalEnvironmentVariableDeclarationsStack = [];
94152                 lexicalEnvironmentFunctionDeclarationsStack = [];
94153                 lexicalEnvironmentStatementsStack = [];
94154                 lexicalEnvironmentFlagsStack = [];
94155             }
94156             return statements;
94157         }
94158         function setLexicalEnvironmentFlags(flags, value) {
94159             lexicalEnvironmentFlags = value ?
94160                 lexicalEnvironmentFlags | flags :
94161                 lexicalEnvironmentFlags & ~flags;
94162         }
94163         function getLexicalEnvironmentFlags() {
94164             return lexicalEnvironmentFlags;
94165         }
94166         function requestEmitHelper(helper) {
94167             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94168             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94169             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
94170             if (helper.dependencies) {
94171                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
94172                     var h = _a[_i];
94173                     requestEmitHelper(h);
94174                 }
94175             }
94176             emitHelpers = ts.append(emitHelpers, helper);
94177         }
94178         function readEmitHelpers() {
94179             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94180             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94181             var helpers = emitHelpers;
94182             emitHelpers = undefined;
94183             return helpers;
94184         }
94185         function dispose() {
94186             if (state < 3 /* Disposed */) {
94187                 // Clean up emit nodes on parse tree
94188                 for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
94189                     var node = nodes_5[_i];
94190                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
94191                 }
94192                 // Release references to external entries for GC purposes.
94193                 lexicalEnvironmentVariableDeclarations = undefined;
94194                 lexicalEnvironmentVariableDeclarationsStack = undefined;
94195                 lexicalEnvironmentFunctionDeclarations = undefined;
94196                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
94197                 onSubstituteNode = undefined;
94198                 onEmitNode = undefined;
94199                 emitHelpers = undefined;
94200                 // Prevent further use of the transformation result.
94201                 state = 3 /* Disposed */;
94202             }
94203         }
94204     }
94205     ts.transformNodes = transformNodes;
94206 })(ts || (ts = {}));
94207 var ts;
94208 (function (ts) {
94209     var brackets = createBracketsMap();
94210     var syntheticParent = { pos: -1, end: -1 };
94211     /*@internal*/
94212     function isBuildInfoFile(file) {
94213         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
94214     }
94215     ts.isBuildInfoFile = isBuildInfoFile;
94216     /*@internal*/
94217     /**
94218      * Iterates over the source files that are expected to have an emit output.
94219      *
94220      * @param host An EmitHost.
94221      * @param action The action to execute.
94222      * @param sourceFilesOrTargetSourceFile
94223      *   If an array, the full list of source files to emit.
94224      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
94225      */
94226     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
94227         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
94228         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
94229         var options = host.getCompilerOptions();
94230         if (options.outFile || options.out) {
94231             var prepends = host.getPrependNodes();
94232             if (sourceFiles.length || prepends.length) {
94233                 var bundle = ts.createBundle(sourceFiles, prepends);
94234                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
94235                 if (result) {
94236                     return result;
94237                 }
94238             }
94239         }
94240         else {
94241             if (!onlyBuildInfo) {
94242                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
94243                     var sourceFile = sourceFiles_1[_a];
94244                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
94245                     if (result) {
94246                         return result;
94247                     }
94248                 }
94249             }
94250             if (includeBuildInfo) {
94251                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(host.getCompilerOptions());
94252                 if (buildInfoPath)
94253                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
94254             }
94255         }
94256     }
94257     ts.forEachEmittedFile = forEachEmittedFile;
94258     function getTsBuildInfoEmitOutputFilePath(options) {
94259         var configFile = options.configFilePath;
94260         if (!ts.isIncrementalCompilation(options))
94261             return undefined;
94262         if (options.tsBuildInfoFile)
94263             return options.tsBuildInfoFile;
94264         var outPath = options.outFile || options.out;
94265         var buildInfoExtensionLess;
94266         if (outPath) {
94267             buildInfoExtensionLess = ts.removeFileExtension(outPath);
94268         }
94269         else {
94270             if (!configFile)
94271                 return undefined;
94272             var configFileExtensionLess = ts.removeFileExtension(configFile);
94273             buildInfoExtensionLess = options.outDir ?
94274                 options.rootDir ?
94275                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
94276                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
94277                 configFileExtensionLess;
94278         }
94279         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
94280     }
94281     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
94282     /*@internal*/
94283     function getOutputPathsForBundle(options, forceDtsPaths) {
94284         var outPath = options.outFile || options.out;
94285         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
94286         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
94287         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
94288         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94289         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
94290         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
94291     }
94292     ts.getOutputPathsForBundle = getOutputPathsForBundle;
94293     /*@internal*/
94294     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
94295         var options = host.getCompilerOptions();
94296         if (sourceFile.kind === 291 /* Bundle */) {
94297             return getOutputPathsForBundle(options, forceDtsPaths);
94298         }
94299         else {
94300             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
94301             var isJsonFile = ts.isJsonSourceFile(sourceFile);
94302             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
94303             var isJsonEmittedToSameLocation = isJsonFile &&
94304                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
94305             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
94306             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
94307             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
94308             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94309             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
94310         }
94311     }
94312     ts.getOutputPathsFor = getOutputPathsFor;
94313     function getSourceMapFilePath(jsFilePath, options) {
94314         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
94315     }
94316     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
94317     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
94318     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
94319     /* @internal */
94320     function getOutputExtension(sourceFile, options) {
94321         if (ts.isJsonSourceFile(sourceFile)) {
94322             return ".json" /* Json */;
94323         }
94324         if (options.jsx === 1 /* Preserve */) {
94325             if (ts.isSourceFileJS(sourceFile)) {
94326                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
94327                     return ".jsx" /* Jsx */;
94328                 }
94329             }
94330             else if (sourceFile.languageVariant === 1 /* JSX */) {
94331                 // TypeScript source file preserving JSX syntax
94332                 return ".jsx" /* Jsx */;
94333             }
94334         }
94335         return ".js" /* Js */;
94336     }
94337     ts.getOutputExtension = getOutputExtension;
94338     function rootDirOfOptions(configFile) {
94339         return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
94340     }
94341     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
94342         return outputDir ?
94343             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
94344             inputFileName;
94345     }
94346     /* @internal */
94347     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
94348         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
94349         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
94350     }
94351     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
94352     function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
94353         if (configFile.options.emitDeclarationOnly)
94354             return undefined;
94355         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
94356         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
94357             ".json" /* Json */ :
94358             ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
94359                 ".jsx" /* Jsx */ :
94360                 ".js" /* Js */);
94361         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
94362             outputFileName :
94363             undefined;
94364     }
94365     function createAddOutput() {
94366         var outputs;
94367         return { addOutput: addOutput, getOutputs: getOutputs };
94368         function addOutput(path) {
94369             if (path) {
94370                 (outputs || (outputs = [])).push(path);
94371             }
94372         }
94373         function getOutputs() {
94374             return outputs || ts.emptyArray;
94375         }
94376     }
94377     function getSingleOutputFileNames(configFile, addOutput) {
94378         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94379         addOutput(jsFilePath);
94380         addOutput(sourceMapFilePath);
94381         addOutput(declarationFilePath);
94382         addOutput(declarationMapPath);
94383         addOutput(buildInfoPath);
94384     }
94385     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
94386         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94387             return;
94388         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94389         addOutput(js);
94390         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94391             return;
94392         if (js && configFile.options.sourceMap) {
94393             addOutput(js + ".map");
94394         }
94395         if (ts.getEmitDeclarations(configFile.options)) {
94396             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94397             addOutput(dts);
94398             if (configFile.options.declarationMap) {
94399                 addOutput(dts + ".map");
94400             }
94401         }
94402     }
94403     /*@internal*/
94404     function getAllProjectOutputs(configFile, ignoreCase) {
94405         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94406         if (configFile.options.outFile || configFile.options.out) {
94407             getSingleOutputFileNames(configFile, addOutput);
94408         }
94409         else {
94410             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
94411                 var inputFileName = _c[_b];
94412                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
94413             }
94414             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
94415         }
94416         return getOutputs();
94417     }
94418     ts.getAllProjectOutputs = getAllProjectOutputs;
94419     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
94420         inputFileName = ts.normalizePath(inputFileName);
94421         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
94422         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94423         if (commandLine.options.outFile || commandLine.options.out) {
94424             getSingleOutputFileNames(commandLine, addOutput);
94425         }
94426         else {
94427             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
94428         }
94429         return getOutputs();
94430     }
94431     ts.getOutputFileNames = getOutputFileNames;
94432     /*@internal*/
94433     function getFirstProjectOutput(configFile, ignoreCase) {
94434         if (configFile.options.outFile || configFile.options.out) {
94435             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
94436             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
94437         }
94438         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
94439             var inputFileName = _b[_a];
94440             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94441                 continue;
94442             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94443             if (jsFilePath)
94444                 return jsFilePath;
94445             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94446                 continue;
94447             if (ts.getEmitDeclarations(configFile.options)) {
94448                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94449             }
94450         }
94451         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
94452         if (buildInfoPath)
94453             return buildInfoPath;
94454         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
94455     }
94456     ts.getFirstProjectOutput = getFirstProjectOutput;
94457     /*@internal*/
94458     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
94459     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
94460         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
94461         var compilerOptions = host.getCompilerOptions();
94462         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
94463         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
94464         var emitterDiagnostics = ts.createDiagnosticCollection();
94465         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
94466         var writer = ts.createTextWriter(newLine);
94467         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
94468         var bundleBuildInfo;
94469         var emitSkipped = false;
94470         var exportedModulesFromDeclarationEmit;
94471         // Emit each output file
94472         enter();
94473         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
94474         exit();
94475         return {
94476             emitSkipped: emitSkipped,
94477             diagnostics: emitterDiagnostics.getDiagnostics(),
94478             emittedFiles: emittedFilesList,
94479             sourceMaps: sourceMapDataList,
94480             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
94481         };
94482         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
94483             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94484             var buildInfoDirectory;
94485             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
94486                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94487                 bundleBuildInfo = {
94488                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
94489                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
94490                 };
94491             }
94492             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
94493             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
94494             emitBuildInfo(bundleBuildInfo, buildInfoPath);
94495             if (!emitSkipped && emittedFilesList) {
94496                 if (!emitOnlyDtsFiles) {
94497                     if (jsFilePath) {
94498                         emittedFilesList.push(jsFilePath);
94499                     }
94500                     if (sourceMapFilePath) {
94501                         emittedFilesList.push(sourceMapFilePath);
94502                     }
94503                     if (buildInfoPath) {
94504                         emittedFilesList.push(buildInfoPath);
94505                     }
94506                 }
94507                 if (declarationFilePath) {
94508                     emittedFilesList.push(declarationFilePath);
94509                 }
94510                 if (declarationMapPath) {
94511                     emittedFilesList.push(declarationMapPath);
94512                 }
94513             }
94514             function relativeToBuildInfo(path) {
94515                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
94516             }
94517         }
94518         function emitBuildInfo(bundle, buildInfoPath) {
94519             // Write build information if applicable
94520             if (!buildInfoPath || targetSourceFile || emitSkipped)
94521                 return;
94522             var program = host.getProgramBuildInfo();
94523             if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
94524                 emitSkipped = true;
94525                 return;
94526             }
94527             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
94528             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
94529         }
94530         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
94531             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
94532                 return;
94533             }
94534             // Make sure not to write js file and source map file if any of them cannot be written
94535             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
94536                 emitSkipped = true;
94537                 return;
94538             }
94539             // Transform the source files
94540             var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
94541             var printerOptions = {
94542                 removeComments: compilerOptions.removeComments,
94543                 newLine: compilerOptions.newLine,
94544                 noEmitHelpers: compilerOptions.noEmitHelpers,
94545                 module: compilerOptions.module,
94546                 target: compilerOptions.target,
94547                 sourceMap: compilerOptions.sourceMap,
94548                 inlineSourceMap: compilerOptions.inlineSourceMap,
94549                 inlineSources: compilerOptions.inlineSources,
94550                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94551                 writeBundleFileInfo: !!bundleBuildInfo,
94552                 relativeToBuildInfo: relativeToBuildInfo
94553             };
94554             // Create a printer to print the nodes
94555             var printer = createPrinter(printerOptions, {
94556                 // resolver hooks
94557                 hasGlobalName: resolver.hasGlobalName,
94558                 // transform hooks
94559                 onEmitNode: transform.emitNodeWithNotification,
94560                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
94561                 substituteNode: transform.substituteNode,
94562             });
94563             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
94564             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
94565             // Clean up emit nodes on parse tree
94566             transform.dispose();
94567             if (bundleBuildInfo)
94568                 bundleBuildInfo.js = printer.bundleFileInfo;
94569         }
94570         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
94571             if (!sourceFileOrBundle)
94572                 return;
94573             if (!declarationFilePath) {
94574                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
94575                     emitSkipped = true;
94576                 return;
94577             }
94578             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
94579             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
94580             // Setup and perform the transformation to retrieve declarations from the input files
94581             var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
94582             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
94583                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
94584                 // Do that here when emitting only dts files
94585                 filesForEmit.forEach(collectLinkedAliases);
94586             }
94587             var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
94588             if (ts.length(declarationTransform.diagnostics)) {
94589                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
94590                     var diagnostic = _b[_a];
94591                     emitterDiagnostics.add(diagnostic);
94592                 }
94593             }
94594             var printerOptions = {
94595                 removeComments: compilerOptions.removeComments,
94596                 newLine: compilerOptions.newLine,
94597                 noEmitHelpers: true,
94598                 module: compilerOptions.module,
94599                 target: compilerOptions.target,
94600                 sourceMap: compilerOptions.sourceMap,
94601                 inlineSourceMap: compilerOptions.inlineSourceMap,
94602                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94603                 onlyPrintJsDocStyle: true,
94604                 writeBundleFileInfo: !!bundleBuildInfo,
94605                 recordInternalSection: !!bundleBuildInfo,
94606                 relativeToBuildInfo: relativeToBuildInfo
94607             };
94608             var declarationPrinter = createPrinter(printerOptions, {
94609                 // resolver hooks
94610                 hasGlobalName: resolver.hasGlobalName,
94611                 // transform hooks
94612                 onEmitNode: declarationTransform.emitNodeWithNotification,
94613                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
94614                 substituteNode: declarationTransform.substituteNode,
94615             });
94616             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
94617             emitSkipped = emitSkipped || declBlocked;
94618             if (!declBlocked || forceDtsEmit) {
94619                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
94620                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
94621                     sourceMap: compilerOptions.declarationMap,
94622                     sourceRoot: compilerOptions.sourceRoot,
94623                     mapRoot: compilerOptions.mapRoot,
94624                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
94625                 });
94626                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 290 /* SourceFile */) {
94627                     var sourceFile = declarationTransform.transformed[0];
94628                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
94629                 }
94630             }
94631             declarationTransform.dispose();
94632             if (bundleBuildInfo)
94633                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
94634         }
94635         function collectLinkedAliases(node) {
94636             if (ts.isExportAssignment(node)) {
94637                 if (node.expression.kind === 75 /* Identifier */) {
94638                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
94639                 }
94640                 return;
94641             }
94642             else if (ts.isExportSpecifier(node)) {
94643                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
94644                 return;
94645             }
94646             ts.forEachChild(node, collectLinkedAliases);
94647         }
94648         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
94649             var bundle = sourceFileOrBundle.kind === 291 /* Bundle */ ? sourceFileOrBundle : undefined;
94650             var sourceFile = sourceFileOrBundle.kind === 290 /* SourceFile */ ? sourceFileOrBundle : undefined;
94651             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
94652             var sourceMapGenerator;
94653             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
94654                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
94655             }
94656             if (bundle) {
94657                 printer.writeBundle(bundle, writer, sourceMapGenerator);
94658             }
94659             else {
94660                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
94661             }
94662             if (sourceMapGenerator) {
94663                 if (sourceMapDataList) {
94664                     sourceMapDataList.push({
94665                         inputSourceFileNames: sourceMapGenerator.getSources(),
94666                         sourceMap: sourceMapGenerator.toJSON()
94667                     });
94668                 }
94669                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
94670                 if (sourceMappingURL) {
94671                     if (!writer.isAtStartOfLine())
94672                         writer.rawWrite(newLine);
94673                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
94674                 }
94675                 // Write the source map
94676                 if (sourceMapFilePath) {
94677                     var sourceMap = sourceMapGenerator.toString();
94678                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
94679                 }
94680             }
94681             else {
94682                 writer.writeLine();
94683             }
94684             // Write the output file
94685             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
94686             // Reset state
94687             writer.clear();
94688         }
94689         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
94690             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
94691                 && (sourceFileOrBundle.kind !== 290 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
94692         }
94693         function getSourceRoot(mapOptions) {
94694             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
94695             // relative paths of the sources list in the sourcemap
94696             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
94697             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
94698         }
94699         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
94700             if (mapOptions.sourceRoot)
94701                 return host.getCommonSourceDirectory();
94702             if (mapOptions.mapRoot) {
94703                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94704                 if (sourceFile) {
94705                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94706                     // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
94707                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94708                 }
94709                 if (ts.getRootLength(sourceMapDir) === 0) {
94710                     // The relative paths are relative to the common directory
94711                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94712                 }
94713                 return sourceMapDir;
94714             }
94715             return ts.getDirectoryPath(ts.normalizePath(filePath));
94716         }
94717         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
94718             if (mapOptions.inlineSourceMap) {
94719                 // Encode the sourceMap into the sourceMap url
94720                 var sourceMapText = sourceMapGenerator.toString();
94721                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
94722                 return "data:application/json;base64," + base64SourceMapText;
94723             }
94724             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
94725             if (mapOptions.mapRoot) {
94726                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94727                 if (sourceFile) {
94728                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94729                     // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
94730                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94731                 }
94732                 if (ts.getRootLength(sourceMapDir) === 0) {
94733                     // The relative paths are relative to the common directory
94734                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94735                     return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
94736                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
94737                     host.getCurrentDirectory(), host.getCanonicalFileName, 
94738                     /*isAbsolutePathAnUrl*/ true);
94739                 }
94740                 else {
94741                     return ts.combinePaths(sourceMapDir, sourceMapFile);
94742                 }
94743             }
94744             return sourceMapFile;
94745         }
94746     }
94747     ts.emitFiles = emitFiles;
94748     /*@internal*/
94749     function getBuildInfoText(buildInfo) {
94750         return JSON.stringify(buildInfo, undefined, 2);
94751     }
94752     ts.getBuildInfoText = getBuildInfoText;
94753     /*@internal*/
94754     function getBuildInfo(buildInfoText) {
94755         return JSON.parse(buildInfoText);
94756     }
94757     ts.getBuildInfo = getBuildInfo;
94758     /*@internal*/
94759     ts.notImplementedResolver = {
94760         hasGlobalName: ts.notImplemented,
94761         getReferencedExportContainer: ts.notImplemented,
94762         getReferencedImportDeclaration: ts.notImplemented,
94763         getReferencedDeclarationWithCollidingName: ts.notImplemented,
94764         isDeclarationWithCollidingName: ts.notImplemented,
94765         isValueAliasDeclaration: ts.notImplemented,
94766         isReferencedAliasDeclaration: ts.notImplemented,
94767         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
94768         getNodeCheckFlags: ts.notImplemented,
94769         isDeclarationVisible: ts.notImplemented,
94770         isLateBound: function (_node) { return false; },
94771         collectLinkedAliases: ts.notImplemented,
94772         isImplementationOfOverload: ts.notImplemented,
94773         isRequiredInitializedParameter: ts.notImplemented,
94774         isOptionalUninitializedParameterProperty: ts.notImplemented,
94775         isExpandoFunctionDeclaration: ts.notImplemented,
94776         getPropertiesOfContainerFunction: ts.notImplemented,
94777         createTypeOfDeclaration: ts.notImplemented,
94778         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
94779         createTypeOfExpression: ts.notImplemented,
94780         createLiteralConstValue: ts.notImplemented,
94781         isSymbolAccessible: ts.notImplemented,
94782         isEntityNameVisible: ts.notImplemented,
94783         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
94784         getConstantValue: ts.notImplemented,
94785         getReferencedValueDeclaration: ts.notImplemented,
94786         getTypeReferenceSerializationKind: ts.notImplemented,
94787         isOptionalParameter: ts.notImplemented,
94788         moduleExportsSomeValue: ts.notImplemented,
94789         isArgumentsLocalBinding: ts.notImplemented,
94790         getExternalModuleFileFromDeclaration: ts.notImplemented,
94791         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
94792         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
94793         isLiteralConstDeclaration: ts.notImplemented,
94794         getJsxFactoryEntity: ts.notImplemented,
94795         getAllAccessorDeclarations: ts.notImplemented,
94796         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
94797         isBindingCapturedByNode: ts.notImplemented,
94798         getDeclarationStatementsForSourceFile: ts.notImplemented,
94799         isImportRequiredByAugmentation: ts.notImplemented,
94800     };
94801     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
94802         var sourceFiles = bundle.sourceFiles.map(function (fileName) {
94803             var sourceFile = ts.createNode(290 /* SourceFile */, 0, 0);
94804             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
94805             sourceFile.text = "";
94806             sourceFile.statements = ts.createNodeArray();
94807             return sourceFile;
94808         });
94809         var jsBundle = ts.Debug.checkDefined(bundle.js);
94810         ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
94811             var sourceFile = sourceFiles[prologueInfo.file];
94812             sourceFile.text = prologueInfo.text;
94813             sourceFile.end = prologueInfo.text.length;
94814             sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
94815                 var statement = ts.createNode(226 /* ExpressionStatement */, directive.pos, directive.end);
94816                 statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
94817                 statement.expression.text = directive.expression.text;
94818                 return statement;
94819             }));
94820         });
94821         return sourceFiles;
94822     }
94823     /*@internal*/
94824     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
94825         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
94826         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
94827         if (!buildInfoText)
94828             return buildInfoPath;
94829         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
94830         if (!jsFileText)
94831             return jsFilePath;
94832         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
94833         // error if no source map or for now if inline sourcemap
94834         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
94835             return sourceMapFilePath || "inline sourcemap decoding";
94836         // read declaration text
94837         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
94838         if (declarationFilePath && !declarationText)
94839             return declarationFilePath;
94840         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
94841         // error if no source map or for now if inline sourcemap
94842         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
94843             return declarationMapPath || "inline sourcemap decoding";
94844         var buildInfo = getBuildInfo(buildInfoText);
94845         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
94846             return buildInfoPath;
94847         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94848         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
94849         /*onlyOwnText*/ true);
94850         var outputFiles = [];
94851         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
94852         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
94853         var emitHost = {
94854             getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
94855             getCanonicalFileName: host.getCanonicalFileName,
94856             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
94857             getCompilerOptions: function () { return config.options; },
94858             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
94859             getNewLine: function () { return host.getNewLine(); },
94860             getSourceFile: ts.returnUndefined,
94861             getSourceFileByPath: ts.returnUndefined,
94862             getSourceFiles: function () { return sourceFilesForJsEmit; },
94863             getLibFileFromReference: ts.notImplemented,
94864             isSourceFileFromExternalLibrary: ts.returnFalse,
94865             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
94866             getProjectReferenceRedirect: ts.returnUndefined,
94867             isSourceOfProjectReferenceRedirect: ts.returnFalse,
94868             writeFile: function (name, text, writeByteOrderMark) {
94869                 switch (name) {
94870                     case jsFilePath:
94871                         if (jsFileText === text)
94872                             return;
94873                         break;
94874                     case sourceMapFilePath:
94875                         if (sourceMapText === text)
94876                             return;
94877                         break;
94878                     case buildInfoPath:
94879                         var newBuildInfo = getBuildInfo(text);
94880                         newBuildInfo.program = buildInfo.program;
94881                         // Update sourceFileInfo
94882                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
94883                         newBuildInfo.bundle.js.sources = js.sources;
94884                         if (dts) {
94885                             newBuildInfo.bundle.dts.sources = dts.sources;
94886                         }
94887                         newBuildInfo.bundle.sourceFiles = sourceFiles;
94888                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
94889                         return;
94890                     case declarationFilePath:
94891                         if (declarationText === text)
94892                             return;
94893                         break;
94894                     case declarationMapPath:
94895                         if (declarationMapText === text)
94896                             return;
94897                         break;
94898                     default:
94899                         ts.Debug.fail("Unexpected path: " + name);
94900                 }
94901                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
94902             },
94903             isEmitBlocked: ts.returnFalse,
94904             readFile: function (f) { return host.readFile(f); },
94905             fileExists: function (f) { return host.fileExists(f); },
94906             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
94907             getProgramBuildInfo: ts.returnUndefined,
94908             getSourceFileFromReference: ts.returnUndefined,
94909             redirectTargetsMap: ts.createMultiMap()
94910         };
94911         emitFiles(ts.notImplementedResolver, emitHost, 
94912         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
94913         return outputFiles;
94914     }
94915     ts.emitUsingBuildInfo = emitUsingBuildInfo;
94916     var PipelinePhase;
94917     (function (PipelinePhase) {
94918         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
94919         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
94920         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
94921         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
94922         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
94923     })(PipelinePhase || (PipelinePhase = {}));
94924     function createPrinter(printerOptions, handlers) {
94925         if (printerOptions === void 0) { printerOptions = {}; }
94926         if (handlers === void 0) { handlers = {}; }
94927         var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken;
94928         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
94929         var newLine = ts.getNewLineCharacter(printerOptions);
94930         var moduleKind = ts.getEmitModuleKind(printerOptions);
94931         var bundledHelpers = ts.createMap();
94932         var currentSourceFile;
94933         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
94934         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
94935         var generatedNames; // Set of names generated by the NameGenerator.
94936         var tempFlagsStack; // Stack of enclosing name generation scopes.
94937         var tempFlags; // TempFlags for the current name generation scope.
94938         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
94939         var reservedNames; // TempFlags to reserve in nested name generation scopes.
94940         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
94941         var writer;
94942         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
94943         var write = writeBase;
94944         var isOwnFileEmit;
94945         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
94946         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
94947         var recordInternalSection = printerOptions.recordInternalSection;
94948         var sourceFileTextPos = 0;
94949         var sourceFileTextKind = "text" /* Text */;
94950         // Source Maps
94951         var sourceMapsDisabled = true;
94952         var sourceMapGenerator;
94953         var sourceMapSource;
94954         var sourceMapSourceIndex = -1;
94955         // Comments
94956         var containerPos = -1;
94957         var containerEnd = -1;
94958         var declarationListContainerEnd = -1;
94959         var currentLineMap;
94960         var detachedCommentsInfo;
94961         var hasWrittenComment = false;
94962         var commentsDisabled = !!printerOptions.removeComments;
94963         var lastNode;
94964         var lastSubstitution;
94965         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
94966         reset();
94967         return {
94968             // public API
94969             printNode: printNode,
94970             printList: printList,
94971             printFile: printFile,
94972             printBundle: printBundle,
94973             // internal API
94974             writeNode: writeNode,
94975             writeList: writeList,
94976             writeFile: writeFile,
94977             writeBundle: writeBundle,
94978             bundleFileInfo: bundleFileInfo
94979         };
94980         function printNode(hint, node, sourceFile) {
94981             switch (hint) {
94982                 case 0 /* SourceFile */:
94983                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
94984                     break;
94985                 case 2 /* IdentifierName */:
94986                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
94987                     break;
94988                 case 1 /* Expression */:
94989                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
94990                     break;
94991             }
94992             switch (node.kind) {
94993                 case 290 /* SourceFile */: return printFile(node);
94994                 case 291 /* Bundle */: return printBundle(node);
94995                 case 292 /* UnparsedSource */: return printUnparsedSource(node);
94996             }
94997             writeNode(hint, node, sourceFile, beginPrint());
94998             return endPrint();
94999         }
95000         function printList(format, nodes, sourceFile) {
95001             writeList(format, nodes, sourceFile, beginPrint());
95002             return endPrint();
95003         }
95004         function printBundle(bundle) {
95005             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
95006             return endPrint();
95007         }
95008         function printFile(sourceFile) {
95009             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
95010             return endPrint();
95011         }
95012         function printUnparsedSource(unparsed) {
95013             writeUnparsedSource(unparsed, beginPrint());
95014             return endPrint();
95015         }
95016         function writeNode(hint, node, sourceFile, output) {
95017             var previousWriter = writer;
95018             setWriter(output, /*_sourceMapGenerator*/ undefined);
95019             print(hint, node, sourceFile);
95020             reset();
95021             writer = previousWriter;
95022         }
95023         function writeList(format, nodes, sourceFile, output) {
95024             var previousWriter = writer;
95025             setWriter(output, /*_sourceMapGenerator*/ undefined);
95026             if (sourceFile) {
95027                 setSourceFile(sourceFile);
95028             }
95029             emitList(syntheticParent, nodes, format);
95030             reset();
95031             writer = previousWriter;
95032         }
95033         function getTextPosWithWriteLine() {
95034             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
95035         }
95036         function updateOrPushBundleFileTextLike(pos, end, kind) {
95037             var last = ts.lastOrUndefined(bundleFileInfo.sections);
95038             if (last && last.kind === kind) {
95039                 last.end = end;
95040             }
95041             else {
95042                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
95043             }
95044         }
95045         function recordBundleFileInternalSectionStart(node) {
95046             if (recordInternalSection &&
95047                 bundleFileInfo &&
95048                 currentSourceFile &&
95049                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
95050                 ts.isInternalDeclaration(node, currentSourceFile) &&
95051                 sourceFileTextKind !== "internal" /* Internal */) {
95052                 var prevSourceFileTextKind = sourceFileTextKind;
95053                 recordBundleFileTextLikeSection(writer.getTextPos());
95054                 sourceFileTextPos = getTextPosWithWriteLine();
95055                 sourceFileTextKind = "internal" /* Internal */;
95056                 return prevSourceFileTextKind;
95057             }
95058             return undefined;
95059         }
95060         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
95061             if (prevSourceFileTextKind) {
95062                 recordBundleFileTextLikeSection(writer.getTextPos());
95063                 sourceFileTextPos = getTextPosWithWriteLine();
95064                 sourceFileTextKind = prevSourceFileTextKind;
95065             }
95066         }
95067         function recordBundleFileTextLikeSection(end) {
95068             if (sourceFileTextPos < end) {
95069                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
95070                 return true;
95071             }
95072             return false;
95073         }
95074         function writeBundle(bundle, output, sourceMapGenerator) {
95075             var _a;
95076             isOwnFileEmit = false;
95077             var previousWriter = writer;
95078             setWriter(output, sourceMapGenerator);
95079             emitShebangIfNeeded(bundle);
95080             emitPrologueDirectivesIfNeeded(bundle);
95081             emitHelpers(bundle);
95082             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
95083             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
95084                 var prepend = _c[_b];
95085                 writeLine();
95086                 var pos = writer.getTextPos();
95087                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
95088                 if (savedSections)
95089                     bundleFileInfo.sections = [];
95090                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
95091                 if (bundleFileInfo) {
95092                     var newSections = bundleFileInfo.sections;
95093                     bundleFileInfo.sections = savedSections;
95094                     if (prepend.oldFileOfCurrentEmit)
95095                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
95096                     else {
95097                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
95098                         bundleFileInfo.sections.push({
95099                             pos: pos,
95100                             end: writer.getTextPos(),
95101                             kind: "prepend" /* Prepend */,
95102                             data: relativeToBuildInfo(prepend.fileName),
95103                             texts: newSections
95104                         });
95105                     }
95106                 }
95107             }
95108             sourceFileTextPos = getTextPosWithWriteLine();
95109             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
95110                 var sourceFile = _e[_d];
95111                 print(0 /* SourceFile */, sourceFile, sourceFile);
95112             }
95113             if (bundleFileInfo && bundle.sourceFiles.length) {
95114                 var end = writer.getTextPos();
95115                 if (recordBundleFileTextLikeSection(end)) {
95116                     // Store prologues
95117                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
95118                     if (prologues) {
95119                         if (!bundleFileInfo.sources)
95120                             bundleFileInfo.sources = {};
95121                         bundleFileInfo.sources.prologues = prologues;
95122                     }
95123                     // Store helpes
95124                     var helpers = getHelpersFromBundledSourceFiles(bundle);
95125                     if (helpers) {
95126                         if (!bundleFileInfo.sources)
95127                             bundleFileInfo.sources = {};
95128                         bundleFileInfo.sources.helpers = helpers;
95129                     }
95130                 }
95131             }
95132             reset();
95133             writer = previousWriter;
95134         }
95135         function writeUnparsedSource(unparsed, output) {
95136             var previousWriter = writer;
95137             setWriter(output, /*_sourceMapGenerator*/ undefined);
95138             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
95139             reset();
95140             writer = previousWriter;
95141         }
95142         function writeFile(sourceFile, output, sourceMapGenerator) {
95143             isOwnFileEmit = true;
95144             var previousWriter = writer;
95145             setWriter(output, sourceMapGenerator);
95146             emitShebangIfNeeded(sourceFile);
95147             emitPrologueDirectivesIfNeeded(sourceFile);
95148             print(0 /* SourceFile */, sourceFile, sourceFile);
95149             reset();
95150             writer = previousWriter;
95151         }
95152         function beginPrint() {
95153             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
95154         }
95155         function endPrint() {
95156             var text = ownWriter.getText();
95157             ownWriter.clear();
95158             return text;
95159         }
95160         function print(hint, node, sourceFile) {
95161             if (sourceFile) {
95162                 setSourceFile(sourceFile);
95163             }
95164             pipelineEmit(hint, node);
95165         }
95166         function setSourceFile(sourceFile) {
95167             currentSourceFile = sourceFile;
95168             currentLineMap = undefined;
95169             detachedCommentsInfo = undefined;
95170             if (sourceFile) {
95171                 setSourceMapSource(sourceFile);
95172             }
95173         }
95174         function setWriter(_writer, _sourceMapGenerator) {
95175             if (_writer && printerOptions.omitTrailingSemicolon) {
95176                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
95177             }
95178             writer = _writer; // TODO: GH#18217
95179             sourceMapGenerator = _sourceMapGenerator;
95180             sourceMapsDisabled = !writer || !sourceMapGenerator;
95181         }
95182         function reset() {
95183             nodeIdToGeneratedName = [];
95184             autoGeneratedIdToGeneratedName = [];
95185             generatedNames = ts.createMap();
95186             tempFlagsStack = [];
95187             tempFlags = 0 /* Auto */;
95188             reservedNamesStack = [];
95189             currentSourceFile = undefined;
95190             currentLineMap = undefined;
95191             detachedCommentsInfo = undefined;
95192             lastNode = undefined;
95193             lastSubstitution = undefined;
95194             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
95195         }
95196         function getCurrentLineMap() {
95197             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
95198         }
95199         function emit(node) {
95200             if (node === undefined)
95201                 return;
95202             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
95203             var substitute = pipelineEmit(4 /* Unspecified */, node);
95204             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
95205             return substitute;
95206         }
95207         function emitIdentifierName(node) {
95208             if (node === undefined)
95209                 return;
95210             return pipelineEmit(2 /* IdentifierName */, node);
95211         }
95212         function emitExpression(node) {
95213             if (node === undefined)
95214                 return;
95215             return pipelineEmit(1 /* Expression */, node);
95216         }
95217         function emitJsxAttributeValue(node) {
95218             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
95219         }
95220         function pipelineEmit(emitHint, node) {
95221             var savedLastNode = lastNode;
95222             var savedLastSubstitution = lastSubstitution;
95223             var savedPreserveSourceNewlines = preserveSourceNewlines;
95224             lastNode = node;
95225             lastSubstitution = undefined;
95226             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
95227                 preserveSourceNewlines = false;
95228             }
95229             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
95230             pipelinePhase(emitHint, node);
95231             ts.Debug.assert(lastNode === node);
95232             var substitute = lastSubstitution;
95233             lastNode = savedLastNode;
95234             lastSubstitution = savedLastSubstitution;
95235             preserveSourceNewlines = savedPreserveSourceNewlines;
95236             return substitute || node;
95237         }
95238         function getPipelinePhase(phase, emitHint, node) {
95239             switch (phase) {
95240                 case 0 /* Notification */:
95241                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
95242                         return pipelineEmitWithNotification;
95243                     }
95244                 // falls through
95245                 case 1 /* Substitution */:
95246                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
95247                         return pipelineEmitWithSubstitution;
95248                     }
95249                 // falls through
95250                 case 2 /* Comments */:
95251                     if (!commentsDisabled && node.kind !== 290 /* SourceFile */) {
95252                         return pipelineEmitWithComments;
95253                     }
95254                 // falls through
95255                 case 3 /* SourceMaps */:
95256                     if (!sourceMapsDisabled && node.kind !== 290 /* SourceFile */ && !ts.isInJsonFile(node)) {
95257                         return pipelineEmitWithSourceMap;
95258                     }
95259                 // falls through
95260                 case 4 /* Emit */:
95261                     return pipelineEmitWithHint;
95262                 default:
95263                     return ts.Debug.assertNever(phase);
95264             }
95265         }
95266         function getNextPipelinePhase(currentPhase, emitHint, node) {
95267             return getPipelinePhase(currentPhase + 1, emitHint, node);
95268         }
95269         function pipelineEmitWithNotification(hint, node) {
95270             ts.Debug.assert(lastNode === node);
95271             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
95272             onEmitNode(hint, node, pipelinePhase);
95273             ts.Debug.assert(lastNode === node);
95274         }
95275         function pipelineEmitWithHint(hint, node) {
95276             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95277             if (hint === 0 /* SourceFile */)
95278                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
95279             if (hint === 2 /* IdentifierName */)
95280                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
95281             if (hint === 6 /* JsxAttributeValue */)
95282                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
95283             if (hint === 3 /* MappedTypeParameter */)
95284                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
95285             if (hint === 5 /* EmbeddedStatement */) {
95286                 ts.Debug.assertNode(node, ts.isEmptyStatement);
95287                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
95288             }
95289             if (hint === 4 /* Unspecified */) {
95290                 if (ts.isKeyword(node.kind))
95291                     return writeTokenNode(node, writeKeyword);
95292                 switch (node.kind) {
95293                     // Pseudo-literals
95294                     case 15 /* TemplateHead */:
95295                     case 16 /* TemplateMiddle */:
95296                     case 17 /* TemplateTail */:
95297                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95298                     case 292 /* UnparsedSource */:
95299                     case 286 /* UnparsedPrepend */:
95300                         return emitUnparsedSourceOrPrepend(node);
95301                     case 285 /* UnparsedPrologue */:
95302                         return writeUnparsedNode(node);
95303                     case 287 /* UnparsedText */:
95304                     case 288 /* UnparsedInternalText */:
95305                         return emitUnparsedTextLike(node);
95306                     case 289 /* UnparsedSyntheticReference */:
95307                         return emitUnparsedSyntheticReference(node);
95308                     // Identifiers
95309                     case 75 /* Identifier */:
95310                         return emitIdentifier(node);
95311                     // PrivateIdentifiers
95312                     case 76 /* PrivateIdentifier */:
95313                         return emitPrivateIdentifier(node);
95314                     // Parse tree nodes
95315                     // Names
95316                     case 153 /* QualifiedName */:
95317                         return emitQualifiedName(node);
95318                     case 154 /* ComputedPropertyName */:
95319                         return emitComputedPropertyName(node);
95320                     // Signature elements
95321                     case 155 /* TypeParameter */:
95322                         return emitTypeParameter(node);
95323                     case 156 /* Parameter */:
95324                         return emitParameter(node);
95325                     case 157 /* Decorator */:
95326                         return emitDecorator(node);
95327                     // Type members
95328                     case 158 /* PropertySignature */:
95329                         return emitPropertySignature(node);
95330                     case 159 /* PropertyDeclaration */:
95331                         return emitPropertyDeclaration(node);
95332                     case 160 /* MethodSignature */:
95333                         return emitMethodSignature(node);
95334                     case 161 /* MethodDeclaration */:
95335                         return emitMethodDeclaration(node);
95336                     case 162 /* Constructor */:
95337                         return emitConstructor(node);
95338                     case 163 /* GetAccessor */:
95339                     case 164 /* SetAccessor */:
95340                         return emitAccessorDeclaration(node);
95341                     case 165 /* CallSignature */:
95342                         return emitCallSignature(node);
95343                     case 166 /* ConstructSignature */:
95344                         return emitConstructSignature(node);
95345                     case 167 /* IndexSignature */:
95346                         return emitIndexSignature(node);
95347                     // Types
95348                     case 168 /* TypePredicate */:
95349                         return emitTypePredicate(node);
95350                     case 169 /* TypeReference */:
95351                         return emitTypeReference(node);
95352                     case 170 /* FunctionType */:
95353                         return emitFunctionType(node);
95354                     case 300 /* JSDocFunctionType */:
95355                         return emitJSDocFunctionType(node);
95356                     case 171 /* ConstructorType */:
95357                         return emitConstructorType(node);
95358                     case 172 /* TypeQuery */:
95359                         return emitTypeQuery(node);
95360                     case 173 /* TypeLiteral */:
95361                         return emitTypeLiteral(node);
95362                     case 174 /* ArrayType */:
95363                         return emitArrayType(node);
95364                     case 175 /* TupleType */:
95365                         return emitTupleType(node);
95366                     case 176 /* OptionalType */:
95367                         return emitOptionalType(node);
95368                     case 178 /* UnionType */:
95369                         return emitUnionType(node);
95370                     case 179 /* IntersectionType */:
95371                         return emitIntersectionType(node);
95372                     case 180 /* ConditionalType */:
95373                         return emitConditionalType(node);
95374                     case 181 /* InferType */:
95375                         return emitInferType(node);
95376                     case 182 /* ParenthesizedType */:
95377                         return emitParenthesizedType(node);
95378                     case 216 /* ExpressionWithTypeArguments */:
95379                         return emitExpressionWithTypeArguments(node);
95380                     case 183 /* ThisType */:
95381                         return emitThisType();
95382                     case 184 /* TypeOperator */:
95383                         return emitTypeOperator(node);
95384                     case 185 /* IndexedAccessType */:
95385                         return emitIndexedAccessType(node);
95386                     case 186 /* MappedType */:
95387                         return emitMappedType(node);
95388                     case 187 /* LiteralType */:
95389                         return emitLiteralType(node);
95390                     case 188 /* ImportType */:
95391                         return emitImportTypeNode(node);
95392                     case 295 /* JSDocAllType */:
95393                         writePunctuation("*");
95394                         return;
95395                     case 296 /* JSDocUnknownType */:
95396                         writePunctuation("?");
95397                         return;
95398                     case 297 /* JSDocNullableType */:
95399                         return emitJSDocNullableType(node);
95400                     case 298 /* JSDocNonNullableType */:
95401                         return emitJSDocNonNullableType(node);
95402                     case 299 /* JSDocOptionalType */:
95403                         return emitJSDocOptionalType(node);
95404                     case 177 /* RestType */:
95405                     case 301 /* JSDocVariadicType */:
95406                         return emitRestOrJSDocVariadicType(node);
95407                     // Binding patterns
95408                     case 189 /* ObjectBindingPattern */:
95409                         return emitObjectBindingPattern(node);
95410                     case 190 /* ArrayBindingPattern */:
95411                         return emitArrayBindingPattern(node);
95412                     case 191 /* BindingElement */:
95413                         return emitBindingElement(node);
95414                     // Misc
95415                     case 221 /* TemplateSpan */:
95416                         return emitTemplateSpan(node);
95417                     case 222 /* SemicolonClassElement */:
95418                         return emitSemicolonClassElement();
95419                     // Statements
95420                     case 223 /* Block */:
95421                         return emitBlock(node);
95422                     case 225 /* VariableStatement */:
95423                         return emitVariableStatement(node);
95424                     case 224 /* EmptyStatement */:
95425                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
95426                     case 226 /* ExpressionStatement */:
95427                         return emitExpressionStatement(node);
95428                     case 227 /* IfStatement */:
95429                         return emitIfStatement(node);
95430                     case 228 /* DoStatement */:
95431                         return emitDoStatement(node);
95432                     case 229 /* WhileStatement */:
95433                         return emitWhileStatement(node);
95434                     case 230 /* ForStatement */:
95435                         return emitForStatement(node);
95436                     case 231 /* ForInStatement */:
95437                         return emitForInStatement(node);
95438                     case 232 /* ForOfStatement */:
95439                         return emitForOfStatement(node);
95440                     case 233 /* ContinueStatement */:
95441                         return emitContinueStatement(node);
95442                     case 234 /* BreakStatement */:
95443                         return emitBreakStatement(node);
95444                     case 235 /* ReturnStatement */:
95445                         return emitReturnStatement(node);
95446                     case 236 /* WithStatement */:
95447                         return emitWithStatement(node);
95448                     case 237 /* SwitchStatement */:
95449                         return emitSwitchStatement(node);
95450                     case 238 /* LabeledStatement */:
95451                         return emitLabeledStatement(node);
95452                     case 239 /* ThrowStatement */:
95453                         return emitThrowStatement(node);
95454                     case 240 /* TryStatement */:
95455                         return emitTryStatement(node);
95456                     case 241 /* DebuggerStatement */:
95457                         return emitDebuggerStatement(node);
95458                     // Declarations
95459                     case 242 /* VariableDeclaration */:
95460                         return emitVariableDeclaration(node);
95461                     case 243 /* VariableDeclarationList */:
95462                         return emitVariableDeclarationList(node);
95463                     case 244 /* FunctionDeclaration */:
95464                         return emitFunctionDeclaration(node);
95465                     case 245 /* ClassDeclaration */:
95466                         return emitClassDeclaration(node);
95467                     case 246 /* InterfaceDeclaration */:
95468                         return emitInterfaceDeclaration(node);
95469                     case 247 /* TypeAliasDeclaration */:
95470                         return emitTypeAliasDeclaration(node);
95471                     case 248 /* EnumDeclaration */:
95472                         return emitEnumDeclaration(node);
95473                     case 249 /* ModuleDeclaration */:
95474                         return emitModuleDeclaration(node);
95475                     case 250 /* ModuleBlock */:
95476                         return emitModuleBlock(node);
95477                     case 251 /* CaseBlock */:
95478                         return emitCaseBlock(node);
95479                     case 252 /* NamespaceExportDeclaration */:
95480                         return emitNamespaceExportDeclaration(node);
95481                     case 253 /* ImportEqualsDeclaration */:
95482                         return emitImportEqualsDeclaration(node);
95483                     case 254 /* ImportDeclaration */:
95484                         return emitImportDeclaration(node);
95485                     case 255 /* ImportClause */:
95486                         return emitImportClause(node);
95487                     case 256 /* NamespaceImport */:
95488                         return emitNamespaceImport(node);
95489                     case 262 /* NamespaceExport */:
95490                         return emitNamespaceExport(node);
95491                     case 257 /* NamedImports */:
95492                         return emitNamedImports(node);
95493                     case 258 /* ImportSpecifier */:
95494                         return emitImportSpecifier(node);
95495                     case 259 /* ExportAssignment */:
95496                         return emitExportAssignment(node);
95497                     case 260 /* ExportDeclaration */:
95498                         return emitExportDeclaration(node);
95499                     case 261 /* NamedExports */:
95500                         return emitNamedExports(node);
95501                     case 263 /* ExportSpecifier */:
95502                         return emitExportSpecifier(node);
95503                     case 264 /* MissingDeclaration */:
95504                         return;
95505                     // Module references
95506                     case 265 /* ExternalModuleReference */:
95507                         return emitExternalModuleReference(node);
95508                     // JSX (non-expression)
95509                     case 11 /* JsxText */:
95510                         return emitJsxText(node);
95511                     case 268 /* JsxOpeningElement */:
95512                     case 271 /* JsxOpeningFragment */:
95513                         return emitJsxOpeningElementOrFragment(node);
95514                     case 269 /* JsxClosingElement */:
95515                     case 272 /* JsxClosingFragment */:
95516                         return emitJsxClosingElementOrFragment(node);
95517                     case 273 /* JsxAttribute */:
95518                         return emitJsxAttribute(node);
95519                     case 274 /* JsxAttributes */:
95520                         return emitJsxAttributes(node);
95521                     case 275 /* JsxSpreadAttribute */:
95522                         return emitJsxSpreadAttribute(node);
95523                     case 276 /* JsxExpression */:
95524                         return emitJsxExpression(node);
95525                     // Clauses
95526                     case 277 /* CaseClause */:
95527                         return emitCaseClause(node);
95528                     case 278 /* DefaultClause */:
95529                         return emitDefaultClause(node);
95530                     case 279 /* HeritageClause */:
95531                         return emitHeritageClause(node);
95532                     case 280 /* CatchClause */:
95533                         return emitCatchClause(node);
95534                     // Property assignments
95535                     case 281 /* PropertyAssignment */:
95536                         return emitPropertyAssignment(node);
95537                     case 282 /* ShorthandPropertyAssignment */:
95538                         return emitShorthandPropertyAssignment(node);
95539                     case 283 /* SpreadAssignment */:
95540                         return emitSpreadAssignment(node);
95541                     // Enum
95542                     case 284 /* EnumMember */:
95543                         return emitEnumMember(node);
95544                     // JSDoc nodes (only used in codefixes currently)
95545                     case 317 /* JSDocParameterTag */:
95546                     case 323 /* JSDocPropertyTag */:
95547                         return emitJSDocPropertyLikeTag(node);
95548                     case 318 /* JSDocReturnTag */:
95549                     case 320 /* JSDocTypeTag */:
95550                     case 319 /* JSDocThisTag */:
95551                     case 316 /* JSDocEnumTag */:
95552                         return emitJSDocSimpleTypedTag(node);
95553                     case 308 /* JSDocImplementsTag */:
95554                     case 307 /* JSDocAugmentsTag */:
95555                         return emitJSDocHeritageTag(node);
95556                     case 321 /* JSDocTemplateTag */:
95557                         return emitJSDocTemplateTag(node);
95558                     case 322 /* JSDocTypedefTag */:
95559                         return emitJSDocTypedefTag(node);
95560                     case 315 /* JSDocCallbackTag */:
95561                         return emitJSDocCallbackTag(node);
95562                     case 305 /* JSDocSignature */:
95563                         return emitJSDocSignature(node);
95564                     case 304 /* JSDocTypeLiteral */:
95565                         return emitJSDocTypeLiteral(node);
95566                     case 310 /* JSDocClassTag */:
95567                     case 306 /* JSDocTag */:
95568                         return emitJSDocSimpleTag(node);
95569                     case 303 /* JSDocComment */:
95570                         return emitJSDoc(node);
95571                     // Transformation nodes (ignored)
95572                 }
95573                 if (ts.isExpression(node)) {
95574                     hint = 1 /* Expression */;
95575                     if (substituteNode !== ts.noEmitSubstitution) {
95576                         lastSubstitution = node = substituteNode(hint, node);
95577                     }
95578                 }
95579                 else if (ts.isToken(node)) {
95580                     return writeTokenNode(node, writePunctuation);
95581                 }
95582             }
95583             if (hint === 1 /* Expression */) {
95584                 switch (node.kind) {
95585                     // Literals
95586                     case 8 /* NumericLiteral */:
95587                     case 9 /* BigIntLiteral */:
95588                         return emitNumericOrBigIntLiteral(node);
95589                     case 10 /* StringLiteral */:
95590                     case 13 /* RegularExpressionLiteral */:
95591                     case 14 /* NoSubstitutionTemplateLiteral */:
95592                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95593                     // Identifiers
95594                     case 75 /* Identifier */:
95595                         return emitIdentifier(node);
95596                     // Reserved words
95597                     case 91 /* FalseKeyword */:
95598                     case 100 /* NullKeyword */:
95599                     case 102 /* SuperKeyword */:
95600                     case 106 /* TrueKeyword */:
95601                     case 104 /* ThisKeyword */:
95602                     case 96 /* ImportKeyword */:
95603                         writeTokenNode(node, writeKeyword);
95604                         return;
95605                     // Expressions
95606                     case 192 /* ArrayLiteralExpression */:
95607                         return emitArrayLiteralExpression(node);
95608                     case 193 /* ObjectLiteralExpression */:
95609                         return emitObjectLiteralExpression(node);
95610                     case 194 /* PropertyAccessExpression */:
95611                         return emitPropertyAccessExpression(node);
95612                     case 195 /* ElementAccessExpression */:
95613                         return emitElementAccessExpression(node);
95614                     case 196 /* CallExpression */:
95615                         return emitCallExpression(node);
95616                     case 197 /* NewExpression */:
95617                         return emitNewExpression(node);
95618                     case 198 /* TaggedTemplateExpression */:
95619                         return emitTaggedTemplateExpression(node);
95620                     case 199 /* TypeAssertionExpression */:
95621                         return emitTypeAssertionExpression(node);
95622                     case 200 /* ParenthesizedExpression */:
95623                         return emitParenthesizedExpression(node);
95624                     case 201 /* FunctionExpression */:
95625                         return emitFunctionExpression(node);
95626                     case 202 /* ArrowFunction */:
95627                         return emitArrowFunction(node);
95628                     case 203 /* DeleteExpression */:
95629                         return emitDeleteExpression(node);
95630                     case 204 /* TypeOfExpression */:
95631                         return emitTypeOfExpression(node);
95632                     case 205 /* VoidExpression */:
95633                         return emitVoidExpression(node);
95634                     case 206 /* AwaitExpression */:
95635                         return emitAwaitExpression(node);
95636                     case 207 /* PrefixUnaryExpression */:
95637                         return emitPrefixUnaryExpression(node);
95638                     case 208 /* PostfixUnaryExpression */:
95639                         return emitPostfixUnaryExpression(node);
95640                     case 209 /* BinaryExpression */:
95641                         return emitBinaryExpression(node);
95642                     case 210 /* ConditionalExpression */:
95643                         return emitConditionalExpression(node);
95644                     case 211 /* TemplateExpression */:
95645                         return emitTemplateExpression(node);
95646                     case 212 /* YieldExpression */:
95647                         return emitYieldExpression(node);
95648                     case 213 /* SpreadElement */:
95649                         return emitSpreadExpression(node);
95650                     case 214 /* ClassExpression */:
95651                         return emitClassExpression(node);
95652                     case 215 /* OmittedExpression */:
95653                         return;
95654                     case 217 /* AsExpression */:
95655                         return emitAsExpression(node);
95656                     case 218 /* NonNullExpression */:
95657                         return emitNonNullExpression(node);
95658                     case 219 /* MetaProperty */:
95659                         return emitMetaProperty(node);
95660                     // JSX
95661                     case 266 /* JsxElement */:
95662                         return emitJsxElement(node);
95663                     case 267 /* JsxSelfClosingElement */:
95664                         return emitJsxSelfClosingElement(node);
95665                     case 270 /* JsxFragment */:
95666                         return emitJsxFragment(node);
95667                     // Transformation nodes
95668                     case 326 /* PartiallyEmittedExpression */:
95669                         return emitPartiallyEmittedExpression(node);
95670                     case 327 /* CommaListExpression */:
95671                         return emitCommaList(node);
95672                 }
95673             }
95674         }
95675         function emitMappedTypeParameter(node) {
95676             emit(node.name);
95677             writeSpace();
95678             writeKeyword("in");
95679             writeSpace();
95680             emit(node.constraint);
95681         }
95682         function pipelineEmitWithSubstitution(hint, node) {
95683             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95684             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
95685             pipelinePhase(hint, lastSubstitution);
95686             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95687         }
95688         function getHelpersFromBundledSourceFiles(bundle) {
95689             var result;
95690             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
95691                 return undefined;
95692             }
95693             var bundledHelpers = ts.createMap();
95694             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
95695                 var sourceFile = _b[_a];
95696                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
95697                 var helpers = getSortedEmitHelpers(sourceFile);
95698                 if (!helpers)
95699                     continue;
95700                 for (var _c = 0, helpers_4 = helpers; _c < helpers_4.length; _c++) {
95701                     var helper = helpers_4[_c];
95702                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
95703                         bundledHelpers.set(helper.name, true);
95704                         (result || (result = [])).push(helper.name);
95705                     }
95706                 }
95707             }
95708             return result;
95709         }
95710         function emitHelpers(node) {
95711             var helpersEmitted = false;
95712             var bundle = node.kind === 291 /* Bundle */ ? node : undefined;
95713             if (bundle && moduleKind === ts.ModuleKind.None) {
95714                 return;
95715             }
95716             var numPrepends = bundle ? bundle.prepends.length : 0;
95717             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
95718             for (var i = 0; i < numNodes; i++) {
95719                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
95720                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
95721                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
95722                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
95723                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
95724                 if (helpers) {
95725                     for (var _a = 0, helpers_5 = helpers; _a < helpers_5.length; _a++) {
95726                         var helper = helpers_5[_a];
95727                         if (!helper.scoped) {
95728                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
95729                             // option is set, or if it can be imported and the importHelpers compiler
95730                             // option is set.
95731                             if (shouldSkip)
95732                                 continue;
95733                             // Skip the helper if it can be bundled but hasn't already been emitted and we
95734                             // are emitting a bundled module.
95735                             if (shouldBundle) {
95736                                 if (bundledHelpers.get(helper.name)) {
95737                                     continue;
95738                                 }
95739                                 bundledHelpers.set(helper.name, true);
95740                             }
95741                         }
95742                         else if (bundle) {
95743                             // Skip the helper if it is scoped and we are emitting bundled helpers
95744                             continue;
95745                         }
95746                         var pos = getTextPosWithWriteLine();
95747                         if (typeof helper.text === "string") {
95748                             writeLines(helper.text);
95749                         }
95750                         else {
95751                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
95752                         }
95753                         if (bundleFileInfo)
95754                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
95755                         helpersEmitted = true;
95756                     }
95757                 }
95758             }
95759             return helpersEmitted;
95760         }
95761         function getSortedEmitHelpers(node) {
95762             var helpers = ts.getEmitHelpers(node);
95763             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
95764         }
95765         //
95766         // Literals/Pseudo-literals
95767         //
95768         // SyntaxKind.NumericLiteral
95769         // SyntaxKind.BigIntLiteral
95770         function emitNumericOrBigIntLiteral(node) {
95771             emitLiteral(node, /*jsxAttributeEscape*/ false);
95772         }
95773         // SyntaxKind.StringLiteral
95774         // SyntaxKind.RegularExpressionLiteral
95775         // SyntaxKind.NoSubstitutionTemplateLiteral
95776         // SyntaxKind.TemplateHead
95777         // SyntaxKind.TemplateMiddle
95778         // SyntaxKind.TemplateTail
95779         function emitLiteral(node, jsxAttributeEscape) {
95780             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
95781             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
95782                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
95783                 writeLiteral(text);
95784             }
95785             else {
95786                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
95787                 writeStringLiteral(text);
95788             }
95789         }
95790         // SyntaxKind.UnparsedSource
95791         // SyntaxKind.UnparsedPrepend
95792         function emitUnparsedSourceOrPrepend(unparsed) {
95793             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
95794                 var text = _b[_a];
95795                 writeLine();
95796                 emit(text);
95797             }
95798         }
95799         // SyntaxKind.UnparsedPrologue
95800         // SyntaxKind.UnparsedText
95801         // SyntaxKind.UnparsedInternal
95802         // SyntaxKind.UnparsedSyntheticReference
95803         function writeUnparsedNode(unparsed) {
95804             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
95805         }
95806         // SyntaxKind.UnparsedText
95807         // SyntaxKind.UnparsedInternal
95808         function emitUnparsedTextLike(unparsed) {
95809             var pos = getTextPosWithWriteLine();
95810             writeUnparsedNode(unparsed);
95811             if (bundleFileInfo) {
95812                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 287 /* UnparsedText */ ?
95813                     "text" /* Text */ :
95814                     "internal" /* Internal */);
95815             }
95816         }
95817         // SyntaxKind.UnparsedSyntheticReference
95818         function emitUnparsedSyntheticReference(unparsed) {
95819             var pos = getTextPosWithWriteLine();
95820             writeUnparsedNode(unparsed);
95821             if (bundleFileInfo) {
95822                 var section = ts.clone(unparsed.section);
95823                 section.pos = pos;
95824                 section.end = writer.getTextPos();
95825                 bundleFileInfo.sections.push(section);
95826             }
95827         }
95828         //
95829         // Identifiers
95830         //
95831         function emitIdentifier(node) {
95832             var writeText = node.symbol ? writeSymbol : write;
95833             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95834             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
95835         }
95836         //
95837         // Names
95838         //
95839         function emitPrivateIdentifier(node) {
95840             var writeText = node.symbol ? writeSymbol : write;
95841             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95842         }
95843         function emitQualifiedName(node) {
95844             emitEntityName(node.left);
95845             writePunctuation(".");
95846             emit(node.right);
95847         }
95848         function emitEntityName(node) {
95849             if (node.kind === 75 /* Identifier */) {
95850                 emitExpression(node);
95851             }
95852             else {
95853                 emit(node);
95854             }
95855         }
95856         function emitComputedPropertyName(node) {
95857             writePunctuation("[");
95858             emitExpression(node.expression);
95859             writePunctuation("]");
95860         }
95861         //
95862         // Signature elements
95863         //
95864         function emitTypeParameter(node) {
95865             emit(node.name);
95866             if (node.constraint) {
95867                 writeSpace();
95868                 writeKeyword("extends");
95869                 writeSpace();
95870                 emit(node.constraint);
95871             }
95872             if (node.default) {
95873                 writeSpace();
95874                 writeOperator("=");
95875                 writeSpace();
95876                 emit(node.default);
95877             }
95878         }
95879         function emitParameter(node) {
95880             emitDecorators(node, node.decorators);
95881             emitModifiers(node, node.modifiers);
95882             emit(node.dotDotDotToken);
95883             emitNodeWithWriter(node.name, writeParameter);
95884             emit(node.questionToken);
95885             if (node.parent && node.parent.kind === 300 /* JSDocFunctionType */ && !node.name) {
95886                 emit(node.type);
95887             }
95888             else {
95889                 emitTypeAnnotation(node.type);
95890             }
95891             // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer.
95892             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node);
95893         }
95894         function emitDecorator(decorator) {
95895             writePunctuation("@");
95896             emitExpression(decorator.expression);
95897         }
95898         //
95899         // Type members
95900         //
95901         function emitPropertySignature(node) {
95902             emitDecorators(node, node.decorators);
95903             emitModifiers(node, node.modifiers);
95904             emitNodeWithWriter(node.name, writeProperty);
95905             emit(node.questionToken);
95906             emitTypeAnnotation(node.type);
95907             writeTrailingSemicolon();
95908         }
95909         function emitPropertyDeclaration(node) {
95910             emitDecorators(node, node.decorators);
95911             emitModifiers(node, node.modifiers);
95912             emit(node.name);
95913             emit(node.questionToken);
95914             emit(node.exclamationToken);
95915             emitTypeAnnotation(node.type);
95916             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
95917             writeTrailingSemicolon();
95918         }
95919         function emitMethodSignature(node) {
95920             pushNameGenerationScope(node);
95921             emitDecorators(node, node.decorators);
95922             emitModifiers(node, node.modifiers);
95923             emit(node.name);
95924             emit(node.questionToken);
95925             emitTypeParameters(node, node.typeParameters);
95926             emitParameters(node, node.parameters);
95927             emitTypeAnnotation(node.type);
95928             writeTrailingSemicolon();
95929             popNameGenerationScope(node);
95930         }
95931         function emitMethodDeclaration(node) {
95932             emitDecorators(node, node.decorators);
95933             emitModifiers(node, node.modifiers);
95934             emit(node.asteriskToken);
95935             emit(node.name);
95936             emit(node.questionToken);
95937             emitSignatureAndBody(node, emitSignatureHead);
95938         }
95939         function emitConstructor(node) {
95940             emitModifiers(node, node.modifiers);
95941             writeKeyword("constructor");
95942             emitSignatureAndBody(node, emitSignatureHead);
95943         }
95944         function emitAccessorDeclaration(node) {
95945             emitDecorators(node, node.decorators);
95946             emitModifiers(node, node.modifiers);
95947             writeKeyword(node.kind === 163 /* GetAccessor */ ? "get" : "set");
95948             writeSpace();
95949             emit(node.name);
95950             emitSignatureAndBody(node, emitSignatureHead);
95951         }
95952         function emitCallSignature(node) {
95953             pushNameGenerationScope(node);
95954             emitDecorators(node, node.decorators);
95955             emitModifiers(node, node.modifiers);
95956             emitTypeParameters(node, node.typeParameters);
95957             emitParameters(node, node.parameters);
95958             emitTypeAnnotation(node.type);
95959             writeTrailingSemicolon();
95960             popNameGenerationScope(node);
95961         }
95962         function emitConstructSignature(node) {
95963             pushNameGenerationScope(node);
95964             emitDecorators(node, node.decorators);
95965             emitModifiers(node, node.modifiers);
95966             writeKeyword("new");
95967             writeSpace();
95968             emitTypeParameters(node, node.typeParameters);
95969             emitParameters(node, node.parameters);
95970             emitTypeAnnotation(node.type);
95971             writeTrailingSemicolon();
95972             popNameGenerationScope(node);
95973         }
95974         function emitIndexSignature(node) {
95975             emitDecorators(node, node.decorators);
95976             emitModifiers(node, node.modifiers);
95977             emitParametersForIndexSignature(node, node.parameters);
95978             emitTypeAnnotation(node.type);
95979             writeTrailingSemicolon();
95980         }
95981         function emitSemicolonClassElement() {
95982             writeTrailingSemicolon();
95983         }
95984         //
95985         // Types
95986         //
95987         function emitTypePredicate(node) {
95988             if (node.assertsModifier) {
95989                 emit(node.assertsModifier);
95990                 writeSpace();
95991             }
95992             emit(node.parameterName);
95993             if (node.type) {
95994                 writeSpace();
95995                 writeKeyword("is");
95996                 writeSpace();
95997                 emit(node.type);
95998             }
95999         }
96000         function emitTypeReference(node) {
96001             emit(node.typeName);
96002             emitTypeArguments(node, node.typeArguments);
96003         }
96004         function emitFunctionType(node) {
96005             pushNameGenerationScope(node);
96006             emitTypeParameters(node, node.typeParameters);
96007             emitParametersForArrow(node, node.parameters);
96008             writeSpace();
96009             writePunctuation("=>");
96010             writeSpace();
96011             emit(node.type);
96012             popNameGenerationScope(node);
96013         }
96014         function emitJSDocFunctionType(node) {
96015             writeKeyword("function");
96016             emitParameters(node, node.parameters);
96017             writePunctuation(":");
96018             emit(node.type);
96019         }
96020         function emitJSDocNullableType(node) {
96021             writePunctuation("?");
96022             emit(node.type);
96023         }
96024         function emitJSDocNonNullableType(node) {
96025             writePunctuation("!");
96026             emit(node.type);
96027         }
96028         function emitJSDocOptionalType(node) {
96029             emit(node.type);
96030             writePunctuation("=");
96031         }
96032         function emitConstructorType(node) {
96033             pushNameGenerationScope(node);
96034             writeKeyword("new");
96035             writeSpace();
96036             emitTypeParameters(node, node.typeParameters);
96037             emitParameters(node, node.parameters);
96038             writeSpace();
96039             writePunctuation("=>");
96040             writeSpace();
96041             emit(node.type);
96042             popNameGenerationScope(node);
96043         }
96044         function emitTypeQuery(node) {
96045             writeKeyword("typeof");
96046             writeSpace();
96047             emit(node.exprName);
96048         }
96049         function emitTypeLiteral(node) {
96050             writePunctuation("{");
96051             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
96052             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
96053             writePunctuation("}");
96054         }
96055         function emitArrayType(node) {
96056             emit(node.elementType);
96057             writePunctuation("[");
96058             writePunctuation("]");
96059         }
96060         function emitRestOrJSDocVariadicType(node) {
96061             writePunctuation("...");
96062             emit(node.type);
96063         }
96064         function emitTupleType(node) {
96065             writePunctuation("[");
96066             emitList(node, node.elementTypes, 528 /* TupleTypeElements */);
96067             writePunctuation("]");
96068         }
96069         function emitOptionalType(node) {
96070             emit(node.type);
96071             writePunctuation("?");
96072         }
96073         function emitUnionType(node) {
96074             emitList(node, node.types, 516 /* UnionTypeConstituents */);
96075         }
96076         function emitIntersectionType(node) {
96077             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
96078         }
96079         function emitConditionalType(node) {
96080             emit(node.checkType);
96081             writeSpace();
96082             writeKeyword("extends");
96083             writeSpace();
96084             emit(node.extendsType);
96085             writeSpace();
96086             writePunctuation("?");
96087             writeSpace();
96088             emit(node.trueType);
96089             writeSpace();
96090             writePunctuation(":");
96091             writeSpace();
96092             emit(node.falseType);
96093         }
96094         function emitInferType(node) {
96095             writeKeyword("infer");
96096             writeSpace();
96097             emit(node.typeParameter);
96098         }
96099         function emitParenthesizedType(node) {
96100             writePunctuation("(");
96101             emit(node.type);
96102             writePunctuation(")");
96103         }
96104         function emitThisType() {
96105             writeKeyword("this");
96106         }
96107         function emitTypeOperator(node) {
96108             writeTokenText(node.operator, writeKeyword);
96109             writeSpace();
96110             emit(node.type);
96111         }
96112         function emitIndexedAccessType(node) {
96113             emit(node.objectType);
96114             writePunctuation("[");
96115             emit(node.indexType);
96116             writePunctuation("]");
96117         }
96118         function emitMappedType(node) {
96119             var emitFlags = ts.getEmitFlags(node);
96120             writePunctuation("{");
96121             if (emitFlags & 1 /* SingleLine */) {
96122                 writeSpace();
96123             }
96124             else {
96125                 writeLine();
96126                 increaseIndent();
96127             }
96128             if (node.readonlyToken) {
96129                 emit(node.readonlyToken);
96130                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
96131                     writeKeyword("readonly");
96132                 }
96133                 writeSpace();
96134             }
96135             writePunctuation("[");
96136             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
96137             writePunctuation("]");
96138             if (node.questionToken) {
96139                 emit(node.questionToken);
96140                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
96141                     writePunctuation("?");
96142                 }
96143             }
96144             writePunctuation(":");
96145             writeSpace();
96146             emit(node.type);
96147             writeTrailingSemicolon();
96148             if (emitFlags & 1 /* SingleLine */) {
96149                 writeSpace();
96150             }
96151             else {
96152                 writeLine();
96153                 decreaseIndent();
96154             }
96155             writePunctuation("}");
96156         }
96157         function emitLiteralType(node) {
96158             emitExpression(node.literal);
96159         }
96160         function emitImportTypeNode(node) {
96161             if (node.isTypeOf) {
96162                 writeKeyword("typeof");
96163                 writeSpace();
96164             }
96165             writeKeyword("import");
96166             writePunctuation("(");
96167             emit(node.argument);
96168             writePunctuation(")");
96169             if (node.qualifier) {
96170                 writePunctuation(".");
96171                 emit(node.qualifier);
96172             }
96173             emitTypeArguments(node, node.typeArguments);
96174         }
96175         //
96176         // Binding patterns
96177         //
96178         function emitObjectBindingPattern(node) {
96179             writePunctuation("{");
96180             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
96181             writePunctuation("}");
96182         }
96183         function emitArrayBindingPattern(node) {
96184             writePunctuation("[");
96185             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
96186             writePunctuation("]");
96187         }
96188         function emitBindingElement(node) {
96189             emit(node.dotDotDotToken);
96190             if (node.propertyName) {
96191                 emit(node.propertyName);
96192                 writePunctuation(":");
96193                 writeSpace();
96194             }
96195             emit(node.name);
96196             emitInitializer(node.initializer, node.name.end, node);
96197         }
96198         //
96199         // Expressions
96200         //
96201         function emitArrayLiteralExpression(node) {
96202             var elements = node.elements;
96203             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96204             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
96205         }
96206         function emitObjectLiteralExpression(node) {
96207             ts.forEach(node.properties, generateMemberNames);
96208             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96209             if (indentedFlag) {
96210                 increaseIndent();
96211             }
96212             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96213             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
96214             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
96215             if (indentedFlag) {
96216                 decreaseIndent();
96217             }
96218         }
96219         function emitPropertyAccessExpression(node) {
96220             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
96221             var token = node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos);
96222             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
96223             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
96224             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
96225             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
96226                 mayNeedDotDotForPropertyAccess(expression) &&
96227                 !writer.hasTrailingComment() &&
96228                 !writer.hasTrailingWhitespace();
96229             if (shouldEmitDotDot) {
96230                 writePunctuation(".");
96231             }
96232             if (node.questionDotToken) {
96233                 emit(token);
96234             }
96235             else {
96236                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
96237             }
96238             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
96239             emit(node.name);
96240             decreaseIndentIf(linesBeforeDot, linesAfterDot);
96241         }
96242         // 1..toString is a valid property access, emit a dot after the literal
96243         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
96244         function mayNeedDotDotForPropertyAccess(expression) {
96245             expression = ts.skipPartiallyEmittedExpressions(expression);
96246             if (ts.isNumericLiteral(expression)) {
96247                 // check if numeric literal is a decimal literal that was originally written with a dot
96248                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
96249                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
96250                 // if the expression doesn't have any comments that will be emitted.
96251                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
96252             }
96253             else if (ts.isAccessExpression(expression)) {
96254                 // check if constant enum value is integer
96255                 var constantValue = ts.getConstantValue(expression);
96256                 // isFinite handles cases when constantValue is undefined
96257                 return typeof constantValue === "number" && isFinite(constantValue)
96258                     && Math.floor(constantValue) === constantValue;
96259             }
96260         }
96261         function emitElementAccessExpression(node) {
96262             emitExpression(node.expression);
96263             emit(node.questionDotToken);
96264             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
96265             emitExpression(node.argumentExpression);
96266             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
96267         }
96268         function emitCallExpression(node) {
96269             emitExpression(node.expression);
96270             emit(node.questionDotToken);
96271             emitTypeArguments(node, node.typeArguments);
96272             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
96273         }
96274         function emitNewExpression(node) {
96275             emitTokenWithComment(99 /* NewKeyword */, node.pos, writeKeyword, node);
96276             writeSpace();
96277             emitExpression(node.expression);
96278             emitTypeArguments(node, node.typeArguments);
96279             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
96280         }
96281         function emitTaggedTemplateExpression(node) {
96282             emitExpression(node.tag);
96283             emitTypeArguments(node, node.typeArguments);
96284             writeSpace();
96285             emitExpression(node.template);
96286         }
96287         function emitTypeAssertionExpression(node) {
96288             writePunctuation("<");
96289             emit(node.type);
96290             writePunctuation(">");
96291             emitExpression(node.expression);
96292         }
96293         function emitParenthesizedExpression(node) {
96294             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
96295             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
96296             emitExpression(node.expression);
96297             writeLineSeparatorsAfter(node.expression, node);
96298             decreaseIndentIf(indented);
96299             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
96300         }
96301         function emitFunctionExpression(node) {
96302             generateNameIfNeeded(node.name);
96303             emitFunctionDeclarationOrExpression(node);
96304         }
96305         function emitArrowFunction(node) {
96306             emitDecorators(node, node.decorators);
96307             emitModifiers(node, node.modifiers);
96308             emitSignatureAndBody(node, emitArrowFunctionHead);
96309         }
96310         function emitArrowFunctionHead(node) {
96311             emitTypeParameters(node, node.typeParameters);
96312             emitParametersForArrow(node, node.parameters);
96313             emitTypeAnnotation(node.type);
96314             writeSpace();
96315             emit(node.equalsGreaterThanToken);
96316         }
96317         function emitDeleteExpression(node) {
96318             emitTokenWithComment(85 /* DeleteKeyword */, node.pos, writeKeyword, node);
96319             writeSpace();
96320             emitExpression(node.expression);
96321         }
96322         function emitTypeOfExpression(node) {
96323             emitTokenWithComment(108 /* TypeOfKeyword */, node.pos, writeKeyword, node);
96324             writeSpace();
96325             emitExpression(node.expression);
96326         }
96327         function emitVoidExpression(node) {
96328             emitTokenWithComment(110 /* VoidKeyword */, node.pos, writeKeyword, node);
96329             writeSpace();
96330             emitExpression(node.expression);
96331         }
96332         function emitAwaitExpression(node) {
96333             emitTokenWithComment(127 /* AwaitKeyword */, node.pos, writeKeyword, node);
96334             writeSpace();
96335             emitExpression(node.expression);
96336         }
96337         function emitPrefixUnaryExpression(node) {
96338             writeTokenText(node.operator, writeOperator);
96339             if (shouldEmitWhitespaceBeforeOperand(node)) {
96340                 writeSpace();
96341             }
96342             emitExpression(node.operand);
96343         }
96344         function shouldEmitWhitespaceBeforeOperand(node) {
96345             // In some cases, we need to emit a space between the operator and the operand. One obvious case
96346             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
96347             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
96348             // are just for clarity of exposition, and not part of the source code):
96349             //
96350             //  (+(+1))
96351             //  (+(++1))
96352             //
96353             // We need to emit a space in both cases. In the first case, the absence of a space will make
96354             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
96355             // expression a prefix increment whose operand is a plus expression - (++(+x))
96356             // The same is true of minus of course.
96357             var operand = node.operand;
96358             return operand.kind === 207 /* PrefixUnaryExpression */
96359                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
96360                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
96361         }
96362         function emitPostfixUnaryExpression(node) {
96363             emitExpression(node.operand);
96364             writeTokenText(node.operator, writeOperator);
96365         }
96366         var EmitBinaryExpressionState;
96367         (function (EmitBinaryExpressionState) {
96368             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
96369             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
96370             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
96371         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
96372         /**
96373          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
96374          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
96375          * not require notification/substitution/comment/sourcemap decorations.
96376          */
96377         function emitBinaryExpression(node) {
96378             var nodeStack = [node];
96379             var stateStack = [0 /* EmitLeft */];
96380             var stackIndex = 0;
96381             while (stackIndex >= 0) {
96382                 node = nodeStack[stackIndex];
96383                 switch (stateStack[stackIndex]) {
96384                     case 0 /* EmitLeft */: {
96385                         maybePipelineEmitExpression(node.left);
96386                         break;
96387                     }
96388                     case 1 /* EmitRight */: {
96389                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
96390                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96391                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96392                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
96393                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
96394                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 97 /* InKeyword */ ? writeKeyword : writeOperator);
96395                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
96396                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
96397                         maybePipelineEmitExpression(node.right);
96398                         break;
96399                     }
96400                     case 2 /* FinishEmit */: {
96401                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96402                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96403                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
96404                         stackIndex--;
96405                         break;
96406                     }
96407                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
96408                 }
96409             }
96410             function maybePipelineEmitExpression(next) {
96411                 // Advance the state of this unit of work,
96412                 stateStack[stackIndex]++;
96413                 // Then actually do the work of emitting the node `next` returned by the prior state
96414                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
96415                 // binary expression handling, where possible, to the contained work queue
96416                 // #region trampolinePipelineEmit
96417                 var savedLastNode = lastNode;
96418                 var savedLastSubstitution = lastSubstitution;
96419                 lastNode = next;
96420                 lastSubstitution = undefined;
96421                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
96422                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
96423                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
96424                     // skip all the intermediate indirection and push the expression directly onto the work stack
96425                     stackIndex++;
96426                     stateStack[stackIndex] = 0 /* EmitLeft */;
96427                     nodeStack[stackIndex] = next;
96428                 }
96429                 else {
96430                     pipelinePhase(1 /* Expression */, next);
96431                 }
96432                 ts.Debug.assert(lastNode === next);
96433                 lastNode = savedLastNode;
96434                 lastSubstitution = savedLastSubstitution;
96435                 // #endregion trampolinePipelineEmit
96436             }
96437         }
96438         function emitConditionalExpression(node) {
96439             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
96440             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
96441             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
96442             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
96443             emitExpression(node.condition);
96444             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
96445             emit(node.questionToken);
96446             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
96447             emitExpression(node.whenTrue);
96448             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
96449             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
96450             emit(node.colonToken);
96451             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
96452             emitExpression(node.whenFalse);
96453             decreaseIndentIf(linesBeforeColon, linesAfterColon);
96454         }
96455         function emitTemplateExpression(node) {
96456             emit(node.head);
96457             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
96458         }
96459         function emitYieldExpression(node) {
96460             emitTokenWithComment(121 /* YieldKeyword */, node.pos, writeKeyword, node);
96461             emit(node.asteriskToken);
96462             emitExpressionWithLeadingSpace(node.expression);
96463         }
96464         function emitSpreadExpression(node) {
96465             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
96466             emitExpression(node.expression);
96467         }
96468         function emitClassExpression(node) {
96469             generateNameIfNeeded(node.name);
96470             emitClassDeclarationOrExpression(node);
96471         }
96472         function emitExpressionWithTypeArguments(node) {
96473             emitExpression(node.expression);
96474             emitTypeArguments(node, node.typeArguments);
96475         }
96476         function emitAsExpression(node) {
96477             emitExpression(node.expression);
96478             if (node.type) {
96479                 writeSpace();
96480                 writeKeyword("as");
96481                 writeSpace();
96482                 emit(node.type);
96483             }
96484         }
96485         function emitNonNullExpression(node) {
96486             emitExpression(node.expression);
96487             writeOperator("!");
96488         }
96489         function emitMetaProperty(node) {
96490             writeToken(node.keywordToken, node.pos, writePunctuation);
96491             writePunctuation(".");
96492             emit(node.name);
96493         }
96494         //
96495         // Misc
96496         //
96497         function emitTemplateSpan(node) {
96498             emitExpression(node.expression);
96499             emit(node.literal);
96500         }
96501         //
96502         // Statements
96503         //
96504         function emitBlock(node) {
96505             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
96506         }
96507         function emitBlockStatements(node, forceSingleLine) {
96508             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
96509             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
96510             emitList(node, node.statements, format);
96511             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
96512         }
96513         function emitVariableStatement(node) {
96514             emitModifiers(node, node.modifiers);
96515             emit(node.declarationList);
96516             writeTrailingSemicolon();
96517         }
96518         function emitEmptyStatement(isEmbeddedStatement) {
96519             // While most trailing semicolons are possibly insignificant, an embedded "empty"
96520             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
96521             if (isEmbeddedStatement) {
96522                 writePunctuation(";");
96523             }
96524             else {
96525                 writeTrailingSemicolon();
96526             }
96527         }
96528         function emitExpressionStatement(node) {
96529             emitExpression(node.expression);
96530             // Emit semicolon in non json files
96531             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
96532             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
96533                 writeTrailingSemicolon();
96534             }
96535         }
96536         function emitIfStatement(node) {
96537             var openParenPos = emitTokenWithComment(95 /* IfKeyword */, node.pos, writeKeyword, node);
96538             writeSpace();
96539             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96540             emitExpression(node.expression);
96541             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96542             emitEmbeddedStatement(node, node.thenStatement);
96543             if (node.elseStatement) {
96544                 writeLineOrSpace(node);
96545                 emitTokenWithComment(87 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
96546                 if (node.elseStatement.kind === 227 /* IfStatement */) {
96547                     writeSpace();
96548                     emit(node.elseStatement);
96549                 }
96550                 else {
96551                     emitEmbeddedStatement(node, node.elseStatement);
96552                 }
96553             }
96554         }
96555         function emitWhileClause(node, startPos) {
96556             var openParenPos = emitTokenWithComment(111 /* WhileKeyword */, startPos, writeKeyword, node);
96557             writeSpace();
96558             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96559             emitExpression(node.expression);
96560             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96561         }
96562         function emitDoStatement(node) {
96563             emitTokenWithComment(86 /* DoKeyword */, node.pos, writeKeyword, node);
96564             emitEmbeddedStatement(node, node.statement);
96565             if (ts.isBlock(node.statement)) {
96566                 writeSpace();
96567             }
96568             else {
96569                 writeLineOrSpace(node);
96570             }
96571             emitWhileClause(node, node.statement.end);
96572             writeTrailingSemicolon();
96573         }
96574         function emitWhileStatement(node) {
96575             emitWhileClause(node, node.pos);
96576             emitEmbeddedStatement(node, node.statement);
96577         }
96578         function emitForStatement(node) {
96579             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96580             writeSpace();
96581             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
96582             emitForBinding(node.initializer);
96583             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
96584             emitExpressionWithLeadingSpace(node.condition);
96585             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
96586             emitExpressionWithLeadingSpace(node.incrementor);
96587             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
96588             emitEmbeddedStatement(node, node.statement);
96589         }
96590         function emitForInStatement(node) {
96591             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96592             writeSpace();
96593             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96594             emitForBinding(node.initializer);
96595             writeSpace();
96596             emitTokenWithComment(97 /* InKeyword */, node.initializer.end, writeKeyword, node);
96597             writeSpace();
96598             emitExpression(node.expression);
96599             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96600             emitEmbeddedStatement(node, node.statement);
96601         }
96602         function emitForOfStatement(node) {
96603             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96604             writeSpace();
96605             emitWithTrailingSpace(node.awaitModifier);
96606             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96607             emitForBinding(node.initializer);
96608             writeSpace();
96609             emitTokenWithComment(152 /* OfKeyword */, node.initializer.end, writeKeyword, node);
96610             writeSpace();
96611             emitExpression(node.expression);
96612             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96613             emitEmbeddedStatement(node, node.statement);
96614         }
96615         function emitForBinding(node) {
96616             if (node !== undefined) {
96617                 if (node.kind === 243 /* VariableDeclarationList */) {
96618                     emit(node);
96619                 }
96620                 else {
96621                     emitExpression(node);
96622                 }
96623             }
96624         }
96625         function emitContinueStatement(node) {
96626             emitTokenWithComment(82 /* ContinueKeyword */, node.pos, writeKeyword, node);
96627             emitWithLeadingSpace(node.label);
96628             writeTrailingSemicolon();
96629         }
96630         function emitBreakStatement(node) {
96631             emitTokenWithComment(77 /* BreakKeyword */, node.pos, writeKeyword, node);
96632             emitWithLeadingSpace(node.label);
96633             writeTrailingSemicolon();
96634         }
96635         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
96636             var node = ts.getParseTreeNode(contextNode);
96637             var isSimilarNode = node && node.kind === contextNode.kind;
96638             var startPos = pos;
96639             if (isSimilarNode && currentSourceFile) {
96640                 pos = ts.skipTrivia(currentSourceFile.text, pos);
96641             }
96642             if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
96643                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
96644                 if (needsIndent) {
96645                     increaseIndent();
96646                 }
96647                 emitLeadingCommentsOfPosition(startPos);
96648                 if (needsIndent) {
96649                     decreaseIndent();
96650                 }
96651             }
96652             pos = writeTokenText(token, writer, pos);
96653             if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
96654                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
96655             }
96656             return pos;
96657         }
96658         function emitReturnStatement(node) {
96659             emitTokenWithComment(101 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
96660             emitExpressionWithLeadingSpace(node.expression);
96661             writeTrailingSemicolon();
96662         }
96663         function emitWithStatement(node) {
96664             var openParenPos = emitTokenWithComment(112 /* WithKeyword */, node.pos, writeKeyword, node);
96665             writeSpace();
96666             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96667             emitExpression(node.expression);
96668             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96669             emitEmbeddedStatement(node, node.statement);
96670         }
96671         function emitSwitchStatement(node) {
96672             var openParenPos = emitTokenWithComment(103 /* SwitchKeyword */, node.pos, writeKeyword, node);
96673             writeSpace();
96674             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96675             emitExpression(node.expression);
96676             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96677             writeSpace();
96678             emit(node.caseBlock);
96679         }
96680         function emitLabeledStatement(node) {
96681             emit(node.label);
96682             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
96683             writeSpace();
96684             emit(node.statement);
96685         }
96686         function emitThrowStatement(node) {
96687             emitTokenWithComment(105 /* ThrowKeyword */, node.pos, writeKeyword, node);
96688             emitExpressionWithLeadingSpace(node.expression);
96689             writeTrailingSemicolon();
96690         }
96691         function emitTryStatement(node) {
96692             emitTokenWithComment(107 /* TryKeyword */, node.pos, writeKeyword, node);
96693             writeSpace();
96694             emit(node.tryBlock);
96695             if (node.catchClause) {
96696                 writeLineOrSpace(node);
96697                 emit(node.catchClause);
96698             }
96699             if (node.finallyBlock) {
96700                 writeLineOrSpace(node);
96701                 emitTokenWithComment(92 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
96702                 writeSpace();
96703                 emit(node.finallyBlock);
96704             }
96705         }
96706         function emitDebuggerStatement(node) {
96707             writeToken(83 /* DebuggerKeyword */, node.pos, writeKeyword);
96708             writeTrailingSemicolon();
96709         }
96710         //
96711         // Declarations
96712         //
96713         function emitVariableDeclaration(node) {
96714             emit(node.name);
96715             emit(node.exclamationToken);
96716             emitTypeAnnotation(node.type);
96717             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
96718         }
96719         function emitVariableDeclarationList(node) {
96720             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
96721             writeSpace();
96722             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
96723         }
96724         function emitFunctionDeclaration(node) {
96725             emitFunctionDeclarationOrExpression(node);
96726         }
96727         function emitFunctionDeclarationOrExpression(node) {
96728             emitDecorators(node, node.decorators);
96729             emitModifiers(node, node.modifiers);
96730             writeKeyword("function");
96731             emit(node.asteriskToken);
96732             writeSpace();
96733             emitIdentifierName(node.name);
96734             emitSignatureAndBody(node, emitSignatureHead);
96735         }
96736         function emitBlockCallback(_hint, body) {
96737             emitBlockFunctionBody(body);
96738         }
96739         function emitSignatureAndBody(node, emitSignatureHead) {
96740             var body = node.body;
96741             if (body) {
96742                 if (ts.isBlock(body)) {
96743                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96744                     if (indentedFlag) {
96745                         increaseIndent();
96746                     }
96747                     pushNameGenerationScope(node);
96748                     ts.forEach(node.parameters, generateNames);
96749                     generateNames(node.body);
96750                     emitSignatureHead(node);
96751                     if (onEmitNode) {
96752                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
96753                     }
96754                     else {
96755                         emitBlockFunctionBody(body);
96756                     }
96757                     popNameGenerationScope(node);
96758                     if (indentedFlag) {
96759                         decreaseIndent();
96760                     }
96761                 }
96762                 else {
96763                     emitSignatureHead(node);
96764                     writeSpace();
96765                     emitExpression(body);
96766                 }
96767             }
96768             else {
96769                 emitSignatureHead(node);
96770                 writeTrailingSemicolon();
96771             }
96772         }
96773         function emitSignatureHead(node) {
96774             emitTypeParameters(node, node.typeParameters);
96775             emitParameters(node, node.parameters);
96776             emitTypeAnnotation(node.type);
96777         }
96778         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
96779             // We must emit a function body as a single-line body in the following case:
96780             // * The body has NodeEmitFlags.SingleLine specified.
96781             // We must emit a function body as a multi-line body in the following cases:
96782             // * The body is explicitly marked as multi-line.
96783             // * A non-synthesized body's start and end position are on different lines.
96784             // * Any statement in the body starts on a new line.
96785             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
96786                 return true;
96787             }
96788             if (body.multiLine) {
96789                 return false;
96790             }
96791             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
96792                 return false;
96793             }
96794             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
96795                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
96796                 return false;
96797             }
96798             var previousStatement;
96799             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
96800                 var statement = _b[_a];
96801                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
96802                     return false;
96803                 }
96804                 previousStatement = statement;
96805             }
96806             return true;
96807         }
96808         function emitBlockFunctionBody(body) {
96809             writeSpace();
96810             writePunctuation("{");
96811             increaseIndent();
96812             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
96813                 ? emitBlockFunctionBodyOnSingleLine
96814                 : emitBlockFunctionBodyWorker;
96815             if (emitBodyWithDetachedComments) {
96816                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
96817             }
96818             else {
96819                 emitBlockFunctionBody(body);
96820             }
96821             decreaseIndent();
96822             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
96823         }
96824         function emitBlockFunctionBodyOnSingleLine(body) {
96825             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
96826         }
96827         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
96828             // Emit all the prologue directives (like "use strict").
96829             var statementOffset = emitPrologueDirectives(body.statements);
96830             var pos = writer.getTextPos();
96831             emitHelpers(body);
96832             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
96833                 decreaseIndent();
96834                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
96835                 increaseIndent();
96836             }
96837             else {
96838                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
96839             }
96840         }
96841         function emitClassDeclaration(node) {
96842             emitClassDeclarationOrExpression(node);
96843         }
96844         function emitClassDeclarationOrExpression(node) {
96845             ts.forEach(node.members, generateMemberNames);
96846             emitDecorators(node, node.decorators);
96847             emitModifiers(node, node.modifiers);
96848             writeKeyword("class");
96849             if (node.name) {
96850                 writeSpace();
96851                 emitIdentifierName(node.name);
96852             }
96853             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96854             if (indentedFlag) {
96855                 increaseIndent();
96856             }
96857             emitTypeParameters(node, node.typeParameters);
96858             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
96859             writeSpace();
96860             writePunctuation("{");
96861             emitList(node, node.members, 129 /* ClassMembers */);
96862             writePunctuation("}");
96863             if (indentedFlag) {
96864                 decreaseIndent();
96865             }
96866         }
96867         function emitInterfaceDeclaration(node) {
96868             emitDecorators(node, node.decorators);
96869             emitModifiers(node, node.modifiers);
96870             writeKeyword("interface");
96871             writeSpace();
96872             emit(node.name);
96873             emitTypeParameters(node, node.typeParameters);
96874             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
96875             writeSpace();
96876             writePunctuation("{");
96877             emitList(node, node.members, 129 /* InterfaceMembers */);
96878             writePunctuation("}");
96879         }
96880         function emitTypeAliasDeclaration(node) {
96881             emitDecorators(node, node.decorators);
96882             emitModifiers(node, node.modifiers);
96883             writeKeyword("type");
96884             writeSpace();
96885             emit(node.name);
96886             emitTypeParameters(node, node.typeParameters);
96887             writeSpace();
96888             writePunctuation("=");
96889             writeSpace();
96890             emit(node.type);
96891             writeTrailingSemicolon();
96892         }
96893         function emitEnumDeclaration(node) {
96894             emitModifiers(node, node.modifiers);
96895             writeKeyword("enum");
96896             writeSpace();
96897             emit(node.name);
96898             writeSpace();
96899             writePunctuation("{");
96900             emitList(node, node.members, 145 /* EnumMembers */);
96901             writePunctuation("}");
96902         }
96903         function emitModuleDeclaration(node) {
96904             emitModifiers(node, node.modifiers);
96905             if (~node.flags & 1024 /* GlobalAugmentation */) {
96906                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
96907                 writeSpace();
96908             }
96909             emit(node.name);
96910             var body = node.body;
96911             if (!body)
96912                 return writeTrailingSemicolon();
96913             while (body.kind === 249 /* ModuleDeclaration */) {
96914                 writePunctuation(".");
96915                 emit(body.name);
96916                 body = body.body;
96917             }
96918             writeSpace();
96919             emit(body);
96920         }
96921         function emitModuleBlock(node) {
96922             pushNameGenerationScope(node);
96923             ts.forEach(node.statements, generateNames);
96924             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
96925             popNameGenerationScope(node);
96926         }
96927         function emitCaseBlock(node) {
96928             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
96929             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
96930             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
96931         }
96932         function emitImportEqualsDeclaration(node) {
96933             emitModifiers(node, node.modifiers);
96934             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96935             writeSpace();
96936             emit(node.name);
96937             writeSpace();
96938             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
96939             writeSpace();
96940             emitModuleReference(node.moduleReference);
96941             writeTrailingSemicolon();
96942         }
96943         function emitModuleReference(node) {
96944             if (node.kind === 75 /* Identifier */) {
96945                 emitExpression(node);
96946             }
96947             else {
96948                 emit(node);
96949             }
96950         }
96951         function emitImportDeclaration(node) {
96952             emitModifiers(node, node.modifiers);
96953             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96954             writeSpace();
96955             if (node.importClause) {
96956                 emit(node.importClause);
96957                 writeSpace();
96958                 emitTokenWithComment(149 /* FromKeyword */, node.importClause.end, writeKeyword, node);
96959                 writeSpace();
96960             }
96961             emitExpression(node.moduleSpecifier);
96962             writeTrailingSemicolon();
96963         }
96964         function emitImportClause(node) {
96965             if (node.isTypeOnly) {
96966                 emitTokenWithComment(145 /* TypeKeyword */, node.pos, writeKeyword, node);
96967                 writeSpace();
96968             }
96969             emit(node.name);
96970             if (node.name && node.namedBindings) {
96971                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
96972                 writeSpace();
96973             }
96974             emit(node.namedBindings);
96975         }
96976         function emitNamespaceImport(node) {
96977             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
96978             writeSpace();
96979             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
96980             writeSpace();
96981             emit(node.name);
96982         }
96983         function emitNamedImports(node) {
96984             emitNamedImportsOrExports(node);
96985         }
96986         function emitImportSpecifier(node) {
96987             emitImportOrExportSpecifier(node);
96988         }
96989         function emitExportAssignment(node) {
96990             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96991             writeSpace();
96992             if (node.isExportEquals) {
96993                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
96994             }
96995             else {
96996                 emitTokenWithComment(84 /* DefaultKeyword */, nextPos, writeKeyword, node);
96997             }
96998             writeSpace();
96999             emitExpression(node.expression);
97000             writeTrailingSemicolon();
97001         }
97002         function emitExportDeclaration(node) {
97003             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97004             writeSpace();
97005             if (node.isTypeOnly) {
97006                 nextPos = emitTokenWithComment(145 /* TypeKeyword */, nextPos, writeKeyword, node);
97007                 writeSpace();
97008             }
97009             if (node.exportClause) {
97010                 emit(node.exportClause);
97011             }
97012             else {
97013                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
97014             }
97015             if (node.moduleSpecifier) {
97016                 writeSpace();
97017                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
97018                 emitTokenWithComment(149 /* FromKeyword */, fromPos, writeKeyword, node);
97019                 writeSpace();
97020                 emitExpression(node.moduleSpecifier);
97021             }
97022             writeTrailingSemicolon();
97023         }
97024         function emitNamespaceExportDeclaration(node) {
97025             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97026             writeSpace();
97027             nextPos = emitTokenWithComment(123 /* AsKeyword */, nextPos, writeKeyword, node);
97028             writeSpace();
97029             nextPos = emitTokenWithComment(136 /* NamespaceKeyword */, nextPos, writeKeyword, node);
97030             writeSpace();
97031             emit(node.name);
97032             writeTrailingSemicolon();
97033         }
97034         function emitNamespaceExport(node) {
97035             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
97036             writeSpace();
97037             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
97038             writeSpace();
97039             emit(node.name);
97040         }
97041         function emitNamedExports(node) {
97042             emitNamedImportsOrExports(node);
97043         }
97044         function emitExportSpecifier(node) {
97045             emitImportOrExportSpecifier(node);
97046         }
97047         function emitNamedImportsOrExports(node) {
97048             writePunctuation("{");
97049             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
97050             writePunctuation("}");
97051         }
97052         function emitImportOrExportSpecifier(node) {
97053             if (node.propertyName) {
97054                 emit(node.propertyName);
97055                 writeSpace();
97056                 emitTokenWithComment(123 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
97057                 writeSpace();
97058             }
97059             emit(node.name);
97060         }
97061         //
97062         // Module references
97063         //
97064         function emitExternalModuleReference(node) {
97065             writeKeyword("require");
97066             writePunctuation("(");
97067             emitExpression(node.expression);
97068             writePunctuation(")");
97069         }
97070         //
97071         // JSX
97072         //
97073         function emitJsxElement(node) {
97074             emit(node.openingElement);
97075             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97076             emit(node.closingElement);
97077         }
97078         function emitJsxSelfClosingElement(node) {
97079             writePunctuation("<");
97080             emitJsxTagName(node.tagName);
97081             emitTypeArguments(node, node.typeArguments);
97082             writeSpace();
97083             emit(node.attributes);
97084             writePunctuation("/>");
97085         }
97086         function emitJsxFragment(node) {
97087             emit(node.openingFragment);
97088             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97089             emit(node.closingFragment);
97090         }
97091         function emitJsxOpeningElementOrFragment(node) {
97092             writePunctuation("<");
97093             if (ts.isJsxOpeningElement(node)) {
97094                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
97095                 emitJsxTagName(node.tagName);
97096                 emitTypeArguments(node, node.typeArguments);
97097                 if (node.attributes.properties && node.attributes.properties.length > 0) {
97098                     writeSpace();
97099                 }
97100                 emit(node.attributes);
97101                 writeLineSeparatorsAfter(node.attributes, node);
97102                 decreaseIndentIf(indented);
97103             }
97104             writePunctuation(">");
97105         }
97106         function emitJsxText(node) {
97107             writer.writeLiteral(node.text);
97108         }
97109         function emitJsxClosingElementOrFragment(node) {
97110             writePunctuation("</");
97111             if (ts.isJsxClosingElement(node)) {
97112                 emitJsxTagName(node.tagName);
97113             }
97114             writePunctuation(">");
97115         }
97116         function emitJsxAttributes(node) {
97117             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
97118         }
97119         function emitJsxAttribute(node) {
97120             emit(node.name);
97121             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
97122         }
97123         function emitJsxSpreadAttribute(node) {
97124             writePunctuation("{...");
97125             emitExpression(node.expression);
97126             writePunctuation("}");
97127         }
97128         function emitJsxExpression(node) {
97129             if (node.expression) {
97130                 writePunctuation("{");
97131                 emit(node.dotDotDotToken);
97132                 emitExpression(node.expression);
97133                 writePunctuation("}");
97134             }
97135         }
97136         function emitJsxTagName(node) {
97137             if (node.kind === 75 /* Identifier */) {
97138                 emitExpression(node);
97139             }
97140             else {
97141                 emit(node);
97142             }
97143         }
97144         //
97145         // Clauses
97146         //
97147         function emitCaseClause(node) {
97148             emitTokenWithComment(78 /* CaseKeyword */, node.pos, writeKeyword, node);
97149             writeSpace();
97150             emitExpression(node.expression);
97151             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
97152         }
97153         function emitDefaultClause(node) {
97154             var pos = emitTokenWithComment(84 /* DefaultKeyword */, node.pos, writeKeyword, node);
97155             emitCaseOrDefaultClauseRest(node, node.statements, pos);
97156         }
97157         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
97158             var emitAsSingleStatement = statements.length === 1 &&
97159                 (
97160                 // treat synthesized nodes as located on the same line for emit purposes
97161                 ts.nodeIsSynthesized(parentNode) ||
97162                     ts.nodeIsSynthesized(statements[0]) ||
97163                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
97164             var format = 163969 /* CaseOrDefaultClauseStatements */;
97165             if (emitAsSingleStatement) {
97166                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97167                 writeSpace();
97168                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
97169             }
97170             else {
97171                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97172             }
97173             emitList(parentNode, statements, format);
97174         }
97175         function emitHeritageClause(node) {
97176             writeSpace();
97177             writeTokenText(node.token, writeKeyword);
97178             writeSpace();
97179             emitList(node, node.types, 528 /* HeritageClauseTypes */);
97180         }
97181         function emitCatchClause(node) {
97182             var openParenPos = emitTokenWithComment(79 /* CatchKeyword */, node.pos, writeKeyword, node);
97183             writeSpace();
97184             if (node.variableDeclaration) {
97185                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
97186                 emit(node.variableDeclaration);
97187                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
97188                 writeSpace();
97189             }
97190             emit(node.block);
97191         }
97192         //
97193         // Property assignments
97194         //
97195         function emitPropertyAssignment(node) {
97196             emit(node.name);
97197             writePunctuation(":");
97198             writeSpace();
97199             // This is to ensure that we emit comment in the following case:
97200             //      For example:
97201             //          obj = {
97202             //              id: /*comment1*/ ()=>void
97203             //          }
97204             // "comment1" is not considered to be leading comment for node.initializer
97205             // but rather a trailing comment on the previous node.
97206             var initializer = node.initializer;
97207             if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
97208                 var commentRange = ts.getCommentRange(initializer);
97209                 emitTrailingCommentsOfPosition(commentRange.pos);
97210             }
97211             emitExpression(initializer);
97212         }
97213         function emitShorthandPropertyAssignment(node) {
97214             emit(node.name);
97215             if (node.objectAssignmentInitializer) {
97216                 writeSpace();
97217                 writePunctuation("=");
97218                 writeSpace();
97219                 emitExpression(node.objectAssignmentInitializer);
97220             }
97221         }
97222         function emitSpreadAssignment(node) {
97223             if (node.expression) {
97224                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
97225                 emitExpression(node.expression);
97226             }
97227         }
97228         //
97229         // Enum
97230         //
97231         function emitEnumMember(node) {
97232             emit(node.name);
97233             emitInitializer(node.initializer, node.name.end, node);
97234         }
97235         //
97236         // JSDoc
97237         //
97238         function emitJSDoc(node) {
97239             write("/**");
97240             if (node.comment) {
97241                 var lines = node.comment.split(/\r\n?|\n/g);
97242                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
97243                     var line = lines_2[_a];
97244                     writeLine();
97245                     writeSpace();
97246                     writePunctuation("*");
97247                     writeSpace();
97248                     write(line);
97249                 }
97250             }
97251             if (node.tags) {
97252                 if (node.tags.length === 1 && node.tags[0].kind === 320 /* JSDocTypeTag */ && !node.comment) {
97253                     writeSpace();
97254                     emit(node.tags[0]);
97255                 }
97256                 else {
97257                     emitList(node, node.tags, 33 /* JSDocComment */);
97258                 }
97259             }
97260             writeSpace();
97261             write("*/");
97262         }
97263         function emitJSDocSimpleTypedTag(tag) {
97264             emitJSDocTagName(tag.tagName);
97265             emitJSDocTypeExpression(tag.typeExpression);
97266             emitJSDocComment(tag.comment);
97267         }
97268         function emitJSDocHeritageTag(tag) {
97269             emitJSDocTagName(tag.tagName);
97270             writeSpace();
97271             writePunctuation("{");
97272             emit(tag.class);
97273             writePunctuation("}");
97274             emitJSDocComment(tag.comment);
97275         }
97276         function emitJSDocTemplateTag(tag) {
97277             emitJSDocTagName(tag.tagName);
97278             emitJSDocTypeExpression(tag.constraint);
97279             writeSpace();
97280             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
97281             emitJSDocComment(tag.comment);
97282         }
97283         function emitJSDocTypedefTag(tag) {
97284             emitJSDocTagName(tag.tagName);
97285             if (tag.typeExpression) {
97286                 if (tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
97287                     emitJSDocTypeExpression(tag.typeExpression);
97288                 }
97289                 else {
97290                     writeSpace();
97291                     writePunctuation("{");
97292                     write("Object");
97293                     if (tag.typeExpression.isArrayType) {
97294                         writePunctuation("[");
97295                         writePunctuation("]");
97296                     }
97297                     writePunctuation("}");
97298                 }
97299             }
97300             if (tag.fullName) {
97301                 writeSpace();
97302                 emit(tag.fullName);
97303             }
97304             emitJSDocComment(tag.comment);
97305             if (tag.typeExpression && tag.typeExpression.kind === 304 /* JSDocTypeLiteral */) {
97306                 emitJSDocTypeLiteral(tag.typeExpression);
97307             }
97308         }
97309         function emitJSDocCallbackTag(tag) {
97310             emitJSDocTagName(tag.tagName);
97311             if (tag.name) {
97312                 writeSpace();
97313                 emit(tag.name);
97314             }
97315             emitJSDocComment(tag.comment);
97316             emitJSDocSignature(tag.typeExpression);
97317         }
97318         function emitJSDocSimpleTag(tag) {
97319             emitJSDocTagName(tag.tagName);
97320             emitJSDocComment(tag.comment);
97321         }
97322         function emitJSDocTypeLiteral(lit) {
97323             emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
97324         }
97325         function emitJSDocSignature(sig) {
97326             if (sig.typeParameters) {
97327                 emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
97328             }
97329             if (sig.parameters) {
97330                 emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */);
97331             }
97332             if (sig.type) {
97333                 writeLine();
97334                 writeSpace();
97335                 writePunctuation("*");
97336                 writeSpace();
97337                 emit(sig.type);
97338             }
97339         }
97340         function emitJSDocPropertyLikeTag(param) {
97341             emitJSDocTagName(param.tagName);
97342             emitJSDocTypeExpression(param.typeExpression);
97343             writeSpace();
97344             if (param.isBracketed) {
97345                 writePunctuation("[");
97346             }
97347             emit(param.name);
97348             if (param.isBracketed) {
97349                 writePunctuation("]");
97350             }
97351             emitJSDocComment(param.comment);
97352         }
97353         function emitJSDocTagName(tagName) {
97354             writePunctuation("@");
97355             emit(tagName);
97356         }
97357         function emitJSDocComment(comment) {
97358             if (comment) {
97359                 writeSpace();
97360                 write(comment);
97361             }
97362         }
97363         function emitJSDocTypeExpression(typeExpression) {
97364             if (typeExpression) {
97365                 writeSpace();
97366                 writePunctuation("{");
97367                 emit(typeExpression.type);
97368                 writePunctuation("}");
97369             }
97370         }
97371         //
97372         // Top-level nodes
97373         //
97374         function emitSourceFile(node) {
97375             writeLine();
97376             var statements = node.statements;
97377             if (emitBodyWithDetachedComments) {
97378                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
97379                 // The synthesized node will have no leading comment so some comments may be missed.
97380                 var shouldEmitDetachedComment = statements.length === 0 ||
97381                     !ts.isPrologueDirective(statements[0]) ||
97382                     ts.nodeIsSynthesized(statements[0]);
97383                 if (shouldEmitDetachedComment) {
97384                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
97385                     return;
97386                 }
97387             }
97388             emitSourceFileWorker(node);
97389         }
97390         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
97391             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
97392             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
97393                 var prepend = _b[_a];
97394                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
97395                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
97396                         var ref = _d[_c];
97397                         emit(ref);
97398                         writeLine();
97399                     }
97400                 }
97401             }
97402         }
97403         function emitTripleSlashDirectivesIfNeeded(node) {
97404             if (node.isDeclarationFile)
97405                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
97406         }
97407         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
97408             if (hasNoDefaultLib) {
97409                 var pos = writer.getTextPos();
97410                 writeComment("/// <reference no-default-lib=\"true\"/>");
97411                 if (bundleFileInfo)
97412                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
97413                 writeLine();
97414             }
97415             if (currentSourceFile && currentSourceFile.moduleName) {
97416                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
97417                 writeLine();
97418             }
97419             if (currentSourceFile && currentSourceFile.amdDependencies) {
97420                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
97421                     var dep = _b[_a];
97422                     if (dep.name) {
97423                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
97424                     }
97425                     else {
97426                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
97427                     }
97428                     writeLine();
97429                 }
97430             }
97431             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
97432                 var directive = files_1[_c];
97433                 var pos = writer.getTextPos();
97434                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
97435                 if (bundleFileInfo)
97436                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
97437                 writeLine();
97438             }
97439             for (var _d = 0, types_22 = types; _d < types_22.length; _d++) {
97440                 var directive = types_22[_d];
97441                 var pos = writer.getTextPos();
97442                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
97443                 if (bundleFileInfo)
97444                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
97445                 writeLine();
97446             }
97447             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
97448                 var directive = libs_1[_e];
97449                 var pos = writer.getTextPos();
97450                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
97451                 if (bundleFileInfo)
97452                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
97453                 writeLine();
97454             }
97455         }
97456         function emitSourceFileWorker(node) {
97457             var statements = node.statements;
97458             pushNameGenerationScope(node);
97459             ts.forEach(node.statements, generateNames);
97460             emitHelpers(node);
97461             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
97462             emitTripleSlashDirectivesIfNeeded(node);
97463             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
97464             popNameGenerationScope(node);
97465         }
97466         // Transformation nodes
97467         function emitPartiallyEmittedExpression(node) {
97468             emitExpression(node.expression);
97469         }
97470         function emitCommaList(node) {
97471             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
97472         }
97473         /**
97474          * Emits any prologue directives at the start of a Statement list, returning the
97475          * number of prologue directives written to the output.
97476          */
97477         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
97478             var needsToSetSourceFile = !!sourceFile;
97479             for (var i = 0; i < statements.length; i++) {
97480                 var statement = statements[i];
97481                 if (ts.isPrologueDirective(statement)) {
97482                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
97483                     if (shouldEmitPrologueDirective) {
97484                         if (needsToSetSourceFile) {
97485                             needsToSetSourceFile = false;
97486                             setSourceFile(sourceFile);
97487                         }
97488                         writeLine();
97489                         var pos = writer.getTextPos();
97490                         emit(statement);
97491                         if (recordBundleFileSection && bundleFileInfo)
97492                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
97493                         if (seenPrologueDirectives) {
97494                             seenPrologueDirectives.set(statement.expression.text, true);
97495                         }
97496                     }
97497                 }
97498                 else {
97499                     // return index of the first non prologue directive
97500                     return i;
97501                 }
97502             }
97503             return statements.length;
97504         }
97505         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
97506             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
97507                 var prologue = prologues_1[_a];
97508                 if (!seenPrologueDirectives.has(prologue.data)) {
97509                     writeLine();
97510                     var pos = writer.getTextPos();
97511                     emit(prologue);
97512                     if (bundleFileInfo)
97513                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
97514                     if (seenPrologueDirectives) {
97515                         seenPrologueDirectives.set(prologue.data, true);
97516                     }
97517                 }
97518             }
97519         }
97520         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
97521             if (ts.isSourceFile(sourceFileOrBundle)) {
97522                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
97523             }
97524             else {
97525                 var seenPrologueDirectives = ts.createMap();
97526                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97527                     var prepend = _b[_a];
97528                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
97529                 }
97530                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97531                     var sourceFile = _d[_c];
97532                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
97533                 }
97534                 setSourceFile(undefined);
97535             }
97536         }
97537         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
97538             var seenPrologueDirectives = ts.createMap();
97539             var prologues;
97540             for (var index = 0; index < bundle.sourceFiles.length; index++) {
97541                 var sourceFile = bundle.sourceFiles[index];
97542                 var directives = void 0;
97543                 var end = 0;
97544                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
97545                     var statement = _b[_a];
97546                     if (!ts.isPrologueDirective(statement))
97547                         break;
97548                     if (seenPrologueDirectives.has(statement.expression.text))
97549                         continue;
97550                     seenPrologueDirectives.set(statement.expression.text, true);
97551                     (directives || (directives = [])).push({
97552                         pos: statement.pos,
97553                         end: statement.end,
97554                         expression: {
97555                             pos: statement.expression.pos,
97556                             end: statement.expression.end,
97557                             text: statement.expression.text
97558                         }
97559                     });
97560                     end = end < statement.end ? statement.end : end;
97561                 }
97562                 if (directives)
97563                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
97564             }
97565             return prologues;
97566         }
97567         function emitShebangIfNeeded(sourceFileOrBundle) {
97568             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
97569                 var shebang = ts.getShebang(sourceFileOrBundle.text);
97570                 if (shebang) {
97571                     writeComment(shebang);
97572                     writeLine();
97573                     return true;
97574                 }
97575             }
97576             else {
97577                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97578                     var prepend = _b[_a];
97579                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
97580                     if (emitShebangIfNeeded(prepend)) {
97581                         return true;
97582                     }
97583                 }
97584                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97585                     var sourceFile = _d[_c];
97586                     // Emit only the first encountered shebang
97587                     if (emitShebangIfNeeded(sourceFile)) {
97588                         return true;
97589                     }
97590                 }
97591             }
97592         }
97593         //
97594         // Helpers
97595         //
97596         function emitNodeWithWriter(node, writer) {
97597             if (!node)
97598                 return;
97599             var savedWrite = write;
97600             write = writer;
97601             emit(node);
97602             write = savedWrite;
97603         }
97604         function emitModifiers(node, modifiers) {
97605             if (modifiers && modifiers.length) {
97606                 emitList(node, modifiers, 262656 /* Modifiers */);
97607                 writeSpace();
97608             }
97609         }
97610         function emitTypeAnnotation(node) {
97611             if (node) {
97612                 writePunctuation(":");
97613                 writeSpace();
97614                 emit(node);
97615             }
97616         }
97617         function emitInitializer(node, equalCommentStartPos, container) {
97618             if (node) {
97619                 writeSpace();
97620                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
97621                 writeSpace();
97622                 emitExpression(node);
97623             }
97624         }
97625         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
97626             if (node) {
97627                 prefixWriter(prefix);
97628                 emit(node);
97629             }
97630         }
97631         function emitWithLeadingSpace(node) {
97632             if (node) {
97633                 writeSpace();
97634                 emit(node);
97635             }
97636         }
97637         function emitExpressionWithLeadingSpace(node) {
97638             if (node) {
97639                 writeSpace();
97640                 emitExpression(node);
97641             }
97642         }
97643         function emitWithTrailingSpace(node) {
97644             if (node) {
97645                 emit(node);
97646                 writeSpace();
97647             }
97648         }
97649         function emitEmbeddedStatement(parent, node) {
97650             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
97651                 writeSpace();
97652                 emit(node);
97653             }
97654             else {
97655                 writeLine();
97656                 increaseIndent();
97657                 if (ts.isEmptyStatement(node)) {
97658                     pipelineEmit(5 /* EmbeddedStatement */, node);
97659                 }
97660                 else {
97661                     emit(node);
97662                 }
97663                 decreaseIndent();
97664             }
97665         }
97666         function emitDecorators(parentNode, decorators) {
97667             emitList(parentNode, decorators, 2146305 /* Decorators */);
97668         }
97669         function emitTypeArguments(parentNode, typeArguments) {
97670             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
97671         }
97672         function emitTypeParameters(parentNode, typeParameters) {
97673             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
97674                 return emitTypeArguments(parentNode, parentNode.typeArguments);
97675             }
97676             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
97677         }
97678         function emitParameters(parentNode, parameters) {
97679             emitList(parentNode, parameters, 2576 /* Parameters */);
97680         }
97681         function canEmitSimpleArrowHead(parentNode, parameters) {
97682             var parameter = ts.singleOrUndefined(parameters);
97683             return parameter
97684                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
97685                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
97686                 && !parentNode.type // arrow function may not have return type annotation
97687                 && !ts.some(parentNode.decorators) // parent may not have decorators
97688                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
97689                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
97690                 && !ts.some(parameter.decorators) // parameter may not have decorators
97691                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
97692                 && !parameter.dotDotDotToken // parameter may not be rest
97693                 && !parameter.questionToken // parameter may not be optional
97694                 && !parameter.type // parameter may not have a type annotation
97695                 && !parameter.initializer // parameter may not have an initializer
97696                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
97697         }
97698         function emitParametersForArrow(parentNode, parameters) {
97699             if (canEmitSimpleArrowHead(parentNode, parameters)) {
97700                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
97701             }
97702             else {
97703                 emitParameters(parentNode, parameters);
97704             }
97705         }
97706         function emitParametersForIndexSignature(parentNode, parameters) {
97707             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
97708         }
97709         function emitList(parentNode, children, format, start, count) {
97710             emitNodeList(emit, parentNode, children, format, start, count);
97711         }
97712         function emitExpressionList(parentNode, children, format, start, count) {
97713             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
97714         }
97715         function writeDelimiter(format) {
97716             switch (format & 60 /* DelimitersMask */) {
97717                 case 0 /* None */:
97718                     break;
97719                 case 16 /* CommaDelimited */:
97720                     writePunctuation(",");
97721                     break;
97722                 case 4 /* BarDelimited */:
97723                     writeSpace();
97724                     writePunctuation("|");
97725                     break;
97726                 case 32 /* AsteriskDelimited */:
97727                     writeSpace();
97728                     writePunctuation("*");
97729                     writeSpace();
97730                     break;
97731                 case 8 /* AmpersandDelimited */:
97732                     writeSpace();
97733                     writePunctuation("&");
97734                     break;
97735             }
97736         }
97737         function emitNodeList(emit, parentNode, children, format, start, count) {
97738             if (start === void 0) { start = 0; }
97739             if (count === void 0) { count = children ? children.length - start : 0; }
97740             var isUndefined = children === undefined;
97741             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
97742                 return;
97743             }
97744             var isEmpty = children === undefined || start >= children.length || count === 0;
97745             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
97746                 if (onBeforeEmitNodeArray) {
97747                     onBeforeEmitNodeArray(children);
97748                 }
97749                 if (onAfterEmitNodeArray) {
97750                     onAfterEmitNodeArray(children);
97751                 }
97752                 return;
97753             }
97754             if (format & 15360 /* BracketsMask */) {
97755                 writePunctuation(getOpeningBracket(format));
97756                 if (isEmpty && !isUndefined) {
97757                     // TODO: GH#18217
97758                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
97759                 }
97760             }
97761             if (onBeforeEmitNodeArray) {
97762                 onBeforeEmitNodeArray(children);
97763             }
97764             if (isEmpty) {
97765                 // Write a line terminator if the parent node was multi-line
97766                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
97767                     writeLine();
97768                 }
97769                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
97770                     writeSpace();
97771                 }
97772             }
97773             else {
97774                 // Write the opening line terminator or leading whitespace.
97775                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
97776                 var shouldEmitInterveningComments = mayEmitInterveningComments;
97777                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
97778                 if (leadingLineTerminatorCount) {
97779                     writeLine(leadingLineTerminatorCount);
97780                     shouldEmitInterveningComments = false;
97781                 }
97782                 else if (format & 256 /* SpaceBetweenBraces */) {
97783                     writeSpace();
97784                 }
97785                 // Increase the indent, if requested.
97786                 if (format & 128 /* Indented */) {
97787                     increaseIndent();
97788                 }
97789                 // Emit each child.
97790                 var previousSibling = void 0;
97791                 var previousSourceFileTextKind = void 0;
97792                 var shouldDecreaseIndentAfterEmit = false;
97793                 for (var i = 0; i < count; i++) {
97794                     var child = children[start + i];
97795                     // Write the delimiter if this is not the first node.
97796                     if (format & 32 /* AsteriskDelimited */) {
97797                         // always write JSDoc in the format "\n *"
97798                         writeLine();
97799                         writeDelimiter(format);
97800                     }
97801                     else if (previousSibling) {
97802                         // i.e
97803                         //      function commentedParameters(
97804                         //          /* Parameter a */
97805                         //          a
97806                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
97807                         //          ,
97808                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
97809                             emitLeadingCommentsOfPosition(previousSibling.end);
97810                         }
97811                         writeDelimiter(format);
97812                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97813                         // Write either a line terminator or whitespace to separate the elements.
97814                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
97815                         if (separatingLineTerminatorCount > 0) {
97816                             // If a synthesized node in a single-line list starts on a new
97817                             // line, we should increase the indent.
97818                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
97819                                 increaseIndent();
97820                                 shouldDecreaseIndentAfterEmit = true;
97821                             }
97822                             writeLine(separatingLineTerminatorCount);
97823                             shouldEmitInterveningComments = false;
97824                         }
97825                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
97826                             writeSpace();
97827                         }
97828                     }
97829                     // Emit this child.
97830                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
97831                     if (shouldEmitInterveningComments) {
97832                         if (emitTrailingCommentsOfPosition) {
97833                             var commentRange = ts.getCommentRange(child);
97834                             emitTrailingCommentsOfPosition(commentRange.pos);
97835                         }
97836                     }
97837                     else {
97838                         shouldEmitInterveningComments = mayEmitInterveningComments;
97839                     }
97840                     emit(child);
97841                     if (shouldDecreaseIndentAfterEmit) {
97842                         decreaseIndent();
97843                         shouldDecreaseIndentAfterEmit = false;
97844                     }
97845                     previousSibling = child;
97846                 }
97847                 // Write a trailing comma, if requested.
97848                 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
97849                 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
97850                     writePunctuation(",");
97851                 }
97852                 // Emit any trailing comment of the last element in the list
97853                 // i.e
97854                 //       var array = [...
97855                 //          2
97856                 //          /* end of element 2 */
97857                 //       ];
97858                 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
97859                     emitLeadingCommentsOfPosition(previousSibling.end);
97860                 }
97861                 // Decrease the indent, if requested.
97862                 if (format & 128 /* Indented */) {
97863                     decreaseIndent();
97864                 }
97865                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97866                 // Write the closing line terminator or closing whitespace.
97867                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
97868                 if (closingLineTerminatorCount) {
97869                     writeLine(closingLineTerminatorCount);
97870                 }
97871                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
97872                     writeSpace();
97873                 }
97874             }
97875             if (onAfterEmitNodeArray) {
97876                 onAfterEmitNodeArray(children);
97877             }
97878             if (format & 15360 /* BracketsMask */) {
97879                 if (isEmpty && !isUndefined) {
97880                     // TODO: GH#18217
97881                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
97882                 }
97883                 writePunctuation(getClosingBracket(format));
97884             }
97885         }
97886         // Writers
97887         function writeLiteral(s) {
97888             writer.writeLiteral(s);
97889         }
97890         function writeStringLiteral(s) {
97891             writer.writeStringLiteral(s);
97892         }
97893         function writeBase(s) {
97894             writer.write(s);
97895         }
97896         function writeSymbol(s, sym) {
97897             writer.writeSymbol(s, sym);
97898         }
97899         function writePunctuation(s) {
97900             writer.writePunctuation(s);
97901         }
97902         function writeTrailingSemicolon() {
97903             writer.writeTrailingSemicolon(";");
97904         }
97905         function writeKeyword(s) {
97906             writer.writeKeyword(s);
97907         }
97908         function writeOperator(s) {
97909             writer.writeOperator(s);
97910         }
97911         function writeParameter(s) {
97912             writer.writeParameter(s);
97913         }
97914         function writeComment(s) {
97915             writer.writeComment(s);
97916         }
97917         function writeSpace() {
97918             writer.writeSpace(" ");
97919         }
97920         function writeProperty(s) {
97921             writer.writeProperty(s);
97922         }
97923         function writeLine(count) {
97924             if (count === void 0) { count = 1; }
97925             for (var i = 0; i < count; i++) {
97926                 writer.writeLine(i > 0);
97927             }
97928         }
97929         function increaseIndent() {
97930             writer.increaseIndent();
97931         }
97932         function decreaseIndent() {
97933             writer.decreaseIndent();
97934         }
97935         function writeToken(token, pos, writer, contextNode) {
97936             return !sourceMapsDisabled
97937                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
97938                 : writeTokenText(token, writer, pos);
97939         }
97940         function writeTokenNode(node, writer) {
97941             if (onBeforeEmitToken) {
97942                 onBeforeEmitToken(node);
97943             }
97944             writer(ts.tokenToString(node.kind));
97945             if (onAfterEmitToken) {
97946                 onAfterEmitToken(node);
97947             }
97948         }
97949         function writeTokenText(token, writer, pos) {
97950             var tokenString = ts.tokenToString(token);
97951             writer(tokenString);
97952             return pos < 0 ? pos : pos + tokenString.length;
97953         }
97954         function writeLineOrSpace(node) {
97955             if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
97956                 writeSpace();
97957             }
97958             else {
97959                 writeLine();
97960             }
97961         }
97962         function writeLines(text) {
97963             var lines = text.split(/\r\n?|\n/g);
97964             var indentation = ts.guessIndentation(lines);
97965             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
97966                 var lineText = lines_3[_a];
97967                 var line = indentation ? lineText.slice(indentation) : lineText;
97968                 if (line.length) {
97969                     writeLine();
97970                     write(line);
97971                 }
97972             }
97973         }
97974         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
97975             if (lineCount) {
97976                 increaseIndent();
97977                 writeLine(lineCount);
97978             }
97979             else if (writeSpaceIfNotIndenting) {
97980                 writeSpace();
97981             }
97982         }
97983         // Helper function to decrease the indent if we previously indented.  Allows multiple
97984         // previous indent values to be considered at a time.  This also allows caller to just
97985         // call this once, passing in all their appropriate indent values, instead of needing
97986         // to call this helper function multiple times.
97987         function decreaseIndentIf(value1, value2) {
97988             if (value1) {
97989                 decreaseIndent();
97990             }
97991             if (value2) {
97992                 decreaseIndent();
97993             }
97994         }
97995         function getLeadingLineTerminatorCount(parentNode, children, format) {
97996             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
97997                 if (format & 65536 /* PreferNewLine */) {
97998                     return 1;
97999                 }
98000                 var firstChild_1 = children[0];
98001                 if (firstChild_1 === undefined) {
98002                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98003                 }
98004                 if (firstChild_1.kind === 11 /* JsxText */) {
98005                     // JsxText will be written with its leading whitespace, so don't add more manually.
98006                     return 0;
98007                 }
98008                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) {
98009                     if (preserveSourceNewlines) {
98010                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
98011                     }
98012                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
98013                 }
98014                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
98015                     return 1;
98016                 }
98017             }
98018             return format & 1 /* MultiLine */ ? 1 : 0;
98019         }
98020         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
98021             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98022                 if (previousNode === undefined || nextNode === undefined) {
98023                     return 0;
98024                 }
98025                 if (nextNode.kind === 11 /* JsxText */) {
98026                     // JsxText will be written with its leading whitespace, so don't add more manually.
98027                     return 0;
98028                 }
98029                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
98030                     if (preserveSourceNewlines) {
98031                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
98032                     }
98033                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
98034                 }
98035                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
98036                     return 1;
98037                 }
98038             }
98039             else if (ts.getStartsOnNewLine(nextNode)) {
98040                 return 1;
98041             }
98042             return format & 1 /* MultiLine */ ? 1 : 0;
98043         }
98044         function getClosingLineTerminatorCount(parentNode, children, format) {
98045             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98046                 if (format & 65536 /* PreferNewLine */) {
98047                     return 1;
98048                 }
98049                 var lastChild_1 = ts.lastOrUndefined(children);
98050                 if (lastChild_1 === undefined) {
98051                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98052                 }
98053                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) {
98054                     if (preserveSourceNewlines) {
98055                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); });
98056                     }
98057                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1;
98058                 }
98059                 if (synthesizedNodeStartsOnNewLine(lastChild_1, format)) {
98060                     return 1;
98061                 }
98062             }
98063             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
98064                 return 1;
98065             }
98066             return 0;
98067         }
98068         function getEffectiveLines(getLineDifference) {
98069             // If 'preserveSourceNewlines' is disabled, we should never call this function
98070             // because it could be more expensive than alternative approximations.
98071             ts.Debug.assert(!!preserveSourceNewlines);
98072             // We start by measuring the line difference from a position to its adjacent comments,
98073             // so that this is counted as a one-line difference, not two:
98074             //
98075             //   node1;
98076             //   // NODE2 COMMENT
98077             //   node2;
98078             var lines = getLineDifference(/*includeComments*/ true);
98079             if (lines === 0) {
98080                 // However, if the line difference considering comments was 0, we might have this:
98081                 //
98082                 //   node1; // NODE2 COMMENT
98083                 //   node2;
98084                 //
98085                 // in which case we should be ignoring node2's comment, so this too is counted as
98086                 // a one-line difference, not zero.
98087                 return getLineDifference(/*includeComments*/ false);
98088             }
98089             return lines;
98090         }
98091         function writeLineSeparatorsAndIndentBefore(node, parent) {
98092             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
98093             if (leadingNewlines) {
98094                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
98095             }
98096             return !!leadingNewlines;
98097         }
98098         function writeLineSeparatorsAfter(node, parent) {
98099             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
98100             if (trailingNewlines) {
98101                 writeLine(trailingNewlines);
98102             }
98103         }
98104         function synthesizedNodeStartsOnNewLine(node, format) {
98105             if (ts.nodeIsSynthesized(node)) {
98106                 var startsOnNewLine = ts.getStartsOnNewLine(node);
98107                 if (startsOnNewLine === undefined) {
98108                     return (format & 65536 /* PreferNewLine */) !== 0;
98109                 }
98110                 return startsOnNewLine;
98111             }
98112             return (format & 65536 /* PreferNewLine */) !== 0;
98113         }
98114         function getLinesBetweenNodes(parent, node1, node2) {
98115             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
98116                 return 0;
98117             }
98118             parent = skipSynthesizedParentheses(parent);
98119             node1 = skipSynthesizedParentheses(node1);
98120             node2 = skipSynthesizedParentheses(node2);
98121             // Always use a newline for synthesized code if the synthesizer desires it.
98122             if (ts.getStartsOnNewLine(node2)) {
98123                 return 1;
98124             }
98125             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
98126                 if (preserveSourceNewlines) {
98127                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
98128                 }
98129                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
98130             }
98131             return 0;
98132         }
98133         function isEmptyBlock(block) {
98134             return block.statements.length === 0
98135                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
98136         }
98137         function skipSynthesizedParentheses(node) {
98138             while (node.kind === 200 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
98139                 node = node.expression;
98140             }
98141             return node;
98142         }
98143         function getTextOfNode(node, includeTrivia) {
98144             if (ts.isGeneratedIdentifier(node)) {
98145                 return generateName(node);
98146             }
98147             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
98148                 return ts.idText(node);
98149             }
98150             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98151                 return getTextOfNode(node.textSourceNode, includeTrivia);
98152             }
98153             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
98154                 return node.text;
98155             }
98156             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
98157         }
98158         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
98159             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98160                 var textSourceNode = node.textSourceNode;
98161                 if (ts.isIdentifier(textSourceNode)) {
98162                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(getTextOfNode(textSourceNode)) + "\"" :
98163                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
98164                             "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
98165                 }
98166                 else {
98167                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
98168                 }
98169             }
98170             return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape, jsxAttributeEscape);
98171         }
98172         /**
98173          * Push a new name generation scope.
98174          */
98175         function pushNameGenerationScope(node) {
98176             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98177                 return;
98178             }
98179             tempFlagsStack.push(tempFlags);
98180             tempFlags = 0;
98181             reservedNamesStack.push(reservedNames);
98182         }
98183         /**
98184          * Pop the current name generation scope.
98185          */
98186         function popNameGenerationScope(node) {
98187             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98188                 return;
98189             }
98190             tempFlags = tempFlagsStack.pop();
98191             reservedNames = reservedNamesStack.pop();
98192         }
98193         function reserveNameInNestedScopes(name) {
98194             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
98195                 reservedNames = ts.createMap();
98196             }
98197             reservedNames.set(name, true);
98198         }
98199         function generateNames(node) {
98200             if (!node)
98201                 return;
98202             switch (node.kind) {
98203                 case 223 /* Block */:
98204                     ts.forEach(node.statements, generateNames);
98205                     break;
98206                 case 238 /* LabeledStatement */:
98207                 case 236 /* WithStatement */:
98208                 case 228 /* DoStatement */:
98209                 case 229 /* WhileStatement */:
98210                     generateNames(node.statement);
98211                     break;
98212                 case 227 /* IfStatement */:
98213                     generateNames(node.thenStatement);
98214                     generateNames(node.elseStatement);
98215                     break;
98216                 case 230 /* ForStatement */:
98217                 case 232 /* ForOfStatement */:
98218                 case 231 /* ForInStatement */:
98219                     generateNames(node.initializer);
98220                     generateNames(node.statement);
98221                     break;
98222                 case 237 /* SwitchStatement */:
98223                     generateNames(node.caseBlock);
98224                     break;
98225                 case 251 /* CaseBlock */:
98226                     ts.forEach(node.clauses, generateNames);
98227                     break;
98228                 case 277 /* CaseClause */:
98229                 case 278 /* DefaultClause */:
98230                     ts.forEach(node.statements, generateNames);
98231                     break;
98232                 case 240 /* TryStatement */:
98233                     generateNames(node.tryBlock);
98234                     generateNames(node.catchClause);
98235                     generateNames(node.finallyBlock);
98236                     break;
98237                 case 280 /* CatchClause */:
98238                     generateNames(node.variableDeclaration);
98239                     generateNames(node.block);
98240                     break;
98241                 case 225 /* VariableStatement */:
98242                     generateNames(node.declarationList);
98243                     break;
98244                 case 243 /* VariableDeclarationList */:
98245                     ts.forEach(node.declarations, generateNames);
98246                     break;
98247                 case 242 /* VariableDeclaration */:
98248                 case 156 /* Parameter */:
98249                 case 191 /* BindingElement */:
98250                 case 245 /* ClassDeclaration */:
98251                     generateNameIfNeeded(node.name);
98252                     break;
98253                 case 244 /* FunctionDeclaration */:
98254                     generateNameIfNeeded(node.name);
98255                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98256                         ts.forEach(node.parameters, generateNames);
98257                         generateNames(node.body);
98258                     }
98259                     break;
98260                 case 189 /* ObjectBindingPattern */:
98261                 case 190 /* ArrayBindingPattern */:
98262                     ts.forEach(node.elements, generateNames);
98263                     break;
98264                 case 254 /* ImportDeclaration */:
98265                     generateNames(node.importClause);
98266                     break;
98267                 case 255 /* ImportClause */:
98268                     generateNameIfNeeded(node.name);
98269                     generateNames(node.namedBindings);
98270                     break;
98271                 case 256 /* NamespaceImport */:
98272                     generateNameIfNeeded(node.name);
98273                     break;
98274                 case 262 /* NamespaceExport */:
98275                     generateNameIfNeeded(node.name);
98276                     break;
98277                 case 257 /* NamedImports */:
98278                     ts.forEach(node.elements, generateNames);
98279                     break;
98280                 case 258 /* ImportSpecifier */:
98281                     generateNameIfNeeded(node.propertyName || node.name);
98282                     break;
98283             }
98284         }
98285         function generateMemberNames(node) {
98286             if (!node)
98287                 return;
98288             switch (node.kind) {
98289                 case 281 /* PropertyAssignment */:
98290                 case 282 /* ShorthandPropertyAssignment */:
98291                 case 159 /* PropertyDeclaration */:
98292                 case 161 /* MethodDeclaration */:
98293                 case 163 /* GetAccessor */:
98294                 case 164 /* SetAccessor */:
98295                     generateNameIfNeeded(node.name);
98296                     break;
98297             }
98298         }
98299         function generateNameIfNeeded(name) {
98300             if (name) {
98301                 if (ts.isGeneratedIdentifier(name)) {
98302                     generateName(name);
98303                 }
98304                 else if (ts.isBindingPattern(name)) {
98305                     generateNames(name);
98306                 }
98307             }
98308         }
98309         /**
98310          * Generate the text for a generated identifier.
98311          */
98312         function generateName(name) {
98313             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
98314                 // Node names generate unique names based on their original node
98315                 // and are cached based on that node's id.
98316                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
98317             }
98318             else {
98319                 // Auto, Loop, and Unique names are cached based on their unique
98320                 // autoGenerateId.
98321                 var autoGenerateId = name.autoGenerateId;
98322                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
98323             }
98324         }
98325         function generateNameCached(node, flags) {
98326             var nodeId = ts.getNodeId(node);
98327             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
98328         }
98329         /**
98330          * Returns a value indicating whether a name is unique globally, within the current file,
98331          * or within the NameGenerator.
98332          */
98333         function isUniqueName(name) {
98334             return isFileLevelUniqueName(name)
98335                 && !generatedNames.has(name)
98336                 && !(reservedNames && reservedNames.has(name));
98337         }
98338         /**
98339          * Returns a value indicating whether a name is unique globally or within the current file.
98340          */
98341         function isFileLevelUniqueName(name) {
98342             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
98343         }
98344         /**
98345          * Returns a value indicating whether a name is unique within a container.
98346          */
98347         function isUniqueLocalName(name, container) {
98348             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
98349                 if (node.locals) {
98350                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
98351                     // We conservatively include alias symbols to cover cases where they're emitted as locals
98352                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
98353                         return false;
98354                     }
98355                 }
98356             }
98357             return true;
98358         }
98359         /**
98360          * Return the next available name in the pattern _a ... _z, _0, _1, ...
98361          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
98362          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
98363          */
98364         function makeTempVariableName(flags, reservedInNestedScopes) {
98365             if (flags && !(tempFlags & flags)) {
98366                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
98367                 if (isUniqueName(name)) {
98368                     tempFlags |= flags;
98369                     if (reservedInNestedScopes) {
98370                         reserveNameInNestedScopes(name);
98371                     }
98372                     return name;
98373                 }
98374             }
98375             while (true) {
98376                 var count = tempFlags & 268435455 /* CountMask */;
98377                 tempFlags++;
98378                 // Skip over 'i' and 'n'
98379                 if (count !== 8 && count !== 13) {
98380                     var name = count < 26
98381                         ? "_" + String.fromCharCode(97 /* a */ + count)
98382                         : "_" + (count - 26);
98383                     if (isUniqueName(name)) {
98384                         if (reservedInNestedScopes) {
98385                             reserveNameInNestedScopes(name);
98386                         }
98387                         return name;
98388                     }
98389                 }
98390             }
98391         }
98392         /**
98393          * Generate a name that is unique within the current file and doesn't conflict with any names
98394          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
98395          * where n is a positive integer. Note that names generated by makeTempVariableName and
98396          * makeUniqueName are guaranteed to never conflict.
98397          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
98398          */
98399         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
98400             if (checkFn === void 0) { checkFn = isUniqueName; }
98401             if (optimistic) {
98402                 if (checkFn(baseName)) {
98403                     if (scoped) {
98404                         reserveNameInNestedScopes(baseName);
98405                     }
98406                     else {
98407                         generatedNames.set(baseName, true);
98408                     }
98409                     return baseName;
98410                 }
98411             }
98412             // Find the first unique 'name_n', where n is a positive number
98413             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
98414                 baseName += "_";
98415             }
98416             var i = 1;
98417             while (true) {
98418                 var generatedName = baseName + i;
98419                 if (checkFn(generatedName)) {
98420                     if (scoped) {
98421                         reserveNameInNestedScopes(generatedName);
98422                     }
98423                     else {
98424                         generatedNames.set(generatedName, true);
98425                     }
98426                     return generatedName;
98427                 }
98428                 i++;
98429             }
98430         }
98431         function makeFileLevelOptimisticUniqueName(name) {
98432             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
98433         }
98434         /**
98435          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
98436          */
98437         function generateNameForModuleOrEnum(node) {
98438             var name = getTextOfNode(node.name);
98439             // Use module/enum name itself if it is unique, otherwise make a unique variation
98440             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
98441         }
98442         /**
98443          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
98444          */
98445         function generateNameForImportOrExportDeclaration(node) {
98446             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
98447             var baseName = ts.isStringLiteral(expr) ?
98448                 ts.makeIdentifierFromModuleName(expr.text) : "module";
98449             return makeUniqueName(baseName);
98450         }
98451         /**
98452          * Generates a unique name for a default export.
98453          */
98454         function generateNameForExportDefault() {
98455             return makeUniqueName("default");
98456         }
98457         /**
98458          * Generates a unique name for a class expression.
98459          */
98460         function generateNameForClassExpression() {
98461             return makeUniqueName("class");
98462         }
98463         function generateNameForMethodOrAccessor(node) {
98464             if (ts.isIdentifier(node.name)) {
98465                 return generateNameCached(node.name);
98466             }
98467             return makeTempVariableName(0 /* Auto */);
98468         }
98469         /**
98470          * Generates a unique name from a node.
98471          */
98472         function generateNameForNode(node, flags) {
98473             switch (node.kind) {
98474                 case 75 /* Identifier */:
98475                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
98476                 case 249 /* ModuleDeclaration */:
98477                 case 248 /* EnumDeclaration */:
98478                     return generateNameForModuleOrEnum(node);
98479                 case 254 /* ImportDeclaration */:
98480                 case 260 /* ExportDeclaration */:
98481                     return generateNameForImportOrExportDeclaration(node);
98482                 case 244 /* FunctionDeclaration */:
98483                 case 245 /* ClassDeclaration */:
98484                 case 259 /* ExportAssignment */:
98485                     return generateNameForExportDefault();
98486                 case 214 /* ClassExpression */:
98487                     return generateNameForClassExpression();
98488                 case 161 /* MethodDeclaration */:
98489                 case 163 /* GetAccessor */:
98490                 case 164 /* SetAccessor */:
98491                     return generateNameForMethodOrAccessor(node);
98492                 case 154 /* ComputedPropertyName */:
98493                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
98494                 default:
98495                     return makeTempVariableName(0 /* Auto */);
98496             }
98497         }
98498         /**
98499          * Generates a unique identifier for a node.
98500          */
98501         function makeName(name) {
98502             switch (name.autoGenerateFlags & 7 /* KindMask */) {
98503                 case 1 /* Auto */:
98504                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98505                 case 2 /* Loop */:
98506                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98507                 case 3 /* Unique */:
98508                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98509             }
98510             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
98511         }
98512         /**
98513          * Gets the node from which a name should be generated.
98514          */
98515         function getNodeForGeneratedName(name) {
98516             var autoGenerateId = name.autoGenerateId;
98517             var node = name;
98518             var original = node.original;
98519             while (original) {
98520                 node = original;
98521                 // if "node" is a different generated name (having a different
98522                 // "autoGenerateId"), use it and stop traversing.
98523                 if (ts.isIdentifier(node)
98524                     && !!(node.autoGenerateFlags & 4 /* Node */)
98525                     && node.autoGenerateId !== autoGenerateId) {
98526                     break;
98527                 }
98528                 original = node.original;
98529             }
98530             // otherwise, return the original node for the source;
98531             return node;
98532         }
98533         // Comments
98534         function pipelineEmitWithComments(hint, node) {
98535             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98536             enterComment();
98537             hasWrittenComment = false;
98538             var emitFlags = ts.getEmitFlags(node);
98539             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
98540             var isEmittedNode = node.kind !== 325 /* NotEmittedStatement */;
98541             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
98542             // It is expensive to walk entire tree just to set one kind of node to have no comments.
98543             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
98544             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
98545             // Save current container state on the stack.
98546             var savedContainerPos = containerPos;
98547             var savedContainerEnd = containerEnd;
98548             var savedDeclarationListContainerEnd = declarationListContainerEnd;
98549             if ((pos > 0 || end > 0) && pos !== end) {
98550                 // Emit leading comments if the position is not synthesized and the node
98551                 // has not opted out from emitting leading comments.
98552                 if (!skipLeadingComments) {
98553                     emitLeadingComments(pos, isEmittedNode);
98554                 }
98555                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
98556                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
98557                     containerPos = pos;
98558                 }
98559                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
98560                     // As above.
98561                     containerEnd = end;
98562                     // To avoid invalid comment emit in a down-level binding pattern, we
98563                     // keep track of the last declaration list container's end
98564                     if (node.kind === 243 /* VariableDeclarationList */) {
98565                         declarationListContainerEnd = end;
98566                     }
98567                 }
98568             }
98569             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
98570             exitComment();
98571             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
98572             if (emitFlags & 2048 /* NoNestedComments */) {
98573                 commentsDisabled = true;
98574                 pipelinePhase(hint, node);
98575                 commentsDisabled = false;
98576             }
98577             else {
98578                 pipelinePhase(hint, node);
98579             }
98580             enterComment();
98581             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
98582             if ((pos > 0 || end > 0) && pos !== end) {
98583                 // Restore previous container state.
98584                 containerPos = savedContainerPos;
98585                 containerEnd = savedContainerEnd;
98586                 declarationListContainerEnd = savedDeclarationListContainerEnd;
98587                 // Emit trailing comments if the position is not synthesized and the node
98588                 // has not opted out from emitting leading comments and is an emitted node.
98589                 if (!skipTrailingComments && isEmittedNode) {
98590                     emitTrailingComments(end);
98591                 }
98592             }
98593             exitComment();
98594             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98595         }
98596         function emitLeadingSynthesizedComment(comment) {
98597             if (comment.kind === 2 /* SingleLineCommentTrivia */) {
98598                 writer.writeLine();
98599             }
98600             writeSynthesizedComment(comment);
98601             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
98602                 writer.writeLine();
98603             }
98604             else {
98605                 writer.writeSpace(" ");
98606             }
98607         }
98608         function emitTrailingSynthesizedComment(comment) {
98609             if (!writer.isAtStartOfLine()) {
98610                 writer.writeSpace(" ");
98611             }
98612             writeSynthesizedComment(comment);
98613             if (comment.hasTrailingNewLine) {
98614                 writer.writeLine();
98615             }
98616         }
98617         function writeSynthesizedComment(comment) {
98618             var text = formatSynthesizedComment(comment);
98619             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
98620             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
98621         }
98622         function formatSynthesizedComment(comment) {
98623             return comment.kind === 3 /* MultiLineCommentTrivia */
98624                 ? "/*" + comment.text + "*/"
98625                 : "//" + comment.text;
98626         }
98627         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
98628             enterComment();
98629             var pos = detachedRange.pos, end = detachedRange.end;
98630             var emitFlags = ts.getEmitFlags(node);
98631             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
98632             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
98633             if (!skipLeadingComments) {
98634                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
98635             }
98636             exitComment();
98637             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
98638                 commentsDisabled = true;
98639                 emitCallback(node);
98640                 commentsDisabled = false;
98641             }
98642             else {
98643                 emitCallback(node);
98644             }
98645             enterComment();
98646             if (!skipTrailingComments) {
98647                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
98648                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
98649                     writer.writeLine();
98650                 }
98651             }
98652             exitComment();
98653         }
98654         function emitLeadingComments(pos, isEmittedNode) {
98655             hasWrittenComment = false;
98656             if (isEmittedNode) {
98657                 forEachLeadingCommentToEmit(pos, emitLeadingComment);
98658             }
98659             else if (pos === 0) {
98660                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
98661                 // unless it is a triple slash comment at the top of the file.
98662                 // For Example:
98663                 //      /// <reference-path ...>
98664                 //      declare var x;
98665                 //      /// <reference-path ...>
98666                 //      interface F {}
98667                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
98668                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
98669             }
98670         }
98671         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98672             if (isTripleSlashComment(commentPos, commentEnd)) {
98673                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
98674             }
98675         }
98676         function shouldWriteComment(text, pos) {
98677             if (printerOptions.onlyPrintJsDocStyle) {
98678                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
98679             }
98680             return true;
98681         }
98682         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98683             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98684                 return;
98685             if (!hasWrittenComment) {
98686                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
98687                 hasWrittenComment = true;
98688             }
98689             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
98690             emitPos(commentPos);
98691             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98692             emitPos(commentEnd);
98693             if (hasTrailingNewLine) {
98694                 writer.writeLine();
98695             }
98696             else if (kind === 3 /* MultiLineCommentTrivia */) {
98697                 writer.writeSpace(" ");
98698             }
98699         }
98700         function emitLeadingCommentsOfPosition(pos) {
98701             if (commentsDisabled || pos === -1) {
98702                 return;
98703             }
98704             emitLeadingComments(pos, /*isEmittedNode*/ true);
98705         }
98706         function emitTrailingComments(pos) {
98707             forEachTrailingCommentToEmit(pos, emitTrailingComment);
98708         }
98709         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98710             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98711                 return;
98712             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
98713             if (!writer.isAtStartOfLine()) {
98714                 writer.writeSpace(" ");
98715             }
98716             emitPos(commentPos);
98717             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98718             emitPos(commentEnd);
98719             if (hasTrailingNewLine) {
98720                 writer.writeLine();
98721             }
98722         }
98723         function emitTrailingCommentsOfPosition(pos, prefixSpace) {
98724             if (commentsDisabled) {
98725                 return;
98726             }
98727             enterComment();
98728             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
98729             exitComment();
98730         }
98731         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98732             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
98733             emitPos(commentPos);
98734             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98735             emitPos(commentEnd);
98736             if (hasTrailingNewLine) {
98737                 writer.writeLine();
98738             }
98739             else {
98740                 writer.writeSpace(" ");
98741             }
98742         }
98743         function forEachLeadingCommentToEmit(pos, cb) {
98744             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
98745             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
98746                 if (hasDetachedComments(pos)) {
98747                     forEachLeadingCommentWithoutDetachedComments(cb);
98748                 }
98749                 else {
98750                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98751                 }
98752             }
98753         }
98754         function forEachTrailingCommentToEmit(end, cb) {
98755             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
98756             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
98757                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
98758             }
98759         }
98760         function hasDetachedComments(pos) {
98761             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
98762         }
98763         function forEachLeadingCommentWithoutDetachedComments(cb) {
98764             // get the leading comments from detachedPos
98765             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
98766             if (detachedCommentsInfo.length - 1) {
98767                 detachedCommentsInfo.pop();
98768             }
98769             else {
98770                 detachedCommentsInfo = undefined;
98771             }
98772             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98773         }
98774         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
98775             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
98776             if (currentDetachedCommentInfo) {
98777                 if (detachedCommentsInfo) {
98778                     detachedCommentsInfo.push(currentDetachedCommentInfo);
98779                 }
98780                 else {
98781                     detachedCommentsInfo = [currentDetachedCommentInfo];
98782                 }
98783             }
98784         }
98785         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
98786             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98787                 return;
98788             emitPos(commentPos);
98789             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
98790             emitPos(commentEnd);
98791         }
98792         /**
98793          * Determine if the given comment is a triple-slash
98794          *
98795          * @return true if the comment is a triple-slash comment else false
98796          */
98797         function isTripleSlashComment(commentPos, commentEnd) {
98798             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
98799         }
98800         // Source Maps
98801         function getParsedSourceMap(node) {
98802             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
98803                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
98804             }
98805             return node.parsedSourceMap || undefined;
98806         }
98807         function pipelineEmitWithSourceMap(hint, node) {
98808             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98809             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
98810             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
98811                 pipelinePhase(hint, node);
98812             }
98813             else if (ts.isUnparsedNode(node)) {
98814                 var parsed = getParsedSourceMap(node.parent);
98815                 if (parsed && sourceMapGenerator) {
98816                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
98817                 }
98818                 pipelinePhase(hint, node);
98819             }
98820             else {
98821                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
98822                 var emitFlags = ts.getEmitFlags(node);
98823                 if (node.kind !== 325 /* NotEmittedStatement */
98824                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
98825                     && pos >= 0) {
98826                     emitSourcePos(source, skipSourceTrivia(source, pos));
98827                 }
98828                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
98829                     sourceMapsDisabled = true;
98830                     pipelinePhase(hint, node);
98831                     sourceMapsDisabled = false;
98832                 }
98833                 else {
98834                     pipelinePhase(hint, node);
98835                 }
98836                 if (node.kind !== 325 /* NotEmittedStatement */
98837                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
98838                     && end >= 0) {
98839                     emitSourcePos(source, end);
98840                 }
98841             }
98842             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98843         }
98844         /**
98845          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
98846          */
98847         function skipSourceTrivia(source, pos) {
98848             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
98849         }
98850         /**
98851          * Emits a mapping.
98852          *
98853          * If the position is synthetic (undefined or a negative value), no mapping will be
98854          * created.
98855          *
98856          * @param pos The position.
98857          */
98858         function emitPos(pos) {
98859             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
98860                 return;
98861             }
98862             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
98863             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
98864             /*nameIndex*/ undefined);
98865         }
98866         function emitSourcePos(source, pos) {
98867             if (source !== sourceMapSource) {
98868                 var savedSourceMapSource = sourceMapSource;
98869                 setSourceMapSource(source);
98870                 emitPos(pos);
98871                 setSourceMapSource(savedSourceMapSource);
98872             }
98873             else {
98874                 emitPos(pos);
98875             }
98876         }
98877         /**
98878          * Emits a token of a node with possible leading and trailing source maps.
98879          *
98880          * @param node The node containing the token.
98881          * @param token The token to emit.
98882          * @param tokenStartPos The start pos of the token.
98883          * @param emitCallback The callback used to emit the token.
98884          */
98885         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
98886             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
98887                 return emitCallback(token, writer, tokenPos);
98888             }
98889             var emitNode = node && node.emitNode;
98890             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
98891             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
98892             var source = range && range.source || sourceMapSource;
98893             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
98894             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
98895                 emitSourcePos(source, tokenPos);
98896             }
98897             tokenPos = emitCallback(token, writer, tokenPos);
98898             if (range)
98899                 tokenPos = range.end;
98900             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
98901                 emitSourcePos(source, tokenPos);
98902             }
98903             return tokenPos;
98904         }
98905         function setSourceMapSource(source) {
98906             if (sourceMapsDisabled) {
98907                 return;
98908             }
98909             sourceMapSource = source;
98910             if (isJsonSourceMapSource(source)) {
98911                 return;
98912             }
98913             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
98914             if (printerOptions.inlineSources) {
98915                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
98916             }
98917         }
98918         function isJsonSourceMapSource(sourceFile) {
98919             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
98920         }
98921     }
98922     ts.createPrinter = createPrinter;
98923     function createBracketsMap() {
98924         var brackets = [];
98925         brackets[1024 /* Braces */] = ["{", "}"];
98926         brackets[2048 /* Parenthesis */] = ["(", ")"];
98927         brackets[4096 /* AngleBrackets */] = ["<", ">"];
98928         brackets[8192 /* SquareBrackets */] = ["[", "]"];
98929         return brackets;
98930     }
98931     function getOpeningBracket(format) {
98932         return brackets[format & 15360 /* BracketsMask */][0];
98933     }
98934     function getClosingBracket(format) {
98935         return brackets[format & 15360 /* BracketsMask */][1];
98936     }
98937     // Flags enum to track count of temp variables and a few dedicated names
98938     var TempFlags;
98939     (function (TempFlags) {
98940         TempFlags[TempFlags["Auto"] = 0] = "Auto";
98941         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
98942         TempFlags[TempFlags["_i"] = 268435456] = "_i";
98943     })(TempFlags || (TempFlags = {}));
98944 })(ts || (ts = {}));
98945 /* @internal */
98946 var ts;
98947 (function (ts) {
98948     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
98949         if (!host.getDirectories || !host.readDirectory) {
98950             return undefined;
98951         }
98952         var cachedReadDirectoryResult = ts.createMap();
98953         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
98954         return {
98955             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
98956             fileExists: fileExists,
98957             readFile: function (path, encoding) { return host.readFile(path, encoding); },
98958             directoryExists: host.directoryExists && directoryExists,
98959             getDirectories: getDirectories,
98960             readDirectory: readDirectory,
98961             createDirectory: host.createDirectory && createDirectory,
98962             writeFile: host.writeFile && writeFile,
98963             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
98964             addOrDeleteFile: addOrDeleteFile,
98965             clearCache: clearCache,
98966             realpath: host.realpath && realpath
98967         };
98968         function toPath(fileName) {
98969             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
98970         }
98971         function getCachedFileSystemEntries(rootDirPath) {
98972             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
98973         }
98974         function getCachedFileSystemEntriesForBaseDir(path) {
98975             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
98976         }
98977         function getBaseNameOfFileName(fileName) {
98978             return ts.getBaseFileName(ts.normalizePath(fileName));
98979         }
98980         function createCachedFileSystemEntries(rootDir, rootDirPath) {
98981             var resultFromHost = {
98982                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
98983                 directories: host.getDirectories(rootDir) || []
98984             };
98985             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
98986             return resultFromHost;
98987         }
98988         /**
98989          * If the readDirectory result was already cached, it returns that
98990          * Otherwise gets result from host and caches it.
98991          * The host request is done under try catch block to avoid caching incorrect result
98992          */
98993         function tryReadDirectory(rootDir, rootDirPath) {
98994             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
98995             var cachedResult = getCachedFileSystemEntries(rootDirPath);
98996             if (cachedResult) {
98997                 return cachedResult;
98998             }
98999             try {
99000                 return createCachedFileSystemEntries(rootDir, rootDirPath);
99001             }
99002             catch (_e) {
99003                 // If there is exception to read directories, dont cache the result and direct the calls to host
99004                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
99005                 return undefined;
99006             }
99007         }
99008         function fileNameEqual(name1, name2) {
99009             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
99010         }
99011         function hasEntry(entries, name) {
99012             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
99013         }
99014         function updateFileSystemEntry(entries, baseName, isValid) {
99015             if (hasEntry(entries, baseName)) {
99016                 if (!isValid) {
99017                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
99018                 }
99019             }
99020             else if (isValid) {
99021                 return entries.push(baseName);
99022             }
99023         }
99024         function writeFile(fileName, data, writeByteOrderMark) {
99025             var path = toPath(fileName);
99026             var result = getCachedFileSystemEntriesForBaseDir(path);
99027             if (result) {
99028                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
99029             }
99030             return host.writeFile(fileName, data, writeByteOrderMark);
99031         }
99032         function fileExists(fileName) {
99033             var path = toPath(fileName);
99034             var result = getCachedFileSystemEntriesForBaseDir(path);
99035             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
99036                 host.fileExists(fileName);
99037         }
99038         function directoryExists(dirPath) {
99039             var path = toPath(dirPath);
99040             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
99041         }
99042         function createDirectory(dirPath) {
99043             var path = toPath(dirPath);
99044             var result = getCachedFileSystemEntriesForBaseDir(path);
99045             var baseFileName = getBaseNameOfFileName(dirPath);
99046             if (result) {
99047                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
99048             }
99049             host.createDirectory(dirPath);
99050         }
99051         function getDirectories(rootDir) {
99052             var rootDirPath = toPath(rootDir);
99053             var result = tryReadDirectory(rootDir, rootDirPath);
99054             if (result) {
99055                 return result.directories.slice();
99056             }
99057             return host.getDirectories(rootDir);
99058         }
99059         function readDirectory(rootDir, extensions, excludes, includes, depth) {
99060             var rootDirPath = toPath(rootDir);
99061             var result = tryReadDirectory(rootDir, rootDirPath);
99062             if (result) {
99063                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
99064             }
99065             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
99066             function getFileSystemEntries(dir) {
99067                 var path = toPath(dir);
99068                 if (path === rootDirPath) {
99069                     return result;
99070                 }
99071                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
99072             }
99073         }
99074         function realpath(s) {
99075             return host.realpath ? host.realpath(s) : s;
99076         }
99077         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
99078             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
99079             if (existingResult) {
99080                 // Just clear the cache for now
99081                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
99082                 clearCache();
99083                 return undefined;
99084             }
99085             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
99086             if (!parentResult) {
99087                 return undefined;
99088             }
99089             // This was earlier a file (hence not in cached directory contents)
99090             // or we never cached the directory containing it
99091             if (!host.directoryExists) {
99092                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
99093                 clearCache();
99094                 return undefined;
99095             }
99096             var baseName = getBaseNameOfFileName(fileOrDirectory);
99097             var fsQueryResult = {
99098                 fileExists: host.fileExists(fileOrDirectoryPath),
99099                 directoryExists: host.directoryExists(fileOrDirectoryPath)
99100             };
99101             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
99102                 // Folder added or removed, clear the cache instead of updating the folder and its structure
99103                 clearCache();
99104             }
99105             else {
99106                 // No need to update the directory structure, just files
99107                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
99108             }
99109             return fsQueryResult;
99110         }
99111         function addOrDeleteFile(fileName, filePath, eventKind) {
99112             if (eventKind === ts.FileWatcherEventKind.Changed) {
99113                 return;
99114             }
99115             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
99116             if (parentResult) {
99117                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
99118             }
99119         }
99120         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
99121             updateFileSystemEntry(parentResult.files, baseName, fileExists);
99122         }
99123         function clearCache() {
99124             cachedReadDirectoryResult.clear();
99125         }
99126     }
99127     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
99128     var ConfigFileProgramReloadLevel;
99129     (function (ConfigFileProgramReloadLevel) {
99130         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
99131         /** Update the file name list from the disk */
99132         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
99133         /** Reload completely by re-reading contents of config file from disk and updating program */
99134         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
99135     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
99136     /**
99137      * Updates the existing missing file watches with the new set of missing files after new program is created
99138      */
99139     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
99140         var missingFilePaths = program.getMissingFilePaths();
99141         var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
99142         // Update the missing file paths watcher
99143         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
99144             // Watch the missing files
99145             createNewValue: createMissingFileWatch,
99146             // Files that are no longer missing (e.g. because they are no longer required)
99147             // should no longer be watched.
99148             onDeleteValue: ts.closeFileWatcher
99149         });
99150     }
99151     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
99152     /**
99153      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
99154      * after new program is created because the config file was reloaded or program was created first time from the config file
99155      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
99156      * as wildcard directories wont change unless reloading config file
99157      */
99158     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
99159         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
99160             // Create new watch and recursive info
99161             createNewValue: createWildcardDirectoryWatcher,
99162             // Close existing watch thats not needed any more
99163             onDeleteValue: closeFileWatcherOf,
99164             // Close existing watch that doesnt match in the flags
99165             onExistingValue: updateWildcardDirectoryWatcher
99166         });
99167         function createWildcardDirectoryWatcher(directory, flags) {
99168             // Create new watch and recursive info
99169             return {
99170                 watcher: watchDirectory(directory, flags),
99171                 flags: flags
99172             };
99173         }
99174         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
99175             // Watcher needs to be updated if the recursive flags dont match
99176             if (existingWatcher.flags === flags) {
99177                 return;
99178             }
99179             existingWatcher.watcher.close();
99180             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
99181         }
99182     }
99183     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
99184     function isEmittedFileOfProgram(program, file) {
99185         if (!program) {
99186             return false;
99187         }
99188         return program.isEmittedFile(file);
99189     }
99190     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
99191     var WatchLogLevel;
99192     (function (WatchLogLevel) {
99193         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
99194         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
99195         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
99196     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
99197     function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
99198         return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
99199     }
99200     ts.getWatchFactory = getWatchFactory;
99201     function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
99202         var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
99203         var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
99204         var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
99205         if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
99206             ts.setSysLog(function (s) { return log(s); });
99207         }
99208         return {
99209             watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
99210                 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99211             },
99212             watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
99213                 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99214             },
99215             watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
99216                 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
99217             }
99218         };
99219     }
99220     function watchFile(host, file, callback, pollingInterval, options) {
99221         return host.watchFile(file, callback, pollingInterval, options);
99222     }
99223     function watchFilePath(host, file, callback, pollingInterval, options, path) {
99224         return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
99225     }
99226     function watchDirectory(host, directory, callback, flags, options) {
99227         return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
99228     }
99229     function getCreateFileWatcher(watchLogLevel, addWatch) {
99230         switch (watchLogLevel) {
99231             case WatchLogLevel.None:
99232                 return addWatch;
99233             case WatchLogLevel.TriggerOnly:
99234                 return createFileWatcherWithTriggerLogging;
99235             case WatchLogLevel.Verbose:
99236                 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
99237         }
99238     }
99239     function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99240         log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99241         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99242         return {
99243             close: function () {
99244                 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99245                 watcher.close();
99246             }
99247         };
99248     }
99249     function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99250         var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99251         log(watchInfo);
99252         var start = ts.timestamp();
99253         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99254         var elapsed = ts.timestamp() - start;
99255         log("Elapsed:: " + elapsed + "ms " + watchInfo);
99256         return {
99257             close: function () {
99258                 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99259                 log(watchInfo);
99260                 var start = ts.timestamp();
99261                 watcher.close();
99262                 var elapsed = ts.timestamp() - start;
99263                 log("Elapsed:: " + elapsed + "ms " + watchInfo);
99264             }
99265         };
99266     }
99267     function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99268         return addWatch(host, file, function (fileName, cbOptional) {
99269             var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99270             log(triggerredInfo);
99271             var start = ts.timestamp();
99272             cb(fileName, cbOptional, passThrough);
99273             var elapsed = ts.timestamp() - start;
99274             log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
99275         }, flags, options);
99276     }
99277     function getFallbackOptions(options) {
99278         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
99279         return {
99280             watchFile: fallbackPolling !== undefined ?
99281                 fallbackPolling :
99282                 ts.WatchFileKind.PriorityPollingInterval
99283         };
99284     }
99285     ts.getFallbackOptions = getFallbackOptions;
99286     function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
99287         return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
99288     }
99289     function closeFileWatcherOf(objWithWatcher) {
99290         objWithWatcher.watcher.close();
99291     }
99292     ts.closeFileWatcherOf = closeFileWatcherOf;
99293 })(ts || (ts = {}));
99294 var ts;
99295 (function (ts) {
99296     function findConfigFile(searchPath, fileExists, configName) {
99297         if (configName === void 0) { configName = "tsconfig.json"; }
99298         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
99299             var fileName = ts.combinePaths(ancestor, configName);
99300             return fileExists(fileName) ? fileName : undefined;
99301         });
99302     }
99303     ts.findConfigFile = findConfigFile;
99304     function resolveTripleslashReference(moduleName, containingFile) {
99305         var basePath = ts.getDirectoryPath(containingFile);
99306         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
99307         return ts.normalizePath(referencedFileName);
99308     }
99309     ts.resolveTripleslashReference = resolveTripleslashReference;
99310     /* @internal */
99311     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
99312         var commonPathComponents;
99313         var failed = ts.forEach(fileNames, function (sourceFile) {
99314             // Each file contributes into common source file path
99315             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
99316             sourcePathComponents.pop(); // The base file name is not part of the common directory path
99317             if (!commonPathComponents) {
99318                 // first file
99319                 commonPathComponents = sourcePathComponents;
99320                 return;
99321             }
99322             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
99323             for (var i = 0; i < n; i++) {
99324                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
99325                     if (i === 0) {
99326                         // Failed to find any common path component
99327                         return true;
99328                     }
99329                     // New common path found that is 0 -> i-1
99330                     commonPathComponents.length = i;
99331                     break;
99332                 }
99333             }
99334             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
99335             if (sourcePathComponents.length < commonPathComponents.length) {
99336                 commonPathComponents.length = sourcePathComponents.length;
99337             }
99338         });
99339         // A common path can not be found when paths span multiple drives on windows, for example
99340         if (failed) {
99341             return "";
99342         }
99343         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
99344             return currentDirectory;
99345         }
99346         return ts.getPathFromPathComponents(commonPathComponents);
99347     }
99348     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
99349     function createCompilerHost(options, setParentNodes) {
99350         return createCompilerHostWorker(options, setParentNodes);
99351     }
99352     ts.createCompilerHost = createCompilerHost;
99353     /*@internal*/
99354     // TODO(shkamat): update this after reworking ts build API
99355     function createCompilerHostWorker(options, setParentNodes, system) {
99356         if (system === void 0) { system = ts.sys; }
99357         var existingDirectories = ts.createMap();
99358         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
99359         function getSourceFile(fileName, languageVersion, onError) {
99360             var text;
99361             try {
99362                 ts.performance.mark("beforeIORead");
99363                 text = compilerHost.readFile(fileName);
99364                 ts.performance.mark("afterIORead");
99365                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
99366             }
99367             catch (e) {
99368                 if (onError) {
99369                     onError(e.message);
99370                 }
99371                 text = "";
99372             }
99373             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
99374         }
99375         function directoryExists(directoryPath) {
99376             if (existingDirectories.has(directoryPath)) {
99377                 return true;
99378             }
99379             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
99380                 existingDirectories.set(directoryPath, true);
99381                 return true;
99382             }
99383             return false;
99384         }
99385         function writeFile(fileName, data, writeByteOrderMark, onError) {
99386             try {
99387                 ts.performance.mark("beforeIOWrite");
99388                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
99389                 // the system.writeFile will do its own directory creation and
99390                 // the ensureDirectoriesExist call will always be redundant.
99391                 ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); });
99392                 ts.performance.mark("afterIOWrite");
99393                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
99394             }
99395             catch (e) {
99396                 if (onError) {
99397                     onError(e.message);
99398                 }
99399             }
99400         }
99401         var outputFingerprints;
99402         function writeFileWorker(fileName, data, writeByteOrderMark) {
99403             if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) {
99404                 system.writeFile(fileName, data, writeByteOrderMark);
99405                 return;
99406             }
99407             if (!outputFingerprints) {
99408                 outputFingerprints = ts.createMap();
99409             }
99410             var hash = system.createHash(data);
99411             var mtimeBefore = system.getModifiedTime(fileName);
99412             if (mtimeBefore) {
99413                 var fingerprint = outputFingerprints.get(fileName);
99414                 // If output has not been changed, and the file has no external modification
99415                 if (fingerprint &&
99416                     fingerprint.byteOrderMark === writeByteOrderMark &&
99417                     fingerprint.hash === hash &&
99418                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
99419                     return;
99420                 }
99421             }
99422             system.writeFile(fileName, data, writeByteOrderMark);
99423             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
99424             outputFingerprints.set(fileName, {
99425                 hash: hash,
99426                 byteOrderMark: writeByteOrderMark,
99427                 mtime: mtimeAfter
99428             });
99429         }
99430         function getDefaultLibLocation() {
99431             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
99432         }
99433         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
99434         var realpath = system.realpath && (function (path) { return system.realpath(path); });
99435         var compilerHost = {
99436             getSourceFile: getSourceFile,
99437             getDefaultLibLocation: getDefaultLibLocation,
99438             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
99439             writeFile: writeFile,
99440             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
99441             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
99442             getCanonicalFileName: getCanonicalFileName,
99443             getNewLine: function () { return newLine; },
99444             fileExists: function (fileName) { return system.fileExists(fileName); },
99445             readFile: function (fileName) { return system.readFile(fileName); },
99446             trace: function (s) { return system.write(s + newLine); },
99447             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
99448             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
99449             getDirectories: function (path) { return system.getDirectories(path); },
99450             realpath: realpath,
99451             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
99452             createDirectory: function (d) { return system.createDirectory(d); },
99453             createHash: ts.maybeBind(system, system.createHash)
99454         };
99455         return compilerHost;
99456     }
99457     ts.createCompilerHostWorker = createCompilerHostWorker;
99458     /*@internal*/
99459     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
99460         var originalReadFile = host.readFile;
99461         var originalFileExists = host.fileExists;
99462         var originalDirectoryExists = host.directoryExists;
99463         var originalCreateDirectory = host.createDirectory;
99464         var originalWriteFile = host.writeFile;
99465         var readFileCache = ts.createMap();
99466         var fileExistsCache = ts.createMap();
99467         var directoryExistsCache = ts.createMap();
99468         var sourceFileCache = ts.createMap();
99469         var readFileWithCache = function (fileName) {
99470             var key = toPath(fileName);
99471             var value = readFileCache.get(key);
99472             if (value !== undefined)
99473                 return value !== false ? value : undefined;
99474             return setReadFileCache(key, fileName);
99475         };
99476         var setReadFileCache = function (key, fileName) {
99477             var newValue = originalReadFile.call(host, fileName);
99478             readFileCache.set(key, newValue !== undefined ? newValue : false);
99479             return newValue;
99480         };
99481         host.readFile = function (fileName) {
99482             var key = toPath(fileName);
99483             var value = readFileCache.get(key);
99484             if (value !== undefined)
99485                 return value !== false ? value : undefined; // could be .d.ts from output
99486             // Cache json or buildInfo
99487             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
99488                 return originalReadFile.call(host, fileName);
99489             }
99490             return setReadFileCache(key, fileName);
99491         };
99492         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
99493             var key = toPath(fileName);
99494             var value = sourceFileCache.get(key);
99495             if (value)
99496                 return value;
99497             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
99498             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
99499                 sourceFileCache.set(key, sourceFile);
99500             }
99501             return sourceFile;
99502         } : undefined;
99503         // fileExists for any kind of extension
99504         host.fileExists = function (fileName) {
99505             var key = toPath(fileName);
99506             var value = fileExistsCache.get(key);
99507             if (value !== undefined)
99508                 return value;
99509             var newValue = originalFileExists.call(host, fileName);
99510             fileExistsCache.set(key, !!newValue);
99511             return newValue;
99512         };
99513         if (originalWriteFile) {
99514             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
99515                 var key = toPath(fileName);
99516                 fileExistsCache.delete(key);
99517                 var value = readFileCache.get(key);
99518                 if (value !== undefined && value !== data) {
99519                     readFileCache.delete(key);
99520                     sourceFileCache.delete(key);
99521                 }
99522                 else if (getSourceFileWithCache) {
99523                     var sourceFile = sourceFileCache.get(key);
99524                     if (sourceFile && sourceFile.text !== data) {
99525                         sourceFileCache.delete(key);
99526                     }
99527                 }
99528                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
99529             };
99530         }
99531         // directoryExists
99532         if (originalDirectoryExists && originalCreateDirectory) {
99533             host.directoryExists = function (directory) {
99534                 var key = toPath(directory);
99535                 var value = directoryExistsCache.get(key);
99536                 if (value !== undefined)
99537                     return value;
99538                 var newValue = originalDirectoryExists.call(host, directory);
99539                 directoryExistsCache.set(key, !!newValue);
99540                 return newValue;
99541             };
99542             host.createDirectory = function (directory) {
99543                 var key = toPath(directory);
99544                 directoryExistsCache.delete(key);
99545                 originalCreateDirectory.call(host, directory);
99546             };
99547         }
99548         return {
99549             originalReadFile: originalReadFile,
99550             originalFileExists: originalFileExists,
99551             originalDirectoryExists: originalDirectoryExists,
99552             originalCreateDirectory: originalCreateDirectory,
99553             originalWriteFile: originalWriteFile,
99554             getSourceFileWithCache: getSourceFileWithCache,
99555             readFileWithCache: readFileWithCache
99556         };
99557     }
99558     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
99559     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
99560         var diagnostics;
99561         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
99562         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
99563         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
99564         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
99565         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
99566         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
99567             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
99568         }
99569         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
99570     }
99571     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
99572     function formatDiagnostics(diagnostics, host) {
99573         var output = "";
99574         for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
99575             var diagnostic = diagnostics_2[_i];
99576             output += formatDiagnostic(diagnostic, host);
99577         }
99578         return output;
99579     }
99580     ts.formatDiagnostics = formatDiagnostics;
99581     function formatDiagnostic(diagnostic, host) {
99582         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
99583         if (diagnostic.file) {
99584             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
99585             var fileName = diagnostic.file.fileName;
99586             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
99587             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
99588         }
99589         return errorMessage;
99590     }
99591     ts.formatDiagnostic = formatDiagnostic;
99592     /** @internal */
99593     var ForegroundColorEscapeSequences;
99594     (function (ForegroundColorEscapeSequences) {
99595         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
99596         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
99597         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
99598         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
99599         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
99600     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
99601     var gutterStyleSequence = "\u001b[7m";
99602     var gutterSeparator = " ";
99603     var resetEscapeSequence = "\u001b[0m";
99604     var ellipsis = "...";
99605     var halfIndent = "  ";
99606     var indent = "    ";
99607     function getCategoryFormat(category) {
99608         switch (category) {
99609             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
99610             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
99611             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
99612             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
99613         }
99614     }
99615     /** @internal */
99616     function formatColorAndReset(text, formatStyle) {
99617         return formatStyle + text + resetEscapeSequence;
99618     }
99619     ts.formatColorAndReset = formatColorAndReset;
99620     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
99621         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
99622         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
99623         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
99624         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
99625         var gutterWidth = (lastLine + 1 + "").length;
99626         if (hasMoreThanFiveLines) {
99627             gutterWidth = Math.max(ellipsis.length, gutterWidth);
99628         }
99629         var context = "";
99630         for (var i = firstLine; i <= lastLine; i++) {
99631             context += host.getNewLine();
99632             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
99633             // so we'll skip ahead to the second-to-last line.
99634             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
99635                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
99636                 i = lastLine - 1;
99637             }
99638             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
99639             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
99640             var lineContent = file.text.slice(lineStart, lineEnd);
99641             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
99642             lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
99643             // Output the gutter and the actual contents of the line.
99644             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
99645             context += lineContent + host.getNewLine();
99646             // Output the gutter and the error span for the line using tildes.
99647             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
99648             context += squiggleColor;
99649             if (i === firstLine) {
99650                 // If we're on the last line, then limit it to the last character of the last line.
99651                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
99652                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
99653                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
99654                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
99655             }
99656             else if (i === lastLine) {
99657                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
99658             }
99659             else {
99660                 // Squiggle the entire line.
99661                 context += lineContent.replace(/./g, "~");
99662             }
99663             context += resetEscapeSequence;
99664         }
99665         return context;
99666     }
99667     /* @internal */
99668     function formatLocation(file, start, host, color) {
99669         if (color === void 0) { color = formatColorAndReset; }
99670         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
99671         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
99672         var output = "";
99673         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
99674         output += ":";
99675         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
99676         output += ":";
99677         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
99678         return output;
99679     }
99680     ts.formatLocation = formatLocation;
99681     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
99682         var output = "";
99683         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
99684             var diagnostic = diagnostics_3[_i];
99685             if (diagnostic.file) {
99686                 var file = diagnostic.file, start = diagnostic.start;
99687                 output += formatLocation(file, start, host); // TODO: GH#18217
99688                 output += " - ";
99689             }
99690             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
99691             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
99692             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
99693             if (diagnostic.file) {
99694                 output += host.getNewLine();
99695                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
99696                 if (diagnostic.relatedInformation) {
99697                     output += host.getNewLine();
99698                     for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
99699                         var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
99700                         if (file) {
99701                             output += host.getNewLine();
99702                             output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
99703                             output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
99704                         }
99705                         output += host.getNewLine();
99706                         output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
99707                     }
99708                 }
99709             }
99710             output += host.getNewLine();
99711         }
99712         return output;
99713     }
99714     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
99715     function flattenDiagnosticMessageText(diag, newLine, indent) {
99716         if (indent === void 0) { indent = 0; }
99717         if (ts.isString(diag)) {
99718             return diag;
99719         }
99720         else if (diag === undefined) {
99721             return "";
99722         }
99723         var result = "";
99724         if (indent) {
99725             result += newLine;
99726             for (var i = 0; i < indent; i++) {
99727                 result += "  ";
99728             }
99729         }
99730         result += diag.messageText;
99731         indent++;
99732         if (diag.next) {
99733             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
99734                 var kid = _a[_i];
99735                 result += flattenDiagnosticMessageText(kid, newLine, indent);
99736             }
99737         }
99738         return result;
99739     }
99740     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
99741     /* @internal */
99742     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
99743         if (names.length === 0) {
99744             return [];
99745         }
99746         var resolutions = [];
99747         var cache = ts.createMap();
99748         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
99749             var name = names_2[_i];
99750             var result = void 0;
99751             if (cache.has(name)) {
99752                 result = cache.get(name);
99753             }
99754             else {
99755                 cache.set(name, result = loader(name, containingFile, redirectedReference));
99756             }
99757             resolutions.push(result);
99758         }
99759         return resolutions;
99760     }
99761     ts.loadWithLocalCache = loadWithLocalCache;
99762     /* @internal */
99763     ts.inferredTypesContainingFile = "__inferred type names__.ts";
99764     /**
99765      * Determines if program structure is upto date or needs to be recreated
99766      */
99767     /* @internal */
99768     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
99769         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
99770         if (!program || hasChangedAutomaticTypeDirectiveNames) {
99771             return false;
99772         }
99773         // If root file names don't match
99774         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
99775             return false;
99776         }
99777         var seenResolvedRefs;
99778         // If project references don't match
99779         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
99780             return false;
99781         }
99782         // If any file is not up-to-date, then the whole program is not up-to-date
99783         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
99784             return false;
99785         }
99786         // If any of the missing file paths are now created
99787         if (program.getMissingFilePaths().some(fileExists)) {
99788             return false;
99789         }
99790         var currentOptions = program.getCompilerOptions();
99791         // If the compilation settings do no match, then the program is not up-to-date
99792         if (!ts.compareDataObjects(currentOptions, newOptions)) {
99793             return false;
99794         }
99795         // If everything matches but the text of config file is changed,
99796         // error locations can change for program options, so update the program
99797         if (currentOptions.configFile && newOptions.configFile) {
99798             return currentOptions.configFile.text === newOptions.configFile.text;
99799         }
99800         return true;
99801         function sourceFileNotUptoDate(sourceFile) {
99802             return !sourceFileVersionUptoDate(sourceFile) ||
99803                 hasInvalidatedResolution(sourceFile.path);
99804         }
99805         function sourceFileVersionUptoDate(sourceFile) {
99806             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
99807         }
99808         function projectReferenceUptoDate(oldRef, newRef, index) {
99809             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
99810                 return false;
99811             }
99812             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
99813         }
99814         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
99815             if (oldResolvedRef) {
99816                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
99817                     // Assume true
99818                     return true;
99819                 }
99820                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
99821                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
99822                     return false;
99823                 }
99824                 // Add to seen before checking the referenced paths of this config file
99825                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
99826                 // If child project references are upto date, this project reference is uptodate
99827                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
99828                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
99829                 });
99830             }
99831             // In old program, not able to resolve project reference path,
99832             // so if config file doesnt exist, it is uptodate.
99833             return !fileExists(resolveProjectReferencePath(oldRef));
99834         }
99835     }
99836     ts.isProgramUptoDate = isProgramUptoDate;
99837     function getConfigFileParsingDiagnostics(configFileParseResult) {
99838         return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
99839             configFileParseResult.errors;
99840     }
99841     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
99842     /**
99843      * Determine if source file needs to be re-created even if its text hasn't changed
99844      */
99845     function shouldProgramCreateNewSourceFiles(program, newOptions) {
99846         if (!program)
99847             return false;
99848         // If any compiler options change, we can't reuse old source file even if version match
99849         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
99850         var oldOptions = program.getCompilerOptions();
99851         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
99852             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
99853         });
99854     }
99855     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
99856         return {
99857             rootNames: rootNames,
99858             options: options,
99859             host: host,
99860             oldProgram: oldProgram,
99861             configFileParsingDiagnostics: configFileParsingDiagnostics
99862         };
99863     }
99864     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
99865         var _a;
99866         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
99867         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
99868         var oldProgram = createProgramOptions.oldProgram;
99869         var processingDefaultLibFiles;
99870         var processingOtherFiles;
99871         var files;
99872         var symlinks;
99873         var commonSourceDirectory;
99874         var diagnosticsProducingTypeChecker;
99875         var noDiagnosticsTypeChecker;
99876         var classifiableNames;
99877         var ambientModuleNameToUnmodifiedFileName = ts.createMap();
99878         // Todo:: Use this to report why file was included in --extendedDiagnostics
99879         var refFileMap;
99880         var cachedBindAndCheckDiagnosticsForFile = {};
99881         var cachedDeclarationDiagnosticsForFile = {};
99882         var resolvedTypeReferenceDirectives = ts.createMap();
99883         var fileProcessingDiagnostics = ts.createDiagnosticCollection();
99884         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
99885         // This works as imported modules are discovered recursively in a depth first manner, specifically:
99886         // - For each root file, findSourceFile is called.
99887         // - This calls processImportedModules for each module imported in the source file.
99888         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
99889         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
99890         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
99891         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
99892         var currentNodeModulesDepth = 0;
99893         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
99894         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
99895         var modulesWithElidedImports = ts.createMap();
99896         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
99897         var sourceFilesFoundSearchingNodeModules = ts.createMap();
99898         ts.performance.mark("beforeProgram");
99899         var host = createProgramOptions.host || createCompilerHost(options);
99900         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
99901         var skipDefaultLib = options.noLib;
99902         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
99903         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
99904         var programDiagnostics = ts.createDiagnosticCollection();
99905         var currentDirectory = host.getCurrentDirectory();
99906         var supportedExtensions = ts.getSupportedExtensions(options);
99907         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
99908         // Map storing if there is emit blocking diagnostics for given input
99909         var hasEmitBlockingDiagnostics = ts.createMap();
99910         var _compilerOptionsObjectLiteralSyntax;
99911         var moduleResolutionCache;
99912         var actualResolveModuleNamesWorker;
99913         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
99914         if (host.resolveModuleNames) {
99915             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
99916                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
99917                 if (!resolved || resolved.extension !== undefined) {
99918                     return resolved;
99919                 }
99920                 var withExtension = ts.clone(resolved);
99921                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
99922                 return withExtension;
99923             }); };
99924         }
99925         else {
99926             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
99927             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
99928             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
99929         }
99930         var actualResolveTypeReferenceDirectiveNamesWorker;
99931         if (host.resolveTypeReferenceDirectives) {
99932             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
99933         }
99934         else {
99935             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
99936             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
99937         }
99938         // Map from a stringified PackageId to the source file with that id.
99939         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
99940         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
99941         var packageIdToSourceFile = ts.createMap();
99942         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
99943         var sourceFileToPackageName = ts.createMap();
99944         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
99945         var redirectTargetsMap = ts.createMultiMap();
99946         /**
99947          * map with
99948          * - SourceFile if present
99949          * - false if sourceFile missing for source of project reference redirect
99950          * - undefined otherwise
99951          */
99952         var filesByName = ts.createMap();
99953         var missingFilePaths;
99954         // stores 'filename -> file association' ignoring case
99955         // used to track cases when two file names differ only in casing
99956         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
99957         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
99958         var resolvedProjectReferences;
99959         var projectReferenceRedirects;
99960         var mapFromFileToProjectReferenceRedirects;
99961         var mapFromToProjectReferenceRedirectSource;
99962         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
99963             !options.disableSourceOfProjectReferenceRedirect;
99964         var _b = updateHostForUseSourceOfProjectReferenceRedirect({
99965             compilerHost: host,
99966             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
99967             toPath: toPath,
99968             getResolvedProjectReferences: getResolvedProjectReferences,
99969             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
99970             forEachResolvedProjectReference: forEachResolvedProjectReference
99971         }), onProgramCreateComplete = _b.onProgramCreateComplete, fileExists = _b.fileExists;
99972         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
99973         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
99974         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
99975         var structuralIsReused;
99976         structuralIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
99977         if (structuralIsReused !== 2 /* Completely */) {
99978             processingDefaultLibFiles = [];
99979             processingOtherFiles = [];
99980             if (projectReferences) {
99981                 if (!resolvedProjectReferences) {
99982                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
99983                 }
99984                 if (rootNames.length) {
99985                     for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
99986                         var parsedRef = resolvedProjectReferences_1[_i];
99987                         if (!parsedRef)
99988                             continue;
99989                         var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
99990                         if (useSourceOfProjectReferenceRedirect) {
99991                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
99992                                 for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) {
99993                                     var fileName = _d[_c];
99994                                     processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99995                                 }
99996                             }
99997                         }
99998                         else {
99999                             if (out) {
100000                                 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
100001                             }
100002                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
100003                                 for (var _e = 0, _f = parsedRef.commandLine.fileNames; _e < _f.length; _e++) {
100004                                     var fileName = _f[_e];
100005                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
100006                                         processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
100007                                     }
100008                                 }
100009                             }
100010                         }
100011                     }
100012                 }
100013             }
100014             ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
100015             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
100016             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
100017             if (typeReferences.length) {
100018                 // This containingFilename needs to match with the one used in managed-side
100019                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
100020                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
100021                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
100022                 for (var i = 0; i < typeReferences.length; i++) {
100023                     processTypeReferenceDirective(typeReferences[i], resolutions[i]);
100024                 }
100025             }
100026             // Do not process the default library if:
100027             //  - The '--noLib' flag is used.
100028             //  - A 'no-default-lib' reference comment is encountered in
100029             //      processing the root files.
100030             if (rootNames.length && !skipDefaultLib) {
100031                 // If '--lib' is not specified, include default library file according to '--target'
100032                 // otherwise, using options specified in '--lib' instead of '--target' default library file
100033                 var defaultLibraryFileName = getDefaultLibraryFileName();
100034                 if (!options.lib && defaultLibraryFileName) {
100035                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100036                 }
100037                 else {
100038                     ts.forEach(options.lib, function (libFileName) {
100039                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100040                     });
100041                 }
100042             }
100043             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
100044                 var path = _a[0], file = _a[1];
100045                 return file === undefined ? path : undefined;
100046             }));
100047             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
100048             processingDefaultLibFiles = undefined;
100049             processingOtherFiles = undefined;
100050         }
100051         ts.Debug.assert(!!missingFilePaths);
100052         // Release any files we have acquired in the old program but are
100053         // not part of the new program.
100054         if (oldProgram && host.onReleaseOldSourceFile) {
100055             var oldSourceFiles = oldProgram.getSourceFiles();
100056             for (var _g = 0, oldSourceFiles_1 = oldSourceFiles; _g < oldSourceFiles_1.length; _g++) {
100057                 var oldSourceFile = oldSourceFiles_1[_g];
100058                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
100059                 if (shouldCreateNewSourceFile || !newFile ||
100060                     // old file wasnt redirect but new file is
100061                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
100062                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
100063                 }
100064             }
100065             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
100066                 if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
100067                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
100068                 }
100069             });
100070         }
100071         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
100072         oldProgram = undefined;
100073         var program = {
100074             getRootFileNames: function () { return rootNames; },
100075             getSourceFile: getSourceFile,
100076             getSourceFileByPath: getSourceFileByPath,
100077             getSourceFiles: function () { return files; },
100078             getMissingFilePaths: function () { return missingFilePaths; },
100079             getRefFileMap: function () { return refFileMap; },
100080             getFilesByNameMap: function () { return filesByName; },
100081             getCompilerOptions: function () { return options; },
100082             getSyntacticDiagnostics: getSyntacticDiagnostics,
100083             getOptionsDiagnostics: getOptionsDiagnostics,
100084             getGlobalDiagnostics: getGlobalDiagnostics,
100085             getSemanticDiagnostics: getSemanticDiagnostics,
100086             getSuggestionDiagnostics: getSuggestionDiagnostics,
100087             getDeclarationDiagnostics: getDeclarationDiagnostics,
100088             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
100089             getProgramDiagnostics: getProgramDiagnostics,
100090             getTypeChecker: getTypeChecker,
100091             getClassifiableNames: getClassifiableNames,
100092             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
100093             getCommonSourceDirectory: getCommonSourceDirectory,
100094             emit: emit,
100095             getCurrentDirectory: function () { return currentDirectory; },
100096             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
100097             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
100098             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
100099             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
100100             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
100101             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
100102             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
100103             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
100104             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100105             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
100106             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
100107             getSourceFileFromReference: getSourceFileFromReference,
100108             getLibFileFromReference: getLibFileFromReference,
100109             sourceFileToPackageName: sourceFileToPackageName,
100110             redirectTargetsMap: redirectTargetsMap,
100111             isEmittedFile: isEmittedFile,
100112             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
100113             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
100114             getProjectReferences: getProjectReferences,
100115             getResolvedProjectReferences: getResolvedProjectReferences,
100116             getProjectReferenceRedirect: getProjectReferenceRedirect,
100117             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100118             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
100119             forEachResolvedProjectReference: forEachResolvedProjectReference,
100120             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100121             emitBuildInfo: emitBuildInfo,
100122             fileExists: fileExists,
100123             getProbableSymlinks: getProbableSymlinks,
100124             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100125         };
100126         onProgramCreateComplete();
100127         verifyCompilerOptions();
100128         ts.performance.mark("afterProgram");
100129         ts.performance.measure("Program", "beforeProgram", "afterProgram");
100130         return program;
100131         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference) {
100132             ts.performance.mark("beforeResolveModule");
100133             var result = actualResolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference);
100134             ts.performance.mark("afterResolveModule");
100135             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
100136             return result;
100137         }
100138         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference) {
100139             ts.performance.mark("beforeResolveTypeReference");
100140             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference);
100141             ts.performance.mark("afterResolveTypeReference");
100142             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
100143             return result;
100144         }
100145         function compareDefaultLibFiles(a, b) {
100146             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
100147         }
100148         function getDefaultLibFilePriority(a) {
100149             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
100150                 var basename = ts.getBaseFileName(a.fileName);
100151                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
100152                     return 0;
100153                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
100154                 var index = ts.libs.indexOf(name);
100155                 if (index !== -1)
100156                     return index + 1;
100157             }
100158             return ts.libs.length + 2;
100159         }
100160         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
100161             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
100162         }
100163         function toPath(fileName) {
100164             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
100165         }
100166         function getCommonSourceDirectory() {
100167             if (commonSourceDirectory === undefined) {
100168                 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
100169                 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
100170                     // If a rootDir is specified use it as the commonSourceDirectory
100171                     commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
100172                 }
100173                 else if (options.composite && options.configFilePath) {
100174                     // Project compilations never infer their root from the input source paths
100175                     commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
100176                     checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
100177                 }
100178                 else {
100179                     commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
100180                 }
100181                 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
100182                     // Make sure directory path ends with directory separator so this string can directly
100183                     // used to replace with "" to get the relative path of the source file and the relative path doesn't
100184                     // start with / making it rooted path
100185                     commonSourceDirectory += ts.directorySeparator;
100186                 }
100187             }
100188             return commonSourceDirectory;
100189         }
100190         function getClassifiableNames() {
100191             if (!classifiableNames) {
100192                 // Initialize a checker so that all our files are bound.
100193                 getTypeChecker();
100194                 classifiableNames = ts.createUnderscoreEscapedMap();
100195                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
100196                     var sourceFile = files_2[_i];
100197                     ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
100198                 }
100199             }
100200             return classifiableNames;
100201         }
100202         function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
100203             if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
100204                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
100205                 // the best we can do is fallback to the default logic.
100206                 return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
100207             }
100208             var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
100209             if (oldSourceFile !== file && file.resolvedModules) {
100210                 // `file` was created for the new program.
100211                 //
100212                 // We only set `file.resolvedModules` via work from the current function,
100213                 // so it is defined iff we already called the current function on `file`.
100214                 // That call happened no later than the creation of the `file` object,
100215                 // which per above occurred during the current program creation.
100216                 // Since we assume the filesystem does not change during program creation,
100217                 // it is safe to reuse resolutions from the earlier call.
100218                 var result_11 = [];
100219                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
100220                     var moduleName = moduleNames_1[_i];
100221                     var resolvedModule = file.resolvedModules.get(moduleName);
100222                     result_11.push(resolvedModule);
100223                 }
100224                 return result_11;
100225             }
100226             // At this point, we know at least one of the following hold:
100227             // - file has local declarations for ambient modules
100228             // - old program state is available
100229             // With this information, we can infer some module resolutions without performing resolution.
100230             /** An ordered list of module names for which we cannot recover the resolution. */
100231             var unknownModuleNames;
100232             /**
100233              * The indexing of elements in this list matches that of `moduleNames`.
100234              *
100235              * Before combining results, result[i] is in one of the following states:
100236              * * undefined: needs to be recomputed,
100237              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
100238              * Needs to be reset to undefined before returning,
100239              * * ResolvedModuleFull instance: can be reused.
100240              */
100241             var result;
100242             var reusedNames;
100243             /** A transient placeholder used to mark predicted resolution in the result list. */
100244             var predictedToResolveToAmbientModuleMarker = {};
100245             for (var i = 0; i < moduleNames.length; i++) {
100246                 var moduleName = moduleNames[i];
100247                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
100248                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
100249                     var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
100250                     if (oldResolvedModule) {
100251                         if (ts.isTraceEnabled(options, host)) {
100252                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
100253                         }
100254                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
100255                         (reusedNames || (reusedNames = [])).push(moduleName);
100256                         continue;
100257                     }
100258                 }
100259                 // We know moduleName resolves to an ambient module provided that moduleName:
100260                 // - is in the list of ambient modules locally declared in the current source file.
100261                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
100262                 //   (so the same module declaration will land in the new program)
100263                 var resolvesToAmbientModuleInNonModifiedFile = false;
100264                 if (ts.contains(file.ambientModuleNames, moduleName)) {
100265                     resolvesToAmbientModuleInNonModifiedFile = true;
100266                     if (ts.isTraceEnabled(options, host)) {
100267                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
100268                     }
100269                 }
100270                 else {
100271                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
100272                 }
100273                 if (resolvesToAmbientModuleInNonModifiedFile) {
100274                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
100275                 }
100276                 else {
100277                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
100278                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
100279                 }
100280             }
100281             var resolutions = unknownModuleNames && unknownModuleNames.length
100282                 ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
100283                 : ts.emptyArray;
100284             // Combine results of resolutions and predicted results
100285             if (!result) {
100286                 // There were no unresolved/ambient resolutions.
100287                 ts.Debug.assert(resolutions.length === moduleNames.length);
100288                 return resolutions;
100289             }
100290             var j = 0;
100291             for (var i = 0; i < result.length; i++) {
100292                 if (result[i]) {
100293                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
100294                     // If it is the former, we can leave it as is.
100295                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
100296                         result[i] = undefined; // TODO: GH#18217
100297                     }
100298                 }
100299                 else {
100300                     result[i] = resolutions[j];
100301                     j++;
100302                 }
100303             }
100304             ts.Debug.assert(j === resolutions.length);
100305             return result;
100306             // If we change our policy of rechecking failed lookups on each program create,
100307             // we should adjust the value returned here.
100308             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
100309                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
100310                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
100311                 if (resolutionToFile && resolvedFile) {
100312                     // In the old program, we resolved to an ambient module that was in the same
100313                     //   place as we expected to find an actual module file.
100314                     // We actually need to return 'false' here even though this seems like a 'true' case
100315                     //   because the normal module resolution algorithm will find this anyway.
100316                     return false;
100317                 }
100318                 // at least one of declarations should come from non-modified source file
100319                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
100320                 if (!unmodifiedFile) {
100321                     return false;
100322                 }
100323                 if (ts.isTraceEnabled(options, host)) {
100324                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
100325                 }
100326                 return true;
100327             }
100328         }
100329         function canReuseProjectReferences() {
100330             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
100331                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
100332                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
100333                 if (oldResolvedRef) {
100334                     // Resolved project reference has gone missing or changed
100335                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
100336                 }
100337                 else {
100338                     // A previously-unresolved reference may be resolved now
100339                     return newResolvedRef !== undefined;
100340                 }
100341             }, function (oldProjectReferences, parent) {
100342                 // If array of references is changed, we cant resue old program
100343                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
100344                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
100345             });
100346         }
100347         function tryReuseStructureFromOldProgram() {
100348             if (!oldProgram) {
100349                 return 0 /* Not */;
100350             }
100351             // check properties that can affect structure of the program or module resolution strategy
100352             // if any of these properties has changed - structure cannot be reused
100353             var oldOptions = oldProgram.getCompilerOptions();
100354             if (ts.changesAffectModuleResolution(oldOptions, options)) {
100355                 return oldProgram.structureIsReused = 0 /* Not */;
100356             }
100357             ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
100358             // there is an old program, check if we can reuse its structure
100359             var oldRootNames = oldProgram.getRootFileNames();
100360             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
100361                 return oldProgram.structureIsReused = 0 /* Not */;
100362             }
100363             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
100364                 return oldProgram.structureIsReused = 0 /* Not */;
100365             }
100366             // Check if any referenced project tsconfig files are different
100367             if (!canReuseProjectReferences()) {
100368                 return oldProgram.structureIsReused = 0 /* Not */;
100369             }
100370             if (projectReferences) {
100371                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
100372             }
100373             // check if program source files has changed in the way that can affect structure of the program
100374             var newSourceFiles = [];
100375             var modifiedSourceFiles = [];
100376             oldProgram.structureIsReused = 2 /* Completely */;
100377             // If the missing file paths are now present, it can change the progam structure,
100378             // and hence cant reuse the structure.
100379             // This is same as how we dont reuse the structure if one of the file from old program is now missing
100380             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
100381                 return oldProgram.structureIsReused = 0 /* Not */;
100382             }
100383             var oldSourceFiles = oldProgram.getSourceFiles();
100384             var SeenPackageName;
100385             (function (SeenPackageName) {
100386                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
100387                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
100388             })(SeenPackageName || (SeenPackageName = {}));
100389             var seenPackageNames = ts.createMap();
100390             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
100391                 var oldSourceFile = oldSourceFiles_2[_i];
100392                 var newSourceFile = host.getSourceFileByPath
100393                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
100394                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
100395                 if (!newSourceFile) {
100396                     return oldProgram.structureIsReused = 0 /* Not */;
100397                 }
100398                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
100399                 var fileChanged = void 0;
100400                 if (oldSourceFile.redirectInfo) {
100401                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
100402                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
100403                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
100404                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
100405                         return oldProgram.structureIsReused = 0 /* Not */;
100406                     }
100407                     fileChanged = false;
100408                     newSourceFile = oldSourceFile; // Use the redirect.
100409                 }
100410                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
100411                     // If a redirected-to source file changes, the redirect may be broken.
100412                     if (newSourceFile !== oldSourceFile) {
100413                         return oldProgram.structureIsReused = 0 /* Not */;
100414                     }
100415                     fileChanged = false;
100416                 }
100417                 else {
100418                     fileChanged = newSourceFile !== oldSourceFile;
100419                 }
100420                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
100421                 newSourceFile.path = oldSourceFile.path;
100422                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
100423                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
100424                 newSourceFile.fileName = oldSourceFile.fileName;
100425                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
100426                 if (packageName !== undefined) {
100427                     // If there are 2 different source files for the same package name and at least one of them changes,
100428                     // they might become redirects. So we must rebuild the program.
100429                     var prevKind = seenPackageNames.get(packageName);
100430                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
100431                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
100432                         return oldProgram.structureIsReused = 0 /* Not */;
100433                     }
100434                     seenPackageNames.set(packageName, newKind);
100435                 }
100436                 if (fileChanged) {
100437                     // The `newSourceFile` object was created for the new program.
100438                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
100439                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
100440                         return oldProgram.structureIsReused = 0 /* Not */;
100441                     }
100442                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
100443                         // value of no-default-lib has changed
100444                         // this will affect if default library is injected into the list of files
100445                         oldProgram.structureIsReused = 1 /* SafeModules */;
100446                     }
100447                     // check tripleslash references
100448                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
100449                         // tripleslash references has changed
100450                         oldProgram.structureIsReused = 1 /* SafeModules */;
100451                     }
100452                     // check imports and module augmentations
100453                     collectExternalModuleReferences(newSourceFile);
100454                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
100455                         // imports has changed
100456                         oldProgram.structureIsReused = 1 /* SafeModules */;
100457                     }
100458                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
100459                         // moduleAugmentations has changed
100460                         oldProgram.structureIsReused = 1 /* SafeModules */;
100461                     }
100462                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
100463                         // dynamicImport has changed
100464                         oldProgram.structureIsReused = 1 /* SafeModules */;
100465                     }
100466                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
100467                         // 'types' references has changed
100468                         oldProgram.structureIsReused = 1 /* SafeModules */;
100469                     }
100470                     // tentatively approve the file
100471                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100472                 }
100473                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
100474                     // 'module/types' references could have changed
100475                     oldProgram.structureIsReused = 1 /* SafeModules */;
100476                     // add file to the modified list so that we will resolve it later
100477                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100478                 }
100479                 // if file has passed all checks it should be safe to reuse it
100480                 newSourceFiles.push(newSourceFile);
100481             }
100482             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100483                 return oldProgram.structureIsReused;
100484             }
100485             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
100486             for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
100487                 var oldFile = oldSourceFiles_3[_a];
100488                 if (!ts.contains(modifiedFiles, oldFile)) {
100489                     for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
100490                         var moduleName = _c[_b];
100491                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
100492                     }
100493                 }
100494             }
100495             // try to verify results of module resolution
100496             for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
100497                 var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
100498                 var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
100499                 var moduleNames = getModuleNames(newSourceFile);
100500                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
100501                 // ensure that module resolution results are still correct
100502                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
100503                 if (resolutionsChanged) {
100504                     oldProgram.structureIsReused = 1 /* SafeModules */;
100505                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
100506                 }
100507                 else {
100508                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
100509                 }
100510                 if (resolveTypeReferenceDirectiveNamesWorker) {
100511                     // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
100512                     var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
100513                     var resolutions_1 = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
100514                     // ensure that types resolutions are still correct
100515                     var resolutionsChanged_1 = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions_1, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
100516                     if (resolutionsChanged_1) {
100517                         oldProgram.structureIsReused = 1 /* SafeModules */;
100518                         newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions_1);
100519                     }
100520                     else {
100521                         newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
100522                     }
100523                 }
100524             }
100525             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100526                 return oldProgram.structureIsReused;
100527             }
100528             if (host.hasChangedAutomaticTypeDirectiveNames) {
100529                 return oldProgram.structureIsReused = 1 /* SafeModules */;
100530             }
100531             missingFilePaths = oldProgram.getMissingFilePaths();
100532             refFileMap = oldProgram.getRefFileMap();
100533             // update fileName -> file mapping
100534             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
100535             for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) {
100536                 var newSourceFile = newSourceFiles_1[_f];
100537                 filesByName.set(newSourceFile.path, newSourceFile);
100538             }
100539             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
100540             oldFilesByNameMap.forEach(function (oldFile, path) {
100541                 if (!oldFile) {
100542                     filesByName.set(path, oldFile);
100543                     return;
100544                 }
100545                 if (oldFile.path === path) {
100546                     // Set the file as found during node modules search if it was found that way in old progra,
100547                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
100548                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
100549                     }
100550                     return;
100551                 }
100552                 filesByName.set(path, filesByName.get(oldFile.path));
100553             });
100554             files = newSourceFiles;
100555             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
100556             for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) {
100557                 var modifiedFile = modifiedSourceFiles_2[_g];
100558                 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
100559             }
100560             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
100561             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
100562             redirectTargetsMap = oldProgram.redirectTargetsMap;
100563             return oldProgram.structureIsReused = 2 /* Completely */;
100564         }
100565         function getEmitHost(writeFileCallback) {
100566             return {
100567                 getPrependNodes: getPrependNodes,
100568                 getCanonicalFileName: getCanonicalFileName,
100569                 getCommonSourceDirectory: program.getCommonSourceDirectory,
100570                 getCompilerOptions: program.getCompilerOptions,
100571                 getCurrentDirectory: function () { return currentDirectory; },
100572                 getNewLine: function () { return host.getNewLine(); },
100573                 getSourceFile: program.getSourceFile,
100574                 getSourceFileByPath: program.getSourceFileByPath,
100575                 getSourceFiles: program.getSourceFiles,
100576                 getLibFileFromReference: program.getLibFileFromReference,
100577                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100578                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100579                 getProjectReferenceRedirect: getProjectReferenceRedirect,
100580                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100581                 getProbableSymlinks: getProbableSymlinks,
100582                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
100583                 isEmitBlocked: isEmitBlocked,
100584                 readFile: function (f) { return host.readFile(f); },
100585                 fileExists: function (f) {
100586                     // Use local caches
100587                     var path = toPath(f);
100588                     if (getSourceFileByPath(path))
100589                         return true;
100590                     if (ts.contains(missingFilePaths, path))
100591                         return false;
100592                     // Before falling back to the host
100593                     return host.fileExists(f);
100594                 },
100595                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100596                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
100597                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
100598                 redirectTargetsMap: redirectTargetsMap,
100599             };
100600         }
100601         function emitBuildInfo(writeFileCallback) {
100602             ts.Debug.assert(!options.out && !options.outFile);
100603             ts.performance.mark("beforeEmit");
100604             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
100605             /*targetSourceFile*/ undefined, 
100606             /*transformers*/ ts.noTransformers, 
100607             /*emitOnlyDtsFiles*/ false, 
100608             /*onlyBuildInfo*/ true);
100609             ts.performance.mark("afterEmit");
100610             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100611             return emitResult;
100612         }
100613         function getResolvedProjectReferences() {
100614             return resolvedProjectReferences;
100615         }
100616         function getProjectReferences() {
100617             return projectReferences;
100618         }
100619         function getPrependNodes() {
100620             return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
100621                 var path = toPath(fileName);
100622                 var sourceFile = getSourceFileByPath(path);
100623                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
100624             });
100625         }
100626         function isSourceFileFromExternalLibrary(file) {
100627             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
100628         }
100629         function isSourceFileDefaultLibrary(file) {
100630             if (file.hasNoDefaultLib) {
100631                 return true;
100632             }
100633             if (!options.noLib) {
100634                 return false;
100635             }
100636             // If '--lib' is not specified, include default library file according to '--target'
100637             // otherwise, using options specified in '--lib' instead of '--target' default library file
100638             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
100639             if (!options.lib) {
100640                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
100641             }
100642             else {
100643                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
100644             }
100645         }
100646         function getDiagnosticsProducingTypeChecker() {
100647             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
100648         }
100649         function dropDiagnosticsProducingTypeChecker() {
100650             diagnosticsProducingTypeChecker = undefined;
100651         }
100652         function getTypeChecker() {
100653             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
100654         }
100655         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
100656             return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
100657         }
100658         function isEmitBlocked(emitFileName) {
100659             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
100660         }
100661         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
100662             if (!forceDtsEmit) {
100663                 var result = handleNoEmitOptions(program, sourceFile, cancellationToken);
100664                 if (result)
100665                     return result;
100666             }
100667             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
100668             // any cost associated with it (like type checking) are appropriate associated with
100669             // the type-checking counter.
100670             //
100671             // If the -out option is specified, we should not pass the source file to getEmitResolver.
100672             // This is because in the -out scenario all files need to be emitted, and therefore all
100673             // files need to be type checked. And the way to specify that all files need to be type
100674             // checked is to not pass the file to getEmitResolver.
100675             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
100676             ts.performance.mark("beforeEmit");
100677             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
100678             /*onlyBuildInfo*/ false, forceDtsEmit);
100679             ts.performance.mark("afterEmit");
100680             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100681             return emitResult;
100682         }
100683         function getSourceFile(fileName) {
100684             return getSourceFileByPath(toPath(fileName));
100685         }
100686         function getSourceFileByPath(path) {
100687             return filesByName.get(path) || undefined;
100688         }
100689         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
100690             if (sourceFile) {
100691                 return getDiagnostics(sourceFile, cancellationToken);
100692             }
100693             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
100694                 if (cancellationToken) {
100695                     cancellationToken.throwIfCancellationRequested();
100696                 }
100697                 return getDiagnostics(sourceFile, cancellationToken);
100698             }));
100699         }
100700         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
100701             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
100702         }
100703         function getSemanticDiagnostics(sourceFile, cancellationToken) {
100704             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
100705         }
100706         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
100707             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
100708         }
100709         function getProgramDiagnostics(sourceFile) {
100710             if (ts.skipTypeChecking(sourceFile, options, program)) {
100711                 return ts.emptyArray;
100712             }
100713             var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
100714             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
100715             return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
100716         }
100717         function getMergedProgramDiagnostics(sourceFile) {
100718             var _a;
100719             var allDiagnostics = [];
100720             for (var _i = 1; _i < arguments.length; _i++) {
100721                 allDiagnostics[_i - 1] = arguments[_i];
100722             }
100723             var flatDiagnostics = ts.flatten(allDiagnostics);
100724             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100725                 return flatDiagnostics;
100726             }
100727             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
100728         }
100729         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
100730             var options = program.getCompilerOptions();
100731             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
100732             if (!sourceFile || options.out || options.outFile) {
100733                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
100734             }
100735             else {
100736                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
100737             }
100738         }
100739         function getSyntacticDiagnosticsForFile(sourceFile) {
100740             // For JavaScript files, we report semantic errors for using TypeScript-only
100741             // constructs from within a JavaScript file as syntactic errors.
100742             if (ts.isSourceFileJS(sourceFile)) {
100743                 if (!sourceFile.additionalSyntacticDiagnostics) {
100744                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
100745                 }
100746                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
100747             }
100748             return sourceFile.parseDiagnostics;
100749         }
100750         function runWithCancellationToken(func) {
100751             try {
100752                 return func();
100753             }
100754             catch (e) {
100755                 if (e instanceof ts.OperationCanceledException) {
100756                     // We were canceled while performing the operation.  Because our type checker
100757                     // might be a bad state, we need to throw it away.
100758                     //
100759                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
100760                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
100761                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
100762                     // cancel when the user has made a change anyways.  And, in that case, we (the
100763                     // program instance) will get thrown away anyways.  So trying to keep one of
100764                     // these type checkers alive doesn't serve much purpose.
100765                     noDiagnosticsTypeChecker = undefined;
100766                     diagnosticsProducingTypeChecker = undefined;
100767                 }
100768                 throw e;
100769             }
100770         }
100771         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
100772             return ts.concatenate(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), getProgramDiagnostics(sourceFile));
100773         }
100774         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
100775             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
100776         }
100777         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
100778             return runWithCancellationToken(function () {
100779                 if (ts.skipTypeChecking(sourceFile, options, program)) {
100780                     return ts.emptyArray;
100781                 }
100782                 var typeChecker = getDiagnosticsProducingTypeChecker();
100783                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
100784                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
100785                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
100786                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
100787                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
100788                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
100789                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
100790                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
100791                 return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
100792             });
100793         }
100794         function getMergedBindAndCheckDiagnostics(sourceFile) {
100795             var _a;
100796             var allDiagnostics = [];
100797             for (var _i = 1; _i < arguments.length; _i++) {
100798                 allDiagnostics[_i - 1] = arguments[_i];
100799             }
100800             var flatDiagnostics = ts.flatten(allDiagnostics);
100801             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100802                 return flatDiagnostics;
100803             }
100804             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
100805             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
100806                 var errorExpectation = _d[_c];
100807                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
100808             }
100809             return diagnostics;
100810         }
100811         /**
100812          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
100813          * Comments that match to any of those diagnostics are marked as used.
100814          */
100815         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
100816             // Diagnostics are only reported if there is no comment directive preceding them
100817             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
100818             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
100819             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
100820             return { diagnostics: diagnostics, directives: directives };
100821         }
100822         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
100823             return runWithCancellationToken(function () {
100824                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
100825             });
100826         }
100827         /**
100828          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
100829          */
100830         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
100831             var file = diagnostic.file, start = diagnostic.start;
100832             if (!file) {
100833                 return -1;
100834             }
100835             // Start out with the line just before the text
100836             var lineStarts = ts.getLineStarts(file);
100837             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
100838             while (line >= 0) {
100839                 // As soon as that line is known to have a comment directive, use that
100840                 if (directives.markUsed(line)) {
100841                     return line;
100842                 }
100843                 // Stop searching if the line is not empty and not a comment
100844                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
100845                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
100846                     return -1;
100847                 }
100848                 line--;
100849             }
100850             return -1;
100851         }
100852         function getJSSyntacticDiagnosticsForFile(sourceFile) {
100853             return runWithCancellationToken(function () {
100854                 var diagnostics = [];
100855                 walk(sourceFile, sourceFile);
100856                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
100857                 return diagnostics;
100858                 function walk(node, parent) {
100859                     // Return directly from the case if the given node doesnt want to visit each child
100860                     // Otherwise break to visit each child
100861                     switch (parent.kind) {
100862                         case 156 /* Parameter */:
100863                         case 159 /* PropertyDeclaration */:
100864                         case 161 /* MethodDeclaration */:
100865                             if (parent.questionToken === node) {
100866                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
100867                                 return "skip";
100868                             }
100869                         // falls through
100870                         case 160 /* MethodSignature */:
100871                         case 162 /* Constructor */:
100872                         case 163 /* GetAccessor */:
100873                         case 164 /* SetAccessor */:
100874                         case 201 /* FunctionExpression */:
100875                         case 244 /* FunctionDeclaration */:
100876                         case 202 /* ArrowFunction */:
100877                         case 242 /* VariableDeclaration */:
100878                             // type annotation
100879                             if (parent.type === node) {
100880                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
100881                                 return "skip";
100882                             }
100883                     }
100884                     switch (node.kind) {
100885                         case 255 /* ImportClause */:
100886                             if (node.isTypeOnly) {
100887                                 diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
100888                                 return "skip";
100889                             }
100890                             break;
100891                         case 260 /* ExportDeclaration */:
100892                             if (node.isTypeOnly) {
100893                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
100894                                 return "skip";
100895                             }
100896                             break;
100897                         case 253 /* ImportEqualsDeclaration */:
100898                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
100899                             return "skip";
100900                         case 259 /* ExportAssignment */:
100901                             if (node.isExportEquals) {
100902                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
100903                                 return "skip";
100904                             }
100905                             break;
100906                         case 279 /* HeritageClause */:
100907                             var heritageClause = node;
100908                             if (heritageClause.token === 113 /* ImplementsKeyword */) {
100909                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
100910                                 return "skip";
100911                             }
100912                             break;
100913                         case 246 /* InterfaceDeclaration */:
100914                             var interfaceKeyword = ts.tokenToString(114 /* InterfaceKeyword */);
100915                             ts.Debug.assertIsDefined(interfaceKeyword);
100916                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
100917                             return "skip";
100918                         case 249 /* ModuleDeclaration */:
100919                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(136 /* NamespaceKeyword */) : ts.tokenToString(135 /* ModuleKeyword */);
100920                             ts.Debug.assertIsDefined(moduleKeyword);
100921                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
100922                             return "skip";
100923                         case 247 /* TypeAliasDeclaration */:
100924                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
100925                             return "skip";
100926                         case 248 /* EnumDeclaration */:
100927                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(88 /* EnumKeyword */));
100928                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
100929                             return "skip";
100930                         case 218 /* NonNullExpression */:
100931                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
100932                             return "skip";
100933                         case 217 /* AsExpression */:
100934                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
100935                             return "skip";
100936                         case 199 /* TypeAssertionExpression */:
100937                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
100938                     }
100939                 }
100940                 function walkArray(nodes, parent) {
100941                     if (parent.decorators === nodes && !options.experimentalDecorators) {
100942                         diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning));
100943                     }
100944                     switch (parent.kind) {
100945                         case 245 /* ClassDeclaration */:
100946                         case 214 /* ClassExpression */:
100947                         case 161 /* MethodDeclaration */:
100948                         case 162 /* Constructor */:
100949                         case 163 /* GetAccessor */:
100950                         case 164 /* SetAccessor */:
100951                         case 201 /* FunctionExpression */:
100952                         case 244 /* FunctionDeclaration */:
100953                         case 202 /* ArrowFunction */:
100954                             // Check type parameters
100955                             if (nodes === parent.typeParameters) {
100956                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
100957                                 return "skip";
100958                             }
100959                         // falls through
100960                         case 225 /* VariableStatement */:
100961                             // Check modifiers
100962                             if (nodes === parent.modifiers) {
100963                                 checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */);
100964                                 return "skip";
100965                             }
100966                             break;
100967                         case 159 /* PropertyDeclaration */:
100968                             // Check modifiers of property declaration
100969                             if (nodes === parent.modifiers) {
100970                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
100971                                     var modifier = _a[_i];
100972                                     if (modifier.kind !== 120 /* StaticKeyword */) {
100973                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
100974                                     }
100975                                 }
100976                                 return "skip";
100977                             }
100978                             break;
100979                         case 156 /* Parameter */:
100980                             // Check modifiers of parameter declaration
100981                             if (nodes === parent.modifiers) {
100982                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
100983                                 return "skip";
100984                             }
100985                             break;
100986                         case 196 /* CallExpression */:
100987                         case 197 /* NewExpression */:
100988                         case 216 /* ExpressionWithTypeArguments */:
100989                         case 267 /* JsxSelfClosingElement */:
100990                         case 268 /* JsxOpeningElement */:
100991                         case 198 /* TaggedTemplateExpression */:
100992                             // Check type arguments
100993                             if (nodes === parent.typeArguments) {
100994                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
100995                                 return "skip";
100996                             }
100997                             break;
100998                     }
100999                 }
101000                 function checkModifiers(modifiers, isConstValid) {
101001                     for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
101002                         var modifier = modifiers_1[_i];
101003                         switch (modifier.kind) {
101004                             case 81 /* ConstKeyword */:
101005                                 if (isConstValid) {
101006                                     continue;
101007                                 }
101008                             // to report error,
101009                             // falls through
101010                             case 119 /* PublicKeyword */:
101011                             case 117 /* PrivateKeyword */:
101012                             case 118 /* ProtectedKeyword */:
101013                             case 138 /* ReadonlyKeyword */:
101014                             case 130 /* DeclareKeyword */:
101015                             case 122 /* AbstractKeyword */:
101016                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
101017                                 break;
101018                             // These are all legal modifiers.
101019                             case 120 /* StaticKeyword */:
101020                             case 89 /* ExportKeyword */:
101021                             case 84 /* DefaultKeyword */:
101022                         }
101023                     }
101024                 }
101025                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
101026                     var start = nodes.pos;
101027                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
101028                 }
101029                 // Since these are syntactic diagnostics, parent might not have been set
101030                 // this means the sourceFile cannot be infered from the node
101031                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
101032                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
101033                 }
101034             });
101035         }
101036         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
101037             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
101038         }
101039         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
101040             return runWithCancellationToken(function () {
101041                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
101042                 // Don't actually write any files since we're just getting diagnostics.
101043                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
101044             });
101045         }
101046         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
101047             var cachedResult = sourceFile
101048                 ? cache.perFile && cache.perFile.get(sourceFile.path)
101049                 : cache.allDiagnostics;
101050             if (cachedResult) {
101051                 return cachedResult;
101052             }
101053             var result = getDiagnostics(sourceFile, cancellationToken);
101054             if (sourceFile) {
101055                 if (!cache.perFile) {
101056                     cache.perFile = ts.createMap();
101057                 }
101058                 cache.perFile.set(sourceFile.path, result);
101059             }
101060             else {
101061                 cache.allDiagnostics = result;
101062             }
101063             return result;
101064         }
101065         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
101066             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
101067         }
101068         function getOptionsDiagnostics() {
101069             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
101070         }
101071         function getOptionsDiagnosticsOfConfigFile() {
101072             if (!options.configFile) {
101073                 return ts.emptyArray;
101074             }
101075             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
101076             forEachResolvedProjectReference(function (resolvedRef) {
101077                 if (resolvedRef) {
101078                     diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
101079                 }
101080             });
101081             return diagnostics;
101082         }
101083         function getGlobalDiagnostics() {
101084             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
101085         }
101086         function getConfigFileParsingDiagnostics() {
101087             return configFileParsingDiagnostics || ts.emptyArray;
101088         }
101089         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
101090             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
101091         }
101092         function fileReferenceIsEqualTo(a, b) {
101093             return a.fileName === b.fileName;
101094         }
101095         function moduleNameIsEqualTo(a, b) {
101096             return a.kind === 75 /* Identifier */
101097                 ? b.kind === 75 /* Identifier */ && a.escapedText === b.escapedText
101098                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
101099         }
101100         function collectExternalModuleReferences(file) {
101101             if (file.imports) {
101102                 return;
101103             }
101104             var isJavaScriptFile = ts.isSourceFileJS(file);
101105             var isExternalModuleFile = ts.isExternalModule(file);
101106             // file.imports may not be undefined if there exists dynamic import
101107             var imports;
101108             var moduleAugmentations;
101109             var ambientModules;
101110             // If we are importing helpers, we need to add a synthetic reference to resolve the
101111             // helpers library.
101112             if (options.importHelpers
101113                 && (options.isolatedModules || isExternalModuleFile)
101114                 && !file.isDeclarationFile) {
101115                 // synthesize 'import "tslib"' declaration
101116                 var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
101117                 var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
101118                 ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
101119                 externalHelpersModuleReference.parent = importDecl;
101120                 importDecl.parent = file;
101121                 imports = [externalHelpersModuleReference];
101122             }
101123             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
101124                 var node = _a[_i];
101125                 collectModuleReferences(node, /*inAmbientModule*/ false);
101126             }
101127             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
101128                 collectDynamicImportOrRequireCalls(file);
101129             }
101130             file.imports = imports || ts.emptyArray;
101131             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
101132             file.ambientModuleNames = ambientModules || ts.emptyArray;
101133             return;
101134             function collectModuleReferences(node, inAmbientModule) {
101135                 if (ts.isAnyImportOrReExport(node)) {
101136                     var moduleNameExpr = ts.getExternalModuleName(node);
101137                     // TypeScript 1.0 spec (April 2014): 12.1.6
101138                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
101139                     // only through top - level external module names. Relative external module names are not permitted.
101140                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
101141                         imports = ts.append(imports, moduleNameExpr);
101142                     }
101143                 }
101144                 else if (ts.isModuleDeclaration(node)) {
101145                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
101146                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
101147                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
101148                         // This will happen in two cases:
101149                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
101150                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
101151                         //   immediately nested in top level ambient module declaration .
101152                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
101153                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
101154                         }
101155                         else if (!inAmbientModule) {
101156                             if (file.isDeclarationFile) {
101157                                 // for global .d.ts files record name of ambient module
101158                                 (ambientModules || (ambientModules = [])).push(nameText);
101159                             }
101160                             // An AmbientExternalModuleDeclaration declares an external module.
101161                             // This type of declaration is permitted only in the global module.
101162                             // The StringLiteral must specify a top - level external module name.
101163                             // Relative external module names are not permitted
101164                             // NOTE: body of ambient module is always a module block, if it exists
101165                             var body = node.body;
101166                             if (body) {
101167                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
101168                                     var statement = _a[_i];
101169                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
101170                                 }
101171                             }
101172                         }
101173                     }
101174                 }
101175             }
101176             function collectDynamicImportOrRequireCalls(file) {
101177                 var r = /import|require/g;
101178                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
101179                     var node = getNodeAtPosition(file, r.lastIndex);
101180                     if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
101181                         imports = ts.append(imports, node.arguments[0]);
101182                     }
101183                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
101184                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
101185                         imports = ts.append(imports, node.arguments[0]);
101186                     }
101187                     else if (ts.isLiteralImportTypeNode(node)) {
101188                         imports = ts.append(imports, node.argument.literal);
101189                     }
101190                 }
101191             }
101192             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
101193             function getNodeAtPosition(sourceFile, position) {
101194                 var current = sourceFile;
101195                 var getContainingChild = function (child) {
101196                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
101197                         return child;
101198                     }
101199                 };
101200                 while (true) {
101201                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
101202                     if (!child) {
101203                         return current;
101204                     }
101205                     current = child;
101206                 }
101207             }
101208         }
101209         function getLibFileFromReference(ref) {
101210             var libName = ts.toFileNameLowerCase(ref.fileName);
101211             var libFileName = ts.libMap.get(libName);
101212             if (libFileName) {
101213                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
101214             }
101215         }
101216         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
101217         function getSourceFileFromReference(referencingFile, ref) {
101218             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
101219         }
101220         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
101221             if (ts.hasExtension(fileName)) {
101222                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
101223                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
101224                     if (fail) {
101225                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
101226                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
101227                         }
101228                         else {
101229                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101230                         }
101231                     }
101232                     return undefined;
101233                 }
101234                 var sourceFile = getSourceFile(fileName);
101235                 if (fail) {
101236                     if (!sourceFile) {
101237                         var redirect = getProjectReferenceRedirect(fileName);
101238                         if (redirect) {
101239                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
101240                         }
101241                         else {
101242                             fail(ts.Diagnostics.File_0_not_found, fileName);
101243                         }
101244                     }
101245                     else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
101246                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
101247                     }
101248                 }
101249                 return sourceFile;
101250             }
101251             else {
101252                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
101253                 if (sourceFileNoExtension)
101254                     return sourceFileNoExtension;
101255                 if (fail && options.allowNonTsExtensions) {
101256                     fail(ts.Diagnostics.File_0_not_found, fileName);
101257                     return undefined;
101258                 }
101259                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
101260                 if (fail && !sourceFileWithAddedExtension)
101261                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101262                 return sourceFileWithAddedExtension;
101263             }
101264         }
101265         /** This has side effects through `findSourceFile`. */
101266         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
101267             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
101268             function (diagnostic) {
101269                 var args = [];
101270                 for (var _i = 1; _i < arguments.length; _i++) {
101271                     args[_i - 1] = arguments[_i];
101272                 }
101273                 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
101274             }, refFile && refFile.file);
101275         }
101276         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
101277             var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
101278             var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
101279             fileProcessingDiagnostics.add(refToReportErrorOn ?
101280                 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
101281                 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
101282         }
101283         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
101284             var redirect = Object.create(redirectTarget);
101285             redirect.fileName = fileName;
101286             redirect.path = path;
101287             redirect.resolvedPath = resolvedPath;
101288             redirect.originalFileName = originalFileName;
101289             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
101290             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101291             Object.defineProperties(redirect, {
101292                 id: {
101293                     get: function () { return this.redirectInfo.redirectTarget.id; },
101294                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
101295                 },
101296                 symbol: {
101297                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
101298                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
101299                 },
101300             });
101301             return redirect;
101302         }
101303         // Get source file from normalized fileName
101304         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
101305             if (useSourceOfProjectReferenceRedirect) {
101306                 var source = getSourceOfProjectReferenceRedirect(fileName);
101307                 // If preserveSymlinks is true, module resolution wont jump the symlink
101308                 // but the resolved real path may be the .d.ts from project reference
101309                 // Note:: Currently we try the real path only if the
101310                 // file is from node_modules to avoid having to run real path on all file paths
101311                 if (!source &&
101312                     host.realpath &&
101313                     options.preserveSymlinks &&
101314                     ts.isDeclarationFileName(fileName) &&
101315                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
101316                     var realPath = host.realpath(fileName);
101317                     if (realPath !== fileName)
101318                         source = getSourceOfProjectReferenceRedirect(realPath);
101319                 }
101320                 if (source) {
101321                     var file_1 = ts.isString(source) ?
101322                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
101323                         undefined;
101324                     if (file_1)
101325                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
101326                     return file_1;
101327                 }
101328             }
101329             var originalFileName = fileName;
101330             if (filesByName.has(path)) {
101331                 var file_2 = filesByName.get(path);
101332                 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
101333                 // try to check if we've already seen this file but with a different casing in path
101334                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
101335                 if (file_2 && options.forceConsistentCasingInFileNames) {
101336                     var checkedName = file_2.fileName;
101337                     var isRedirect = toPath(checkedName) !== toPath(fileName);
101338                     if (isRedirect) {
101339                         fileName = getProjectReferenceRedirect(fileName) || fileName;
101340                     }
101341                     // Check if it differs only in drive letters its ok to ignore that error:
101342                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
101343                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
101344                     if (checkedAbsolutePath !== inputAbsolutePath) {
101345                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
101346                     }
101347                 }
101348                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
101349                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
101350                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
101351                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
101352                     if (!options.noResolve) {
101353                         processReferencedFiles(file_2, isDefaultLib);
101354                         processTypeReferenceDirectives(file_2);
101355                     }
101356                     if (!options.noLib) {
101357                         processLibReferenceDirectives(file_2);
101358                     }
101359                     modulesWithElidedImports.set(file_2.path, false);
101360                     processImportedModules(file_2);
101361                 }
101362                 // See if we need to reprocess the imports due to prior skipped imports
101363                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
101364                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
101365                         modulesWithElidedImports.set(file_2.path, false);
101366                         processImportedModules(file_2);
101367                     }
101368                 }
101369                 return file_2 || undefined;
101370             }
101371             var redirectedPath;
101372             if (refFile && !useSourceOfProjectReferenceRedirect) {
101373                 var redirectProject = getProjectReferenceRedirectProject(fileName);
101374                 if (redirectProject) {
101375                     if (redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out) {
101376                         // Shouldnt create many to 1 mapping file in --out scenario
101377                         return undefined;
101378                     }
101379                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
101380                     fileName = redirect;
101381                     // Once we start redirecting to a file, we can potentially come back to it
101382                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
101383                     // end up trying to add it to the program *again* because we were tracking it via its
101384                     // original (un-redirected) name. So we have to map both the original path and the redirected path
101385                     // to the source file we're about to find/create
101386                     redirectedPath = toPath(redirect);
101387                 }
101388             }
101389             // We haven't looked for this file, do so now and cache result
101390             var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { return fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); }, shouldCreateNewSourceFile);
101391             if (packageId) {
101392                 var packageIdKey = ts.packageIdToString(packageId);
101393                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
101394                 if (fileFromPackageId) {
101395                     // Some other SourceFile already exists with this package name and version.
101396                     // Instead of creating a duplicate, just redirect to the existing one.
101397                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
101398                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
101399                     addFileToFilesByName(dupFile, path, redirectedPath);
101400                     sourceFileToPackageName.set(path, packageId.name);
101401                     processingOtherFiles.push(dupFile);
101402                     return dupFile;
101403                 }
101404                 else if (file) {
101405                     // This is the first source file to have this packageId.
101406                     packageIdToSourceFile.set(packageIdKey, file);
101407                     sourceFileToPackageName.set(path, packageId.name);
101408                 }
101409             }
101410             addFileToFilesByName(file, path, redirectedPath);
101411             if (file) {
101412                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101413                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
101414                 file.path = path;
101415                 file.resolvedPath = toPath(fileName);
101416                 file.originalFileName = originalFileName;
101417                 addFileToRefFileMap(fileName, file, refFile);
101418                 if (host.useCaseSensitiveFileNames()) {
101419                     var pathLowerCase = ts.toFileNameLowerCase(path);
101420                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
101421                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
101422                     if (existingFile) {
101423                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
101424                     }
101425                     else {
101426                         filesByNameIgnoreCase.set(pathLowerCase, file);
101427                     }
101428                 }
101429                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
101430                 if (!options.noResolve) {
101431                     processReferencedFiles(file, isDefaultLib);
101432                     processTypeReferenceDirectives(file);
101433                 }
101434                 if (!options.noLib) {
101435                     processLibReferenceDirectives(file);
101436                 }
101437                 // always process imported modules to record module name resolutions
101438                 processImportedModules(file);
101439                 if (isDefaultLib) {
101440                     processingDefaultLibFiles.push(file);
101441                 }
101442                 else {
101443                     processingOtherFiles.push(file);
101444                 }
101445             }
101446             return file;
101447         }
101448         function addFileToRefFileMap(referencedFileName, file, refFile) {
101449             if (refFile && file) {
101450                 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
101451                     referencedFileName: referencedFileName,
101452                     kind: refFile.kind,
101453                     index: refFile.index,
101454                     file: refFile.file.path
101455                 });
101456             }
101457         }
101458         function addFileToFilesByName(file, path, redirectedPath) {
101459             if (redirectedPath) {
101460                 filesByName.set(redirectedPath, file);
101461                 filesByName.set(path, file || false);
101462             }
101463             else {
101464                 filesByName.set(path, file);
101465             }
101466         }
101467         function getProjectReferenceRedirect(fileName) {
101468             var referencedProject = getProjectReferenceRedirectProject(fileName);
101469             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
101470         }
101471         function getProjectReferenceRedirectProject(fileName) {
101472             // Ignore dts or any json files
101473             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101474                 return undefined;
101475             }
101476             // If this file is produced by a referenced project, we need to rewrite it to
101477             // look in the output folder of the referenced project rather than the input
101478             return getResolvedProjectReferenceToRedirect(fileName);
101479         }
101480         function getProjectReferenceOutputName(referencedProject, fileName) {
101481             var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
101482             return out ?
101483                 ts.changeExtension(out, ".d.ts" /* Dts */) :
101484                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
101485         }
101486         /**
101487          * Get the referenced project if the file is input file from that reference project
101488          */
101489         function getResolvedProjectReferenceToRedirect(fileName) {
101490             if (mapFromFileToProjectReferenceRedirects === undefined) {
101491                 mapFromFileToProjectReferenceRedirects = ts.createMap();
101492                 forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
101493                     // not input file from the referenced project, ignore
101494                     if (referencedProject &&
101495                         toPath(options.configFilePath) !== referenceProjectPath) {
101496                         referencedProject.commandLine.fileNames.forEach(function (f) {
101497                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
101498                         });
101499                     }
101500                 });
101501             }
101502             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
101503             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
101504         }
101505         function forEachResolvedProjectReference(cb) {
101506             return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
101507                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
101508                 var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
101509                 return cb(resolvedRef, resolvedRefPath);
101510             });
101511         }
101512         function getSourceOfProjectReferenceRedirect(file) {
101513             if (!ts.isDeclarationFileName(file))
101514                 return undefined;
101515             if (mapFromToProjectReferenceRedirectSource === undefined) {
101516                 mapFromToProjectReferenceRedirectSource = ts.createMap();
101517                 forEachResolvedProjectReference(function (resolvedRef) {
101518                     if (resolvedRef) {
101519                         var out = resolvedRef.commandLine.options.outFile || resolvedRef.commandLine.options.out;
101520                         if (out) {
101521                             // Dont know which source file it means so return true?
101522                             var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
101523                             mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
101524                         }
101525                         else {
101526                             ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
101527                                 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101528                                     var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
101529                                     mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
101530                                 }
101531                             });
101532                         }
101533                     }
101534                 });
101535             }
101536             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
101537         }
101538         function isSourceOfProjectReferenceRedirect(fileName) {
101539             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
101540         }
101541         function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
101542             var seenResolvedRefs;
101543             return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
101544             function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
101545                 // Visit project references first
101546                 if (cbRef) {
101547                     var result = cbRef(projectReferences, parent);
101548                     if (result) {
101549                         return result;
101550                     }
101551                 }
101552                 return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
101553                     if (ts.contains(seenResolvedRefs, resolvedRef)) {
101554                         // ignore recursives
101555                         return undefined;
101556                     }
101557                     var result = cbResolvedRef(resolvedRef, index, parent);
101558                     if (result) {
101559                         return result;
101560                     }
101561                     if (!resolvedRef)
101562                         return undefined;
101563                     (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
101564                     return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
101565                 });
101566             }
101567         }
101568         function getResolvedProjectReferenceByPath(projectReferencePath) {
101569             if (!projectReferenceRedirects) {
101570                 return undefined;
101571             }
101572             return projectReferenceRedirects.get(projectReferencePath) || undefined;
101573         }
101574         function processReferencedFiles(file, isDefaultLib) {
101575             ts.forEach(file.referencedFiles, function (ref, index) {
101576                 var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
101577                 processSourceFile(referencedFileName, isDefaultLib, 
101578                 /*ignoreNoDefaultLib*/ false, 
101579                 /*packageId*/ undefined, {
101580                     kind: ts.RefFileKind.ReferenceFile,
101581                     index: index,
101582                     file: file,
101583                     pos: ref.pos,
101584                     end: ref.end
101585                 });
101586             });
101587         }
101588         function processTypeReferenceDirectives(file) {
101589             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
101590             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
101591             if (!typeDirectives) {
101592                 return;
101593             }
101594             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
101595             for (var i = 0; i < typeDirectives.length; i++) {
101596                 var ref = file.typeReferenceDirectives[i];
101597                 var resolvedTypeReferenceDirective = resolutions[i];
101598                 // store resolved type directive on the file
101599                 var fileName = ts.toFileNameLowerCase(ref.fileName);
101600                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
101601                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
101602                     kind: ts.RefFileKind.TypeReferenceDirective,
101603                     index: i,
101604                     file: file,
101605                     pos: ref.pos,
101606                     end: ref.end
101607                 });
101608             }
101609         }
101610         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
101611             // If we already found this library as a primary reference - nothing to do
101612             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
101613             if (previousResolution && previousResolution.primary) {
101614                 return;
101615             }
101616             var saveResolution = true;
101617             if (resolvedTypeReferenceDirective) {
101618                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101619                     currentNodeModulesDepth++;
101620                 if (resolvedTypeReferenceDirective.primary) {
101621                     // resolved from the primary path
101622                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
101623                 }
101624                 else {
101625                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
101626                     // for sameness and possibly issue an error
101627                     if (previousResolution) {
101628                         // Don't bother reading the file again if it's the same file.
101629                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
101630                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
101631                             var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
101632                             if (otherFileText !== existingFile_1.text) {
101633                                 // Try looking up ref for original file
101634                                 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
101635                                 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
101636                                 fileProcessingDiagnostics.add(refToReportErrorOn ?
101637                                     createFileDiagnosticAtReference(refToReportErrorOn, ts.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) :
101638                                     createRefFileDiagnostic(refFile, ts.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));
101639                             }
101640                         }
101641                         // don't overwrite previous resolution result
101642                         saveResolution = false;
101643                     }
101644                     else {
101645                         // First resolution of this library
101646                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
101647                     }
101648                 }
101649                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101650                     currentNodeModulesDepth--;
101651             }
101652             else {
101653                 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
101654             }
101655             if (saveResolution) {
101656                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
101657             }
101658         }
101659         function processLibReferenceDirectives(file) {
101660             ts.forEach(file.libReferenceDirectives, function (libReference) {
101661                 var libName = ts.toFileNameLowerCase(libReference.fileName);
101662                 var libFileName = ts.libMap.get(libName);
101663                 if (libFileName) {
101664                     // we ignore any 'no-default-lib' reference set on this file.
101665                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
101666                 }
101667                 else {
101668                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
101669                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
101670                     var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
101671                     fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
101672                 }
101673             });
101674         }
101675         function createRefFileDiagnostic(refFile, message) {
101676             var args = [];
101677             for (var _i = 2; _i < arguments.length; _i++) {
101678                 args[_i - 2] = arguments[_i];
101679             }
101680             if (!refFile) {
101681                 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
101682             }
101683             else {
101684                 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
101685             }
101686         }
101687         function getCanonicalFileName(fileName) {
101688             return host.getCanonicalFileName(fileName);
101689         }
101690         function processImportedModules(file) {
101691             collectExternalModuleReferences(file);
101692             if (file.imports.length || file.moduleAugmentations.length) {
101693                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
101694                 var moduleNames = getModuleNames(file);
101695                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
101696                 ts.Debug.assert(resolutions.length === moduleNames.length);
101697                 for (var i = 0; i < moduleNames.length; i++) {
101698                     var resolution = resolutions[i];
101699                     ts.setResolvedModule(file, moduleNames[i], resolution);
101700                     if (!resolution) {
101701                         continue;
101702                     }
101703                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
101704                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
101705                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
101706                     var resolvedFileName = resolution.resolvedFileName;
101707                     if (isFromNodeModulesSearch) {
101708                         currentNodeModulesDepth++;
101709                     }
101710                     // add file to program only if:
101711                     // - resolution was successful
101712                     // - noResolve is falsy
101713                     // - module name comes from the list of imports
101714                     // - it's not a top level JavaScript module that exceeded the search max
101715                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
101716                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
101717                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
101718                     var shouldAddFile = resolvedFileName
101719                         && !getResolutionDiagnostic(options, resolution)
101720                         && !options.noResolve
101721                         && i < file.imports.length
101722                         && !elideImport
101723                         && !(isJsFile && !options.allowJs)
101724                         && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
101725                     if (elideImport) {
101726                         modulesWithElidedImports.set(file.path, true);
101727                     }
101728                     else if (shouldAddFile) {
101729                         var path = toPath(resolvedFileName);
101730                         var pos = ts.skipTrivia(file.text, file.imports[i].pos);
101731                         findSourceFile(resolvedFileName, path, 
101732                         /*isDefaultLib*/ false, 
101733                         /*ignoreNoDefaultLib*/ false, {
101734                             kind: ts.RefFileKind.Import,
101735                             index: i,
101736                             file: file,
101737                             pos: pos,
101738                             end: file.imports[i].end
101739                         }, resolution.packageId);
101740                     }
101741                     if (isFromNodeModulesSearch) {
101742                         currentNodeModulesDepth--;
101743                     }
101744                 }
101745             }
101746             else {
101747                 // no imports - drop cached module resolutions
101748                 file.resolvedModules = undefined;
101749             }
101750         }
101751         function computeCommonSourceDirectory(sourceFiles) {
101752             var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
101753             return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
101754         }
101755         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
101756             var allFilesBelongToPath = true;
101757             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
101758             var rootPaths;
101759             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
101760                 var sourceFile = sourceFiles_2[_i];
101761                 if (!sourceFile.isDeclarationFile) {
101762                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
101763                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
101764                         if (!rootPaths)
101765                             rootPaths = ts.arrayToSet(rootNames, toPath);
101766                         addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
101767                         allFilesBelongToPath = false;
101768                     }
101769                 }
101770             }
101771             return allFilesBelongToPath;
101772         }
101773         function parseProjectReferenceConfigFile(ref) {
101774             if (!projectReferenceRedirects) {
101775                 projectReferenceRedirects = ts.createMap();
101776             }
101777             // The actual filename (i.e. add "/tsconfig.json" if necessary)
101778             var refPath = resolveProjectReferencePath(ref);
101779             var sourceFilePath = toPath(refPath);
101780             var fromCache = projectReferenceRedirects.get(sourceFilePath);
101781             if (fromCache !== undefined) {
101782                 return fromCache || undefined;
101783             }
101784             var commandLine;
101785             var sourceFile;
101786             if (host.getParsedCommandLine) {
101787                 commandLine = host.getParsedCommandLine(refPath);
101788                 if (!commandLine) {
101789                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
101790                     projectReferenceRedirects.set(sourceFilePath, false);
101791                     return undefined;
101792                 }
101793                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
101794                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
101795                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101796             }
101797             else {
101798                 // An absolute path pointing to the containing directory of the config file
101799                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
101800                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
101801                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101802                 if (sourceFile === undefined) {
101803                     projectReferenceRedirects.set(sourceFilePath, false);
101804                     return undefined;
101805                 }
101806                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
101807             }
101808             sourceFile.fileName = refPath;
101809             sourceFile.path = sourceFilePath;
101810             sourceFile.resolvedPath = sourceFilePath;
101811             sourceFile.originalFileName = refPath;
101812             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
101813             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
101814             if (commandLine.projectReferences) {
101815                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
101816             }
101817             return resolvedRef;
101818         }
101819         function verifyCompilerOptions() {
101820             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
101821                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
101822             }
101823             if (options.isolatedModules) {
101824                 if (options.out) {
101825                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
101826                 }
101827                 if (options.outFile) {
101828                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
101829                 }
101830             }
101831             if (options.inlineSourceMap) {
101832                 if (options.sourceMap) {
101833                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
101834                 }
101835                 if (options.mapRoot) {
101836                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
101837                 }
101838             }
101839             if (options.paths && options.baseUrl === undefined) {
101840                 createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
101841             }
101842             if (options.composite) {
101843                 if (options.declaration === false) {
101844                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
101845                 }
101846                 if (options.incremental === false) {
101847                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
101848                 }
101849             }
101850             if (options.tsBuildInfoFile) {
101851                 if (!ts.isIncrementalCompilation(options)) {
101852                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
101853                 }
101854             }
101855             else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) {
101856                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
101857             }
101858             if (!options.listFilesOnly && options.noEmit && ts.isIncrementalCompilation(options)) {
101859                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
101860             }
101861             verifyProjectReferences();
101862             // List of collected files is complete; validate exhautiveness if this is a project with a file list
101863             if (options.composite) {
101864                 var rootPaths = ts.arrayToSet(rootNames, toPath);
101865                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
101866                     var file = files_3[_i];
101867                     // Ignore file that is not emitted
101868                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
101869                         addProgramDiagnosticAtRefPath(file, rootPaths, ts.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 || "");
101870                     }
101871                 }
101872             }
101873             if (options.paths) {
101874                 for (var key in options.paths) {
101875                     if (!ts.hasProperty(options.paths, key)) {
101876                         continue;
101877                     }
101878                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
101879                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
101880                     }
101881                     if (ts.isArray(options.paths[key])) {
101882                         var len = options.paths[key].length;
101883                         if (len === 0) {
101884                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
101885                         }
101886                         for (var i = 0; i < len; i++) {
101887                             var subst = options.paths[key][i];
101888                             var typeOfSubst = typeof subst;
101889                             if (typeOfSubst === "string") {
101890                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
101891                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
101892                                 }
101893                             }
101894                             else {
101895                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
101896                             }
101897                         }
101898                     }
101899                     else {
101900                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
101901                     }
101902                 }
101903             }
101904             if (!options.sourceMap && !options.inlineSourceMap) {
101905                 if (options.inlineSources) {
101906                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
101907                 }
101908                 if (options.sourceRoot) {
101909                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
101910                 }
101911             }
101912             if (options.out && options.outFile) {
101913                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
101914             }
101915             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
101916                 // Error to specify --mapRoot without --sourcemap
101917                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
101918             }
101919             if (options.declarationDir) {
101920                 if (!ts.getEmitDeclarations(options)) {
101921                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
101922                 }
101923                 if (options.out || options.outFile) {
101924                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
101925                 }
101926             }
101927             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
101928                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
101929             }
101930             if (options.lib && options.noLib) {
101931                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
101932             }
101933             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
101934                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
101935             }
101936             var languageVersion = options.target || 0 /* ES3 */;
101937             var outFile = options.outFile || options.out;
101938             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
101939             if (options.isolatedModules) {
101940                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
101941                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
101942                 }
101943                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
101944                 if (firstNonExternalModuleSourceFile) {
101945                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
101946                     programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
101947                 }
101948             }
101949             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
101950                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
101951                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101952                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
101953             }
101954             // Cannot specify module gen that isn't amd or system with --out
101955             if (outFile && !options.emitDeclarationOnly) {
101956                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
101957                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
101958                 }
101959                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
101960                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101961                     programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
101962                 }
101963             }
101964             if (options.resolveJsonModule) {
101965                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
101966                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
101967                 }
101968                 // Any emit other than common js, amd, es2015 or esnext is error
101969                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
101970                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
101971                 }
101972             }
101973             // there has to be common source directory if user specified --outdir || --sourceRoot
101974             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
101975             if (options.outDir || // there is --outDir specified
101976                 options.sourceRoot || // there is --sourceRoot specified
101977                 options.mapRoot) { // there is --mapRoot specified
101978                 // Precalculate and cache the common source directory
101979                 var dir = getCommonSourceDirectory();
101980                 // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
101981                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
101982                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
101983                 }
101984             }
101985             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
101986                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
101987             }
101988             if (options.checkJs && !options.allowJs) {
101989                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
101990             }
101991             if (options.emitDeclarationOnly) {
101992                 if (!ts.getEmitDeclarations(options)) {
101993                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
101994                 }
101995                 if (options.noEmit) {
101996                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
101997                 }
101998             }
101999             if (options.emitDecoratorMetadata &&
102000                 !options.experimentalDecorators) {
102001                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
102002             }
102003             if (options.jsxFactory) {
102004                 if (options.reactNamespace) {
102005                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
102006                 }
102007                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
102008                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
102009                 }
102010             }
102011             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
102012                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
102013             }
102014             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
102015             if (!options.noEmit && !options.suppressOutputPathCheck) {
102016                 var emitHost = getEmitHost();
102017                 var emitFilesSeen_1 = ts.createMap();
102018                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
102019                     if (!options.emitDeclarationOnly) {
102020                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
102021                     }
102022                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
102023                 });
102024             }
102025             // Verify that all the emit files are unique and don't overwrite input files
102026             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
102027                 if (emitFileName) {
102028                     var emitFilePath = toPath(emitFileName);
102029                     // Report error if the output overwrites input file
102030                     if (filesByName.has(emitFilePath)) {
102031                         var chain = void 0;
102032                         if (!options.configFilePath) {
102033                             // The program is from either an inferred project or an external project
102034                             chain = ts.chainDiagnosticMessages(/*details*/ undefined, ts.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);
102035                         }
102036                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
102037                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
102038                     }
102039                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
102040                     // Report error if multiple files write into same file
102041                     if (emitFilesSeen.has(emitFileKey)) {
102042                         // Already seen the same emit file - report error
102043                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
102044                     }
102045                     else {
102046                         emitFilesSeen.set(emitFileKey, true);
102047                     }
102048                 }
102049             }
102050         }
102051         function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
102052             var _a, _b;
102053             var args = [];
102054             for (var _i = 2; _i < arguments.length; _i++) {
102055                 args[_i - 2] = arguments[_i];
102056             }
102057             var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
102058             var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
102059             var pos, end;
102060             switch (kind) {
102061                 case ts.RefFileKind.Import:
102062                     pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
102063                     end = refFile.imports[index].end;
102064                     break;
102065                 case ts.RefFileKind.ReferenceFile:
102066                     (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
102067                     break;
102068                 case ts.RefFileKind.TypeReferenceDirective:
102069                     (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
102070                     break;
102071                 default:
102072                     return ts.Debug.assertNever(kind);
102073             }
102074             return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
102075         }
102076         function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
102077             var args = [];
102078             for (var _i = 3; _i < arguments.length; _i++) {
102079                 args[_i - 3] = arguments[_i];
102080             }
102081             var refPaths = refFileMap && refFileMap.get(file.path);
102082             var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
102083                 ts.elementAt(refPaths, 0);
102084             programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
102085         }
102086         function verifyProjectReferences() {
102087             var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
102088             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
102089                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
102090                 var parentFile = parent && parent.sourceFile;
102091                 if (!resolvedRef) {
102092                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
102093                     return;
102094                 }
102095                 var options = resolvedRef.commandLine.options;
102096                 if (!options.composite) {
102097                     // ok to not have composite if the current program is container only
102098                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
102099                     if (inputs.length) {
102100                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
102101                     }
102102                 }
102103                 if (ref.prepend) {
102104                     var out = options.outFile || options.out;
102105                     if (out) {
102106                         if (!host.fileExists(out)) {
102107                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
102108                         }
102109                     }
102110                     else {
102111                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
102112                     }
102113                 }
102114                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
102115                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
102116                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
102117                 }
102118             });
102119         }
102120         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
102121             var needCompilerDiagnostic = true;
102122             var pathsSyntax = getOptionPathsSyntax();
102123             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
102124                 var pathProp = pathsSyntax_1[_i];
102125                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
102126                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
102127                         var keyProps = _b[_a];
102128                         var initializer = keyProps.initializer;
102129                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
102130                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
102131                             needCompilerDiagnostic = false;
102132                         }
102133                     }
102134                 }
102135             }
102136             if (needCompilerDiagnostic) {
102137                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102138             }
102139         }
102140         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
102141             var needCompilerDiagnostic = true;
102142             var pathsSyntax = getOptionPathsSyntax();
102143             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
102144                 var pathProp = pathsSyntax_2[_i];
102145                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
102146                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
102147                     needCompilerDiagnostic = false;
102148                 }
102149             }
102150             if (needCompilerDiagnostic) {
102151                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
102152             }
102153         }
102154         function getOptionsSyntaxByName(name) {
102155             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102156             if (compilerOptionsObjectLiteralSyntax) {
102157                 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
102158             }
102159             return undefined;
102160         }
102161         function getOptionPathsSyntax() {
102162             return getOptionsSyntaxByName("paths") || ts.emptyArray;
102163         }
102164         function createDiagnosticForOptionName(message, option1, option2, option3) {
102165             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
102166         }
102167         function createOptionValueDiagnostic(option1, message, arg0) {
102168             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
102169         }
102170         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
102171             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
102172             if (referencesSyntax && referencesSyntax.elements.length > index) {
102173                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
102174             }
102175             else {
102176                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
102177             }
102178         }
102179         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
102180             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102181             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
102182                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
102183             if (needCompilerDiagnostic) {
102184                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102185             }
102186         }
102187         function getCompilerOptionsObjectLiteralSyntax() {
102188             if (_compilerOptionsObjectLiteralSyntax === undefined) {
102189                 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
102190                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
102191                 if (jsonObjectLiteral) {
102192                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
102193                         var prop = _a[_i];
102194                         if (ts.isObjectLiteralExpression(prop.initializer)) {
102195                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
102196                             break;
102197                         }
102198                     }
102199                 }
102200             }
102201             return _compilerOptionsObjectLiteralSyntax;
102202         }
102203         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
102204             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
102205             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
102206                 var prop = props_3[_i];
102207                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
102208             }
102209             return !!props.length;
102210         }
102211         function blockEmittingOfFile(emitFileName, diag) {
102212             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
102213             programDiagnostics.add(diag);
102214         }
102215         function isEmittedFile(file) {
102216             if (options.noEmit) {
102217                 return false;
102218             }
102219             // If this is source file, its not emitted file
102220             var filePath = toPath(file);
102221             if (getSourceFileByPath(filePath)) {
102222                 return false;
102223             }
102224             // If options have --outFile or --out just check that
102225             var out = options.outFile || options.out;
102226             if (out) {
102227                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
102228             }
102229             // If declarationDir is specified, return if its a file in that directory
102230             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
102231                 return true;
102232             }
102233             // If --outDir, check if file is in that directory
102234             if (options.outDir) {
102235                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
102236             }
102237             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
102238                 // Otherwise just check if sourceFile with the name exists
102239                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
102240                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
102241                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
102242             }
102243             return false;
102244         }
102245         function isSameFile(file1, file2) {
102246             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
102247         }
102248         function getProbableSymlinks() {
102249             if (host.getSymlinks) {
102250                 return host.getSymlinks();
102251             }
102252             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
102253         }
102254     }
102255     ts.createProgram = createProgram;
102256     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
102257         var mapOfDeclarationDirectories;
102258         var symlinkedDirectories;
102259         var symlinkedFiles;
102260         var originalFileExists = host.compilerHost.fileExists;
102261         var originalDirectoryExists = host.compilerHost.directoryExists;
102262         var originalGetDirectories = host.compilerHost.getDirectories;
102263         var originalRealpath = host.compilerHost.realpath;
102264         if (!host.useSourceOfProjectReferenceRedirect)
102265             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
102266         host.compilerHost.fileExists = fileExists;
102267         if (originalDirectoryExists) {
102268             // This implementation of directoryExists checks if the directory being requested is
102269             // directory of .d.ts file for the referenced Project.
102270             // If it is it returns true irrespective of whether that directory exists on host
102271             host.compilerHost.directoryExists = function (path) {
102272                 if (originalDirectoryExists.call(host.compilerHost, path)) {
102273                     handleDirectoryCouldBeSymlink(path);
102274                     return true;
102275                 }
102276                 if (!host.getResolvedProjectReferences())
102277                     return false;
102278                 if (!mapOfDeclarationDirectories) {
102279                     mapOfDeclarationDirectories = ts.createMap();
102280                     host.forEachResolvedProjectReference(function (ref) {
102281                         if (!ref)
102282                             return;
102283                         var out = ref.commandLine.options.outFile || ref.commandLine.options.out;
102284                         if (out) {
102285                             mapOfDeclarationDirectories.set(ts.getDirectoryPath(host.toPath(out)), true);
102286                         }
102287                         else {
102288                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
102289                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
102290                             if (declarationDir) {
102291                                 mapOfDeclarationDirectories.set(host.toPath(declarationDir), true);
102292                             }
102293                         }
102294                     });
102295                 }
102296                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
102297             };
102298         }
102299         if (originalGetDirectories) {
102300             // Call getDirectories only if directory actually present on the host
102301             // This is needed to ensure that we arent getting directories that we fake about presence for
102302             host.compilerHost.getDirectories = function (path) {
102303                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
102304                     originalGetDirectories.call(host.compilerHost, path) :
102305                     [];
102306             };
102307         }
102308         // This is something we keep for life time of the host
102309         if (originalRealpath) {
102310             host.compilerHost.realpath = function (s) {
102311                 return (symlinkedFiles === null || symlinkedFiles === void 0 ? void 0 : symlinkedFiles.get(host.toPath(s))) ||
102312                     originalRealpath.call(host.compilerHost, s);
102313             };
102314         }
102315         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists };
102316         function onProgramCreateComplete() {
102317             host.compilerHost.fileExists = originalFileExists;
102318             host.compilerHost.directoryExists = originalDirectoryExists;
102319             host.compilerHost.getDirectories = originalGetDirectories;
102320             // DO not revert realpath as it could be used later
102321         }
102322         // This implementation of fileExists checks if the file being requested is
102323         // .d.ts file for the referenced Project.
102324         // If it is it returns true irrespective of whether that file exists on host
102325         function fileExists(file) {
102326             if (originalFileExists.call(host.compilerHost, file))
102327                 return true;
102328             if (!host.getResolvedProjectReferences())
102329                 return false;
102330             if (!ts.isDeclarationFileName(file))
102331                 return false;
102332             // Project references go to source file instead of .d.ts file
102333             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
102334         }
102335         function fileExistsIfProjectReferenceDts(file) {
102336             var source = host.getSourceOfProjectReferenceRedirect(file);
102337             return source !== undefined ?
102338                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
102339                 undefined;
102340         }
102341         function directoryExistsIfProjectReferenceDeclDir(dir) {
102342             var dirPath = host.toPath(dir);
102343             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
102344             return ts.forEachKey(mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
102345                 // Any parent directory of declaration dir
102346                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
102347                 // Any directory inside declaration dir
102348                 ts.startsWith(dirPath, declDirPath + "/"); });
102349         }
102350         function handleDirectoryCouldBeSymlink(directory) {
102351             if (!host.getResolvedProjectReferences())
102352                 return;
102353             // Because we already watch node_modules, handle symlinks in there
102354             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
102355                 return;
102356             if (!symlinkedDirectories)
102357                 symlinkedDirectories = ts.createMap();
102358             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
102359             if (symlinkedDirectories.has(directoryPath))
102360                 return;
102361             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
102362             var realPath;
102363             if (real === directory ||
102364                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
102365                 // not symlinked
102366                 symlinkedDirectories.set(directoryPath, false);
102367                 return;
102368             }
102369             symlinkedDirectories.set(directoryPath, {
102370                 real: ts.ensureTrailingDirectorySeparator(real),
102371                 realPath: realPath
102372             });
102373         }
102374         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
102375             var fileOrDirectoryExistsUsingSource = isFile ?
102376                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
102377                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
102378             // Check current directory or file
102379             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
102380             if (result !== undefined)
102381                 return result;
102382             if (!symlinkedDirectories)
102383                 return false;
102384             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
102385             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
102386                 return false;
102387             if (isFile && symlinkedFiles && symlinkedFiles.has(fileOrDirectoryPath))
102388                 return true;
102389             // If it contains node_modules check if its one of the symlinked path we know of
102390             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
102391                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
102392                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
102393                     return undefined;
102394                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
102395                 if (isFile && result) {
102396                     if (!symlinkedFiles)
102397                         symlinkedFiles = ts.createMap();
102398                     // Store the real path for the file'
102399                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
102400                     symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
102401                 }
102402                 return result;
102403             }) || false;
102404         }
102405     }
102406     /*@internal*/
102407     function handleNoEmitOptions(program, sourceFile, cancellationToken) {
102408         var options = program.getCompilerOptions();
102409         if (options.noEmit) {
102410             return { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
102411         }
102412         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
102413         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
102414         // get any preEmit diagnostics, not just the ones
102415         if (!options.noEmitOnError)
102416             return undefined;
102417         var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
102418         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
102419             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
102420         }
102421         return diagnostics.length > 0 ?
102422             { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true } :
102423             undefined;
102424     }
102425     ts.handleNoEmitOptions = handleNoEmitOptions;
102426     /* @internal */
102427     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
102428         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
102429         return {
102430             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
102431             readDirectory: function (root, extensions, excludes, includes, depth) {
102432                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
102433                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
102434             },
102435             readFile: function (f) { return directoryStructureHost.readFile(f); },
102436             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
102437             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
102438             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
102439             trace: host.trace ? function (s) { return host.trace(s); } : undefined
102440         };
102441     }
102442     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
102443     /* @internal */
102444     function createPrependNodes(projectReferences, getCommandLine, readFile) {
102445         if (!projectReferences)
102446             return ts.emptyArray;
102447         var nodes;
102448         for (var i = 0; i < projectReferences.length; i++) {
102449             var ref = projectReferences[i];
102450             var resolvedRefOpts = getCommandLine(ref, i);
102451             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
102452                 var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
102453                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
102454                 if (!out)
102455                     continue;
102456                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
102457                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
102458                 (nodes || (nodes = [])).push(node);
102459             }
102460         }
102461         return nodes || ts.emptyArray;
102462     }
102463     ts.createPrependNodes = createPrependNodes;
102464     function resolveProjectReferencePath(hostOrRef, ref) {
102465         var passedInRef = ref ? ref : hostOrRef;
102466         return ts.resolveConfigFileProjectName(passedInRef.path);
102467     }
102468     ts.resolveProjectReferencePath = resolveProjectReferencePath;
102469     /* @internal */
102470     /**
102471      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
102472      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
102473      * This returns a diagnostic even if the module will be an untyped module.
102474      */
102475     function getResolutionDiagnostic(options, _a) {
102476         var extension = _a.extension;
102477         switch (extension) {
102478             case ".ts" /* Ts */:
102479             case ".d.ts" /* Dts */:
102480                 // These are always allowed.
102481                 return undefined;
102482             case ".tsx" /* Tsx */:
102483                 return needJsx();
102484             case ".jsx" /* Jsx */:
102485                 return needJsx() || needAllowJs();
102486             case ".js" /* Js */:
102487                 return needAllowJs();
102488             case ".json" /* Json */:
102489                 return needResolveJsonModule();
102490         }
102491         function needJsx() {
102492             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
102493         }
102494         function needAllowJs() {
102495             return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
102496         }
102497         function needResolveJsonModule() {
102498             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
102499         }
102500     }
102501     ts.getResolutionDiagnostic = getResolutionDiagnostic;
102502     function getModuleNames(_a) {
102503         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
102504         var res = imports.map(function (i) { return i.text; });
102505         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
102506             var aug = moduleAugmentations_1[_i];
102507             if (aug.kind === 10 /* StringLiteral */) {
102508                 res.push(aug.text);
102509             }
102510             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
102511         }
102512         return res;
102513     }
102514 })(ts || (ts = {}));
102515 /*@internal*/
102516 var ts;
102517 (function (ts) {
102518     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
102519         var outputFiles = [];
102520         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
102521         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
102522         function writeFile(fileName, text, writeByteOrderMark) {
102523             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
102524         }
102525     }
102526     ts.getFileEmitOutput = getFileEmitOutput;
102527     var BuilderState;
102528     (function (BuilderState) {
102529         /**
102530          * Get the referencedFile from the imported module symbol
102531          */
102532         function getReferencedFileFromImportedModuleSymbol(symbol) {
102533             if (symbol.declarations && symbol.declarations[0]) {
102534                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
102535                 return declarationSourceFile && declarationSourceFile.resolvedPath;
102536             }
102537         }
102538         /**
102539          * Get the referencedFile from the import name node from file
102540          */
102541         function getReferencedFileFromImportLiteral(checker, importName) {
102542             var symbol = checker.getSymbolAtLocation(importName);
102543             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
102544         }
102545         /**
102546          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
102547          */
102548         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
102549             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
102550         }
102551         /**
102552          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
102553          */
102554         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
102555             var referencedFiles;
102556             // We need to use a set here since the code can contain the same import twice,
102557             // but that will only be one dependency.
102558             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
102559             if (sourceFile.imports && sourceFile.imports.length > 0) {
102560                 var checker = program.getTypeChecker();
102561                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
102562                     var importName = _a[_i];
102563                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
102564                     if (declarationSourceFilePath) {
102565                         addReferencedFile(declarationSourceFilePath);
102566                     }
102567                 }
102568             }
102569             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
102570             // Handle triple slash references
102571             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
102572                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
102573                     var referencedFile = _c[_b];
102574                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
102575                     addReferencedFile(referencedPath);
102576                 }
102577             }
102578             // Handle type reference directives
102579             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
102580                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
102581                     if (!resolvedTypeReferenceDirective) {
102582                         return;
102583                     }
102584                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
102585                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
102586                     addReferencedFile(typeFilePath);
102587                 });
102588             }
102589             // Add module augmentation as references
102590             if (sourceFile.moduleAugmentations.length) {
102591                 var checker = program.getTypeChecker();
102592                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
102593                     var moduleName = _e[_d];
102594                     if (!ts.isStringLiteral(moduleName)) {
102595                         continue;
102596                     }
102597                     var symbol = checker.getSymbolAtLocation(moduleName);
102598                     if (!symbol) {
102599                         continue;
102600                     }
102601                     // Add any file other than our own as reference
102602                     addReferenceFromAmbientModule(symbol);
102603                 }
102604             }
102605             // From ambient modules
102606             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
102607                 var ambientModule = _g[_f];
102608                 if (ambientModule.declarations.length > 1) {
102609                     addReferenceFromAmbientModule(ambientModule);
102610                 }
102611             }
102612             return referencedFiles;
102613             function addReferenceFromAmbientModule(symbol) {
102614                 // Add any file other than our own as reference
102615                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
102616                     var declaration = _a[_i];
102617                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
102618                     if (declarationSourceFile &&
102619                         declarationSourceFile !== sourceFile) {
102620                         addReferencedFile(declarationSourceFile.resolvedPath);
102621                     }
102622                 }
102623             }
102624             function addReferencedFile(referencedPath) {
102625                 if (!referencedFiles) {
102626                     referencedFiles = ts.createMap();
102627                 }
102628                 referencedFiles.set(referencedPath, true);
102629             }
102630         }
102631         /**
102632          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
102633          */
102634         function canReuseOldState(newReferencedMap, oldState) {
102635             return oldState && !oldState.referencedMap === !newReferencedMap;
102636         }
102637         BuilderState.canReuseOldState = canReuseOldState;
102638         /**
102639          * Creates the state of file references and signature for the new program from oldState if it is safe
102640          */
102641         function create(newProgram, getCanonicalFileName, oldState) {
102642             var fileInfos = ts.createMap();
102643             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
102644             var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
102645             var hasCalledUpdateShapeSignature = ts.createMap();
102646             var useOldState = canReuseOldState(referencedMap, oldState);
102647             // Create the reference map, and set the file infos
102648             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
102649                 var sourceFile = _a[_i];
102650                 var version_1 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
102651                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
102652                 if (referencedMap) {
102653                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
102654                     if (newReferences) {
102655                         referencedMap.set(sourceFile.resolvedPath, newReferences);
102656                     }
102657                     // Copy old visible to outside files map
102658                     if (useOldState) {
102659                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
102660                         if (exportedModules) {
102661                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
102662                         }
102663                     }
102664                 }
102665                 fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
102666             }
102667             return {
102668                 fileInfos: fileInfos,
102669                 referencedMap: referencedMap,
102670                 exportedModulesMap: exportedModulesMap,
102671                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
102672             };
102673         }
102674         BuilderState.create = create;
102675         /**
102676          * Releases needed properties
102677          */
102678         function releaseCache(state) {
102679             state.allFilesExcludingDefaultLibraryFile = undefined;
102680             state.allFileNames = undefined;
102681         }
102682         BuilderState.releaseCache = releaseCache;
102683         /**
102684          * Creates a clone of the state
102685          */
102686         function clone(state) {
102687             var fileInfos = ts.createMap();
102688             state.fileInfos.forEach(function (value, key) {
102689                 fileInfos.set(key, __assign({}, value));
102690             });
102691             // Dont need to backup allFiles info since its cache anyway
102692             return {
102693                 fileInfos: fileInfos,
102694                 referencedMap: cloneMapOrUndefined(state.referencedMap),
102695                 exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap),
102696                 hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature),
102697             };
102698         }
102699         BuilderState.clone = clone;
102700         /**
102701          * Gets the files affected by the path from the program
102702          */
102703         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
102704             // Since the operation could be cancelled, the signatures are always stored in the cache
102705             // They will be committed once it is safe to use them
102706             // eg when calling this api from tsserver, if there is no cancellation of the operation
102707             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
102708             var signatureCache = cacheToUpdateSignature || ts.createMap();
102709             var sourceFile = programOfThisState.getSourceFileByPath(path);
102710             if (!sourceFile) {
102711                 return ts.emptyArray;
102712             }
102713             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
102714                 return [sourceFile];
102715             }
102716             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
102717             if (!cacheToUpdateSignature) {
102718                 // Commit all the signatures in the signature cache
102719                 updateSignaturesFromCache(state, signatureCache);
102720             }
102721             return result;
102722         }
102723         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
102724         /**
102725          * Updates the signatures from the cache into state's fileinfo signatures
102726          * This should be called whenever it is safe to commit the state of the builder
102727          */
102728         function updateSignaturesFromCache(state, signatureCache) {
102729             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
102730         }
102731         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
102732         function updateSignatureOfFile(state, signature, path) {
102733             state.fileInfos.get(path).signature = signature;
102734             state.hasCalledUpdateShapeSignature.set(path, true);
102735         }
102736         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
102737         /**
102738          * Returns if the shape of the signature has changed since last emit
102739          */
102740         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102741             ts.Debug.assert(!!sourceFile);
102742             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
102743             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
102744             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
102745                 return false;
102746             }
102747             var info = state.fileInfos.get(sourceFile.resolvedPath);
102748             if (!info)
102749                 return ts.Debug.fail();
102750             var prevSignature = info.signature;
102751             var latestSignature;
102752             if (sourceFile.isDeclarationFile) {
102753                 latestSignature = sourceFile.version;
102754                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
102755                     // All the references in this file are exported
102756                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
102757                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
102758                 }
102759             }
102760             else {
102761                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
102762                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
102763                 /*customTransformers*/ undefined, 
102764                 /*forceDtsEmit*/ true);
102765                 var firstDts_1 = emitOutput_1.outputFiles &&
102766                     programOfThisState.getCompilerOptions().declarationMap ?
102767                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
102768                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
102769                 if (firstDts_1) {
102770                     ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); });
102771                     latestSignature = computeHash(firstDts_1.text);
102772                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
102773                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
102774                     }
102775                 }
102776                 else {
102777                     latestSignature = prevSignature; // TODO: GH#18217
102778                 }
102779             }
102780             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
102781             return !prevSignature || latestSignature !== prevSignature;
102782         }
102783         BuilderState.updateShapeSignature = updateShapeSignature;
102784         /**
102785          * Coverts the declaration emit result into exported modules map
102786          */
102787         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
102788             if (!exportedModulesFromDeclarationEmit) {
102789                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
102790                 return;
102791             }
102792             var exportedModules;
102793             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
102794             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
102795             function addExportedModule(exportedModulePath) {
102796                 if (exportedModulePath) {
102797                     if (!exportedModules) {
102798                         exportedModules = ts.createMap();
102799                     }
102800                     exportedModules.set(exportedModulePath, true);
102801                 }
102802             }
102803         }
102804         /**
102805          * Updates the exported modules from cache into state's exported modules map
102806          * This should be called whenever it is safe to commit the state of the builder
102807          */
102808         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
102809             if (exportedModulesMapCache) {
102810                 ts.Debug.assert(!!state.exportedModulesMap);
102811                 exportedModulesMapCache.forEach(function (exportedModules, path) {
102812                     if (exportedModules) {
102813                         state.exportedModulesMap.set(path, exportedModules);
102814                     }
102815                     else {
102816                         state.exportedModulesMap.delete(path);
102817                     }
102818                 });
102819             }
102820         }
102821         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
102822         /**
102823          * Get all the dependencies of the sourceFile
102824          */
102825         function getAllDependencies(state, programOfThisState, sourceFile) {
102826             var compilerOptions = programOfThisState.getCompilerOptions();
102827             // With --out or --outFile all outputs go into single file, all files depend on each other
102828             if (compilerOptions.outFile || compilerOptions.out) {
102829                 return getAllFileNames(state, programOfThisState);
102830             }
102831             // If this is non module emit, or its a global file, it depends on all the source files
102832             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
102833                 return getAllFileNames(state, programOfThisState);
102834             }
102835             // Get the references, traversing deep from the referenceMap
102836             var seenMap = ts.createMap();
102837             var queue = [sourceFile.resolvedPath];
102838             while (queue.length) {
102839                 var path = queue.pop();
102840                 if (!seenMap.has(path)) {
102841                     seenMap.set(path, true);
102842                     var references = state.referencedMap.get(path);
102843                     if (references) {
102844                         var iterator = references.keys();
102845                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
102846                             queue.push(iterResult.value);
102847                         }
102848                     }
102849                 }
102850             }
102851             return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
102852                 var file = programOfThisState.getSourceFileByPath(path);
102853                 return file ? file.fileName : path;
102854             }));
102855         }
102856         BuilderState.getAllDependencies = getAllDependencies;
102857         /**
102858          * Gets the names of all files from the program
102859          */
102860         function getAllFileNames(state, programOfThisState) {
102861             if (!state.allFileNames) {
102862                 var sourceFiles = programOfThisState.getSourceFiles();
102863                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
102864             }
102865             return state.allFileNames;
102866         }
102867         /**
102868          * Gets the files referenced by the the file path
102869          */
102870         function getReferencedByPaths(state, referencedFilePath) {
102871             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
102872                 var filePath = _a[0], referencesInFile = _a[1];
102873                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
102874             }));
102875         }
102876         BuilderState.getReferencedByPaths = getReferencedByPaths;
102877         /**
102878          * For script files that contains only ambient external modules, although they are not actually external module files,
102879          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
102880          * there are no point to rebuild all script files if these special files have changed. However, if any statement
102881          * in the file is not ambient external module, we treat it as a regular script file.
102882          */
102883         function containsOnlyAmbientModules(sourceFile) {
102884             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
102885                 var statement = _a[_i];
102886                 if (!ts.isModuleWithStringLiteralName(statement)) {
102887                     return false;
102888                 }
102889             }
102890             return true;
102891         }
102892         /**
102893          * Return true if file contains anything that augments to global scope we need to build them as if
102894          * they are global files as well as module
102895          */
102896         function containsGlobalScopeAugmentation(sourceFile) {
102897             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
102898         }
102899         /**
102900          * Return true if the file will invalidate all files because it affectes global scope
102901          */
102902         function isFileAffectingGlobalScope(sourceFile) {
102903             return containsGlobalScopeAugmentation(sourceFile) ||
102904                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
102905         }
102906         /**
102907          * Gets all files of the program excluding the default library file
102908          */
102909         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
102910             // Use cached result
102911             if (state.allFilesExcludingDefaultLibraryFile) {
102912                 return state.allFilesExcludingDefaultLibraryFile;
102913             }
102914             var result;
102915             if (firstSourceFile)
102916                 addSourceFile(firstSourceFile);
102917             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
102918                 var sourceFile = _a[_i];
102919                 if (sourceFile !== firstSourceFile) {
102920                     addSourceFile(sourceFile);
102921                 }
102922             }
102923             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
102924             return state.allFilesExcludingDefaultLibraryFile;
102925             function addSourceFile(sourceFile) {
102926                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
102927                     (result || (result = [])).push(sourceFile);
102928                 }
102929             }
102930         }
102931         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
102932         /**
102933          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
102934          */
102935         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
102936             var compilerOptions = programOfThisState.getCompilerOptions();
102937             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
102938             // so returning the file itself is good enough.
102939             if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
102940                 return [sourceFileWithUpdatedShape];
102941             }
102942             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102943         }
102944         /**
102945          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
102946          */
102947         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102948             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
102949                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102950             }
102951             var compilerOptions = programOfThisState.getCompilerOptions();
102952             if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
102953                 return [sourceFileWithUpdatedShape];
102954             }
102955             // Now we need to if each file in the referencedBy list has a shape change as well.
102956             // Because if so, its own referencedBy files need to be saved as well to make the
102957             // emitting result consistent with files on disk.
102958             var seenFileNamesMap = ts.createMap();
102959             // Start with the paths this file was referenced by
102960             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
102961             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
102962             while (queue.length > 0) {
102963                 var currentPath = queue.pop();
102964                 if (!seenFileNamesMap.has(currentPath)) {
102965                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
102966                     seenFileNamesMap.set(currentPath, currentSourceFile);
102967                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
102968                         queue.push.apply(// TODO: GH#18217
102969                         queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
102970                     }
102971                 }
102972             }
102973             // Return array of values that needs emit
102974             // Return array of values that needs emit
102975             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
102976         }
102977     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
102978     function cloneMapOrUndefined(map) {
102979         return map ? ts.cloneMap(map) : undefined;
102980     }
102981     ts.cloneMapOrUndefined = cloneMapOrUndefined;
102982 })(ts || (ts = {}));
102983 /*@internal*/
102984 var ts;
102985 (function (ts) {
102986     var BuilderFileEmit;
102987     (function (BuilderFileEmit) {
102988         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
102989         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
102990     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
102991     function hasSameKeys(map1, map2) {
102992         // Has same size and every key is present in both maps
102993         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
102994     }
102995     /**
102996      * Create the state so that we can iterate on changedFiles/affected files
102997      */
102998     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
102999         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
103000         state.program = newProgram;
103001         var compilerOptions = newProgram.getCompilerOptions();
103002         state.compilerOptions = compilerOptions;
103003         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
103004         if (!compilerOptions.outFile && !compilerOptions.out) {
103005             state.semanticDiagnosticsPerFile = ts.createMap();
103006         }
103007         state.changedFilesSet = ts.createMap();
103008         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
103009         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
103010         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
103011             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
103012         if (useOldState) {
103013             // Verify the sanity of old state
103014             if (!oldState.currentChangedFilePath) {
103015                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
103016                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
103017             }
103018             var changedFilesSet = oldState.changedFilesSet;
103019             if (canCopySemanticDiagnostics) {
103020                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
103021             }
103022             // Copy old state's changed files set
103023             if (changedFilesSet) {
103024                 ts.copyEntries(changedFilesSet, state.changedFilesSet);
103025             }
103026             if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
103027                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
103028                 state.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(oldState.affectedFilesPendingEmitKind);
103029                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
103030                 state.seenAffectedFiles = ts.createMap();
103031             }
103032         }
103033         // Update changed files and copy semantic diagnostics if we can
103034         var referencedMap = state.referencedMap;
103035         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
103036         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
103037         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
103038         state.fileInfos.forEach(function (info, sourceFilePath) {
103039             var oldInfo;
103040             var newReferences;
103041             // if not using old state, every file is changed
103042             if (!useOldState ||
103043                 // File wasnt present in old state
103044                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
103045                 // versions dont match
103046                 oldInfo.version !== info.version ||
103047                 // Referenced files changed
103048                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
103049                 // Referenced file was deleted in the new program
103050                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
103051                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
103052                 state.changedFilesSet.set(sourceFilePath, true);
103053             }
103054             else if (canCopySemanticDiagnostics) {
103055                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
103056                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
103057                     return;
103058                 }
103059                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
103060                     return;
103061                 }
103062                 // Unchanged file copy diagnostics
103063                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
103064                 if (diagnostics) {
103065                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
103066                     if (!state.semanticDiagnosticsFromOldState) {
103067                         state.semanticDiagnosticsFromOldState = ts.createMap();
103068                     }
103069                     state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
103070                 }
103071             }
103072         });
103073         // If the global file is removed, add all files as changed
103074         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
103075             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
103076                 .forEach(function (file) { return state.changedFilesSet.set(file.resolvedPath, true); });
103077         }
103078         else if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
103079             // Add all files to affectedFilesPendingEmit since emit changed
103080             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
103081             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
103082             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103083         }
103084         state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
103085         return state;
103086     }
103087     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
103088         if (!diagnostics.length)
103089             return ts.emptyArray;
103090         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
103091         return diagnostics.map(function (diagnostic) {
103092             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
103093             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103094             result.source = diagnostic.source;
103095             var relatedInformation = diagnostic.relatedInformation;
103096             result.relatedInformation = relatedInformation ?
103097                 relatedInformation.length ?
103098                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
103099                     ts.emptyArray :
103100                 undefined;
103101             return result;
103102         });
103103         function toPath(path) {
103104             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103105         }
103106     }
103107     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
103108         var file = diagnostic.file;
103109         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
103110     }
103111     /**
103112      * Releases program and other related not needed properties
103113      */
103114     function releaseCache(state) {
103115         ts.BuilderState.releaseCache(state);
103116         state.program = undefined;
103117     }
103118     /**
103119      * Creates a clone of the state
103120      */
103121     function cloneBuilderProgramState(state) {
103122         var newState = ts.BuilderState.clone(state);
103123         newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
103124         newState.changedFilesSet = ts.cloneMap(state.changedFilesSet);
103125         newState.affectedFiles = state.affectedFiles;
103126         newState.affectedFilesIndex = state.affectedFilesIndex;
103127         newState.currentChangedFilePath = state.currentChangedFilePath;
103128         newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures);
103129         newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
103130         newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles);
103131         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
103132         newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
103133         newState.program = state.program;
103134         newState.compilerOptions = state.compilerOptions;
103135         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
103136         newState.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(state.affectedFilesPendingEmitKind);
103137         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
103138         newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles);
103139         newState.programEmitComplete = state.programEmitComplete;
103140         return newState;
103141     }
103142     /**
103143      * Verifies that source file is ok to be used in calls that arent handled by next
103144      */
103145     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
103146         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
103147     }
103148     /**
103149      * This function returns the next affected file to be processed.
103150      * Note that until doneAffected is called it would keep reporting same result
103151      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
103152      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
103153      */
103154     function getNextAffectedFile(state, cancellationToken, computeHash) {
103155         while (true) {
103156             var affectedFiles = state.affectedFiles;
103157             if (affectedFiles) {
103158                 var seenAffectedFiles = state.seenAffectedFiles;
103159                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
103160                 while (affectedFilesIndex < affectedFiles.length) {
103161                     var affectedFile = affectedFiles[affectedFilesIndex];
103162                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
103163                         // Set the next affected file as seen and remove the cached semantic diagnostics
103164                         state.affectedFilesIndex = affectedFilesIndex;
103165                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
103166                         return affectedFile;
103167                     }
103168                     affectedFilesIndex++;
103169                 }
103170                 // Remove the changed file from the change set
103171                 state.changedFilesSet.delete(state.currentChangedFilePath);
103172                 state.currentChangedFilePath = undefined;
103173                 // Commit the changes in file signature
103174                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
103175                 state.currentAffectedFilesSignatures.clear();
103176                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
103177                 state.affectedFiles = undefined;
103178             }
103179             // Get next changed file
103180             var nextKey = state.changedFilesSet.keys().next();
103181             if (nextKey.done) {
103182                 // Done
103183                 return undefined;
103184             }
103185             // With --out or --outFile all outputs go into single file
103186             // so operations are performed directly on program, return program
103187             var program = ts.Debug.checkDefined(state.program);
103188             var compilerOptions = program.getCompilerOptions();
103189             if (compilerOptions.outFile || compilerOptions.out) {
103190                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103191                 return program;
103192             }
103193             // Get next batch of affected files
103194             state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
103195             if (state.exportedModulesMap) {
103196                 state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
103197             }
103198             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
103199             state.currentChangedFilePath = nextKey.value;
103200             state.affectedFilesIndex = 0;
103201             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103202         }
103203     }
103204     /**
103205      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
103206      */
103207     function getNextAffectedFilePendingEmit(state) {
103208         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
103209         if (affectedFilesPendingEmit) {
103210             var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap());
103211             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
103212                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
103213                 if (affectedFile) {
103214                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
103215                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
103216                     if (seenKind === undefined || seenKind < emitKind) {
103217                         // emit this file
103218                         state.affectedFilesPendingEmitIndex = i;
103219                         return { affectedFile: affectedFile, emitKind: emitKind };
103220                     }
103221                 }
103222             }
103223             state.affectedFilesPendingEmit = undefined;
103224             state.affectedFilesPendingEmitKind = undefined;
103225             state.affectedFilesPendingEmitIndex = undefined;
103226         }
103227         return undefined;
103228     }
103229     /**
103230      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
103231      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
103232      */
103233     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
103234         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
103235         // If affected files is everything except default library, then nothing more to do
103236         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
103237             if (!state.cleanedDiagnosticsOfLibFiles) {
103238                 state.cleanedDiagnosticsOfLibFiles = true;
103239                 var program_1 = ts.Debug.checkDefined(state.program);
103240                 var options_2 = program_1.getCompilerOptions();
103241                 ts.forEach(program_1.getSourceFiles(), function (f) {
103242                     return program_1.isSourceFileDefaultLibrary(f) &&
103243                         !ts.skipTypeChecking(f, options_2, program_1) &&
103244                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
103245                 });
103246             }
103247             return;
103248         }
103249         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
103250             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
103251         }
103252     }
103253     /**
103254      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
103255      * Also we need to make sure signature is updated for these files
103256      */
103257     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
103258         removeSemanticDiagnosticsOf(state, path);
103259         if (!state.changedFilesSet.has(path)) {
103260             var program = ts.Debug.checkDefined(state.program);
103261             var sourceFile = program.getSourceFileByPath(path);
103262             if (sourceFile) {
103263                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
103264                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
103265                 // This ensures that we dont later during incremental builds considering wrong signature.
103266                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
103267                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
103268                 // If not dts emit, nothing more to do
103269                 if (ts.getEmitDeclarations(state.compilerOptions)) {
103270                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
103271                 }
103272             }
103273         }
103274         return false;
103275     }
103276     /**
103277      * Removes semantic diagnostics for path and
103278      * returns true if there are no more semantic diagnostics from the old state
103279      */
103280     function removeSemanticDiagnosticsOf(state, path) {
103281         if (!state.semanticDiagnosticsFromOldState) {
103282             return true;
103283         }
103284         state.semanticDiagnosticsFromOldState.delete(path);
103285         state.semanticDiagnosticsPerFile.delete(path);
103286         return !state.semanticDiagnosticsFromOldState.size;
103287     }
103288     function isChangedSignagure(state, path) {
103289         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
103290         var oldSignagure = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
103291         return newSignature !== oldSignagure;
103292     }
103293     /**
103294      * Iterate on referencing modules that export entities from affected file
103295      */
103296     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
103297         // If there was change in signature (dts output) for the changed file,
103298         // then only we need to handle pending file emit
103299         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
103300             return;
103301         }
103302         if (!isChangedSignagure(state, affectedFile.resolvedPath))
103303             return;
103304         // Since isolated modules dont change js files, files affected by change in signature is itself
103305         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
103306         if (state.compilerOptions.isolatedModules) {
103307             var seenFileNamesMap = ts.createMap();
103308             seenFileNamesMap.set(affectedFile.resolvedPath, true);
103309             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
103310             while (queue.length > 0) {
103311                 var currentPath = queue.pop();
103312                 if (!seenFileNamesMap.has(currentPath)) {
103313                     seenFileNamesMap.set(currentPath, true);
103314                     var result = fn(state, currentPath);
103315                     if (result && isChangedSignagure(state, currentPath)) {
103316                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
103317                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
103318                     }
103319                 }
103320             }
103321         }
103322         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103323         var seenFileAndExportsOfFile = ts.createMap();
103324         // Go through exported modules from cache first
103325         // If exported modules has path, all files referencing file exported from are affected
103326         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103327             return exportedModules &&
103328                 exportedModules.has(affectedFile.resolvedPath) &&
103329                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103330         })) {
103331             return;
103332         }
103333         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103334         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103335             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103336                 exportedModules.has(affectedFile.resolvedPath) &&
103337                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103338         });
103339     }
103340     /**
103341      * Iterate on files referencing referencedPath
103342      */
103343     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
103344         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
103345             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
103346         });
103347     }
103348     /**
103349      * fn on file and iterate on anything that exports this file
103350      */
103351     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
103352         if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) {
103353             return false;
103354         }
103355         if (fn(state, filePath)) {
103356             // If there are no more diagnostics from old cache, done
103357             return true;
103358         }
103359         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103360         // Go through exported modules from cache first
103361         // If exported modules has path, all files referencing file exported from are affected
103362         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103363             return exportedModules &&
103364                 exportedModules.has(filePath) &&
103365                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103366         })) {
103367             return true;
103368         }
103369         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103370         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103371             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103372                 exportedModules.has(filePath) &&
103373                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103374         })) {
103375             return true;
103376         }
103377         // Remove diagnostics of files that import this file (without going to exports of referencing files)
103378         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
103379             return referencesInFile.has(filePath) &&
103380                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
103381                 fn(state, referencingFilePath);
103382         } // Dont add to seen since this is not yet done with the export removal
103383         );
103384     }
103385     /**
103386      * This is called after completing operation on the next affected file.
103387      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
103388      */
103389     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103390         if (isBuildInfoEmit) {
103391             state.emittedBuildInfo = true;
103392         }
103393         else if (affected === state.program) {
103394             state.changedFilesSet.clear();
103395             state.programEmitComplete = true;
103396         }
103397         else {
103398             state.seenAffectedFiles.set(affected.resolvedPath, true);
103399             if (emitKind !== undefined) {
103400                 (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.resolvedPath, emitKind);
103401             }
103402             if (isPendingEmit) {
103403                 state.affectedFilesPendingEmitIndex++;
103404             }
103405             else {
103406                 state.affectedFilesIndex++;
103407             }
103408         }
103409     }
103410     /**
103411      * Returns the result with affected file
103412      */
103413     function toAffectedFileResult(state, result, affected) {
103414         doneWithAffectedFile(state, affected);
103415         return { result: result, affected: affected };
103416     }
103417     /**
103418      * Returns the result with affected file
103419      */
103420     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103421         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
103422         return { result: result, affected: affected };
103423     }
103424     /**
103425      * Gets semantic diagnostics for the file which are
103426      * bindAndCheckDiagnostics (from cache) and program diagnostics
103427      */
103428     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103429         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
103430     }
103431     /**
103432      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
103433      * Note that it is assumed that when asked about binder and checker diagnostics, the file has been taken out of affected files/changed file set
103434      */
103435     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103436         var path = sourceFile.resolvedPath;
103437         if (state.semanticDiagnosticsPerFile) {
103438             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
103439             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
103440             if (cachedDiagnostics) {
103441                 return cachedDiagnostics;
103442             }
103443         }
103444         // Diagnostics werent cached, get them from program, and cache the result
103445         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
103446         if (state.semanticDiagnosticsPerFile) {
103447             state.semanticDiagnosticsPerFile.set(path, diagnostics);
103448         }
103449         return diagnostics;
103450     }
103451     /**
103452      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
103453      */
103454     function getProgramBuildInfo(state, getCanonicalFileName) {
103455         if (state.compilerOptions.outFile || state.compilerOptions.out)
103456             return undefined;
103457         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
103458         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
103459         var fileInfos = {};
103460         state.fileInfos.forEach(function (value, key) {
103461             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
103462             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
103463         });
103464         var result = {
103465             fileInfos: fileInfos,
103466             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
103467         };
103468         if (state.referencedMap) {
103469             var referencedMap = {};
103470             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
103471                 var key = _a[_i];
103472                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103473             }
103474             result.referencedMap = referencedMap;
103475         }
103476         if (state.exportedModulesMap) {
103477             var exportedModulesMap = {};
103478             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
103479                 var key = _c[_b];
103480                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
103481                 // Not in temporary cache, use existing value
103482                 if (newValue === undefined)
103483                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103484                 // Value in cache and has updated value map, use that
103485                 else if (newValue)
103486                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103487             }
103488             result.exportedModulesMap = exportedModulesMap;
103489         }
103490         if (state.semanticDiagnosticsPerFile) {
103491             var semanticDiagnosticsPerFile = [];
103492             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
103493                 var key = _e[_d];
103494                 var value = state.semanticDiagnosticsPerFile.get(key);
103495                 semanticDiagnosticsPerFile.push(value.length ?
103496                     [
103497                         relativeToBuildInfo(key),
103498                         state.hasReusableDiagnostic ?
103499                             value :
103500                             convertToReusableDiagnostics(value, relativeToBuildInfo)
103501                     ] :
103502                     relativeToBuildInfo(key));
103503             }
103504             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
103505         }
103506         return result;
103507         function relativeToBuildInfoEnsuringAbsolutePath(path) {
103508             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
103509         }
103510         function relativeToBuildInfo(path) {
103511             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
103512         }
103513     }
103514     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
103515         var result = {};
103516         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
103517         for (var name in options) {
103518             if (ts.hasProperty(options, name)) {
103519                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
103520             }
103521         }
103522         if (result.configFilePath) {
103523             result.configFilePath = relativeToBuildInfo(result.configFilePath);
103524         }
103525         return result;
103526     }
103527     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
103528         if (option) {
103529             if (option.type === "list") {
103530                 var values = value;
103531                 if (option.element.isFilePath && values.length) {
103532                     return values.map(relativeToBuildInfo);
103533                 }
103534             }
103535             else if (option.isFilePath) {
103536                 return relativeToBuildInfo(value);
103537             }
103538         }
103539         return value;
103540     }
103541     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
103542         ts.Debug.assert(!!diagnostics.length);
103543         return diagnostics.map(function (diagnostic) {
103544             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
103545             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103546             result.source = diagnostic.source;
103547             var relatedInformation = diagnostic.relatedInformation;
103548             result.relatedInformation = relatedInformation ?
103549                 relatedInformation.length ?
103550                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
103551                     ts.emptyArray :
103552                 undefined;
103553             return result;
103554         });
103555     }
103556     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
103557         var file = diagnostic.file;
103558         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
103559     }
103560     var BuilderProgramKind;
103561     (function (BuilderProgramKind) {
103562         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
103563         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
103564     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
103565     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103566         var host;
103567         var newProgram;
103568         var oldProgram;
103569         if (newProgramOrRootNames === undefined) {
103570             ts.Debug.assert(hostOrOptions === undefined);
103571             host = oldProgramOrHost;
103572             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103573             ts.Debug.assert(!!oldProgram);
103574             newProgram = oldProgram.getProgram();
103575         }
103576         else if (ts.isArray(newProgramOrRootNames)) {
103577             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103578             newProgram = ts.createProgram({
103579                 rootNames: newProgramOrRootNames,
103580                 options: hostOrOptions,
103581                 host: oldProgramOrHost,
103582                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
103583                 configFileParsingDiagnostics: configFileParsingDiagnostics,
103584                 projectReferences: projectReferences
103585             });
103586             host = oldProgramOrHost;
103587         }
103588         else {
103589             newProgram = newProgramOrRootNames;
103590             host = hostOrOptions;
103591             oldProgram = oldProgramOrHost;
103592             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
103593         }
103594         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
103595     }
103596     ts.getBuilderCreationParameters = getBuilderCreationParameters;
103597     function createBuilderProgram(kind, _a) {
103598         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103599         // Return same program if underlying program doesnt change
103600         var oldState = oldProgram && oldProgram.getState();
103601         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
103602             newProgram = undefined; // TODO: GH#18217
103603             oldState = undefined;
103604             return oldProgram;
103605         }
103606         /**
103607          * Create the canonical file name for identity
103608          */
103609         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103610         /**
103611          * Computing hash to for signature verification
103612          */
103613         var computeHash = host.createHash || ts.generateDjb2Hash;
103614         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
103615         var backupState;
103616         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
103617         // To ensure that we arent storing any references to old program or new program without state
103618         newProgram = undefined; // TODO: GH#18217
103619         oldProgram = undefined;
103620         oldState = undefined;
103621         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
103622         builderProgram.getState = function () { return state; };
103623         builderProgram.backupState = function () {
103624             ts.Debug.assert(backupState === undefined);
103625             backupState = cloneBuilderProgramState(state);
103626         };
103627         builderProgram.restoreState = function () {
103628             state = ts.Debug.checkDefined(backupState);
103629             backupState = undefined;
103630         };
103631         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
103632         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
103633         builderProgram.emit = emit;
103634         builderProgram.releaseProgram = function () {
103635             releaseCache(state);
103636             backupState = undefined;
103637         };
103638         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
103639             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103640         }
103641         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103642             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103643             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
103644         }
103645         else {
103646             ts.notImplemented();
103647         }
103648         return builderProgram;
103649         /**
103650          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
103651          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103652          * in that order would be used to write the files
103653          */
103654         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103655             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103656             var emitKind = 1 /* Full */;
103657             var isPendingEmitFile = false;
103658             if (!affected) {
103659                 if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
103660                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
103661                     if (!pendingAffectedFile) {
103662                         if (state.emittedBuildInfo) {
103663                             return undefined;
103664                         }
103665                         var affected_1 = ts.Debug.checkDefined(state.program);
103666                         return toAffectedFileEmitResult(state, 
103667                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103668                         // Otherwise just affected file
103669                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
103670                         /*isPendingEmitFile*/ false, 
103671                         /*isBuildInfoEmit*/ true);
103672                     }
103673                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
103674                     isPendingEmitFile = true;
103675                 }
103676                 else {
103677                     var program = ts.Debug.checkDefined(state.program);
103678                     if (state.programEmitComplete)
103679                         return undefined;
103680                     affected = program;
103681                 }
103682             }
103683             return toAffectedFileEmitResult(state, 
103684             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103685             // Otherwise just affected file
103686             ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile);
103687         }
103688         /**
103689          * Emits the JavaScript and declaration files.
103690          * When targetSource file is specified, emits the files corresponding to that source file,
103691          * otherwise for the whole program.
103692          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
103693          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
103694          * it will only emit all the affected files instead of whole program
103695          *
103696          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103697          * in that order would be used to write the files
103698          */
103699         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103700             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103701                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
103702                 var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
103703                 if (result)
103704                     return result;
103705                 if (!targetSourceFile) {
103706                     // Emit and report any errors we ran into.
103707                     var sourceMaps = [];
103708                     var emitSkipped = false;
103709                     var diagnostics = void 0;
103710                     var emittedFiles = [];
103711                     var affectedEmitResult = void 0;
103712                     while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
103713                         emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
103714                         diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
103715                         emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
103716                         sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
103717                     }
103718                     return {
103719                         emitSkipped: emitSkipped,
103720                         diagnostics: diagnostics || ts.emptyArray,
103721                         emittedFiles: emittedFiles,
103722                         sourceMaps: sourceMaps
103723                     };
103724                 }
103725             }
103726             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
103727         }
103728         /**
103729          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
103730          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
103731          */
103732         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
103733             while (true) {
103734                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103735                 if (!affected) {
103736                     // Done
103737                     return undefined;
103738                 }
103739                 else if (affected === state.program) {
103740                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
103741                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
103742                 }
103743                 // Add file to affected file pending emit to handle for later emit time
103744                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103745                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
103746                 }
103747                 // Get diagnostics for the affected file if its not ignored
103748                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
103749                     // Get next affected file
103750                     doneWithAffectedFile(state, affected);
103751                     continue;
103752                 }
103753                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
103754             }
103755         }
103756         /**
103757          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
103758          * The semantic diagnostics are cached and managed here
103759          * Note that it is assumed that when asked about semantic diagnostics through this API,
103760          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
103761          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
103762          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
103763          */
103764         function getSemanticDiagnostics(sourceFile, cancellationToken) {
103765             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
103766             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
103767             if (compilerOptions.outFile || compilerOptions.out) {
103768                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103769                 // We dont need to cache the diagnostics just return them from program
103770                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
103771             }
103772             if (sourceFile) {
103773                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
103774             }
103775             // When semantic builder asks for diagnostics of the whole program,
103776             // ensure that all the affected files are handled
103777             // eslint-disable-next-line no-empty
103778             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
103779             }
103780             var diagnostics;
103781             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
103782                 var sourceFile_1 = _a[_i];
103783                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
103784             }
103785             return diagnostics || ts.emptyArray;
103786         }
103787     }
103788     ts.createBuilderProgram = createBuilderProgram;
103789     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
103790         if (!state.affectedFilesPendingEmit)
103791             state.affectedFilesPendingEmit = [];
103792         if (!state.affectedFilesPendingEmitKind)
103793             state.affectedFilesPendingEmitKind = ts.createMap();
103794         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
103795         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
103796         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
103797         // affectedFilesPendingEmitIndex === undefined
103798         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
103799         //   so start from 0 as array would be affectedFilesPendingEmit
103800         // else, continue to iterate from existing index, the current set is appended to existing files
103801         if (state.affectedFilesPendingEmitIndex === undefined) {
103802             state.affectedFilesPendingEmitIndex = 0;
103803         }
103804     }
103805     function getMapOfReferencedSet(mapLike, toPath) {
103806         if (!mapLike)
103807             return undefined;
103808         var map = ts.createMap();
103809         // Copies keys/values from template. Note that for..in will not throw if
103810         // template is undefined, and instead will just exit the loop.
103811         for (var key in mapLike) {
103812             if (ts.hasProperty(mapLike, key)) {
103813                 map.set(toPath(key), ts.arrayToSet(mapLike[key], toPath));
103814             }
103815         }
103816         return map;
103817     }
103818     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
103819         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
103820         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103821         var fileInfos = ts.createMap();
103822         for (var key in program.fileInfos) {
103823             if (ts.hasProperty(program.fileInfos, key)) {
103824                 fileInfos.set(toPath(key), program.fileInfos[key]);
103825             }
103826         }
103827         var state = {
103828             fileInfos: fileInfos,
103829             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
103830             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
103831             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
103832             semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
103833             hasReusableDiagnostic: true
103834         };
103835         return {
103836             getState: function () { return state; },
103837             backupState: ts.noop,
103838             restoreState: ts.noop,
103839             getProgram: ts.notImplemented,
103840             getProgramOrUndefined: ts.returnUndefined,
103841             releaseProgram: ts.noop,
103842             getCompilerOptions: function () { return state.compilerOptions; },
103843             getSourceFile: ts.notImplemented,
103844             getSourceFiles: ts.notImplemented,
103845             getOptionsDiagnostics: ts.notImplemented,
103846             getGlobalDiagnostics: ts.notImplemented,
103847             getConfigFileParsingDiagnostics: ts.notImplemented,
103848             getSyntacticDiagnostics: ts.notImplemented,
103849             getDeclarationDiagnostics: ts.notImplemented,
103850             getSemanticDiagnostics: ts.notImplemented,
103851             emit: ts.notImplemented,
103852             getAllDependencies: ts.notImplemented,
103853             getCurrentDirectory: ts.notImplemented,
103854             emitNextAffectedFile: ts.notImplemented,
103855             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
103856             close: ts.noop,
103857         };
103858         function toPath(path) {
103859             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103860         }
103861         function toAbsolutePath(path) {
103862             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
103863         }
103864     }
103865     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
103866     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
103867         return {
103868             getState: ts.notImplemented,
103869             backupState: ts.noop,
103870             restoreState: ts.noop,
103871             getProgram: getProgram,
103872             getProgramOrUndefined: function () { return state.program; },
103873             releaseProgram: function () { return state.program = undefined; },
103874             getCompilerOptions: function () { return state.compilerOptions; },
103875             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
103876             getSourceFiles: function () { return getProgram().getSourceFiles(); },
103877             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
103878             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
103879             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
103880             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
103881             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
103882             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
103883             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
103884             getAllDependencies: ts.notImplemented,
103885             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
103886             close: ts.noop,
103887         };
103888         function getProgram() {
103889             return ts.Debug.checkDefined(state.program);
103890         }
103891     }
103892     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
103893 })(ts || (ts = {}));
103894 var ts;
103895 (function (ts) {
103896     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103897         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103898     }
103899     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
103900     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103901         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103902     }
103903     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
103904     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103905         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103906         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
103907     }
103908     ts.createAbstractBuilder = createAbstractBuilder;
103909 })(ts || (ts = {}));
103910 /*@internal*/
103911 var ts;
103912 (function (ts) {
103913     function removeIgnoredPath(path) {
103914         // Consider whole staging folder as if node_modules changed.
103915         if (ts.endsWith(path, "/node_modules/.staging")) {
103916             return ts.removeSuffix(path, "/.staging");
103917         }
103918         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
103919             undefined :
103920             path;
103921     }
103922     ts.removeIgnoredPath = removeIgnoredPath;
103923     /**
103924      * Filter out paths like
103925      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
103926      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
103927      * @param dirPath
103928      */
103929     function canWatchDirectory(dirPath) {
103930         var rootLength = ts.getRootLength(dirPath);
103931         if (dirPath.length === rootLength) {
103932             // Ignore "/", "c:/"
103933             return false;
103934         }
103935         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
103936         if (nextDirectorySeparator === -1) {
103937             // ignore "/user", "c:/users" or "c:/folderAtRoot"
103938             return false;
103939         }
103940         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
103941         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
103942         if (isNonDirectorySeparatorRoot &&
103943             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
103944             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
103945             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
103946             if (nextDirectorySeparator === -1) {
103947                 // ignore "//vda1cs4850/c$/folderAtRoot"
103948                 return false;
103949             }
103950             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
103951         }
103952         if (isNonDirectorySeparatorRoot &&
103953             pathPartForUserCheck.search(/users\//i) !== 0) {
103954             // Paths like c:/folderAtRoot/subFolder are allowed
103955             return true;
103956         }
103957         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
103958             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
103959             if (searchIndex === 0) {
103960                 // Folder isnt at expected minimum levels
103961                 return false;
103962             }
103963         }
103964         return true;
103965     }
103966     ts.canWatchDirectory = canWatchDirectory;
103967     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
103968         var filesWithChangedSetOfUnresolvedImports;
103969         var filesWithInvalidatedResolutions;
103970         var filesWithInvalidatedNonRelativeUnresolvedImports;
103971         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
103972         var resolutionsWithFailedLookups = [];
103973         var resolvedFileToResolution = ts.createMultiMap();
103974         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
103975         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
103976         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
103977         // The key in the map is source file's path.
103978         // The values are Map of resolutions with key being name lookedup.
103979         var resolvedModuleNames = ts.createMap();
103980         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
103981         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
103982         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
103983         var resolvedTypeReferenceDirectives = ts.createMap();
103984         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
103985         /**
103986          * These are the extensions that failed lookup files will have by default,
103987          * any other extension of failed lookup will be store that path in custom failed lookup path
103988          * This helps in not having to comb through all resolutions when files are added/removed
103989          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
103990          */
103991         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
103992         var customFailedLookupPaths = ts.createMap();
103993         var directoryWatchesOfFailedLookups = ts.createMap();
103994         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
103995         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
103996         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
103997         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
103998         var typeRootsWatches = ts.createMap();
103999         return {
104000             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
104001             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
104002             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104003             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104004             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
104005             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
104006             resolveModuleNames: resolveModuleNames,
104007             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
104008             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
104009             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
104010             removeResolutionsOfFile: removeResolutionsOfFile,
104011             invalidateResolutionOfFile: invalidateResolutionOfFile,
104012             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
104013             createHasInvalidatedResolution: createHasInvalidatedResolution,
104014             updateTypeRootsWatch: updateTypeRootsWatch,
104015             closeTypeRootsWatch: closeTypeRootsWatch,
104016             clear: clear
104017         };
104018         function getResolvedModule(resolution) {
104019             return resolution.resolvedModule;
104020         }
104021         function getResolvedTypeReferenceDirective(resolution) {
104022             return resolution.resolvedTypeReferenceDirective;
104023         }
104024         function isInDirectoryPath(dir, file) {
104025             if (dir === undefined || file.length <= dir.length) {
104026                 return false;
104027             }
104028             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
104029         }
104030         function clear() {
104031             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
104032             customFailedLookupPaths.clear();
104033             nonRelativeExternalModuleResolutions.clear();
104034             closeTypeRootsWatch();
104035             resolvedModuleNames.clear();
104036             resolvedTypeReferenceDirectives.clear();
104037             resolvedFileToResolution.clear();
104038             resolutionsWithFailedLookups.length = 0;
104039             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104040             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104041             clearPerDirectoryResolutions();
104042         }
104043         function startRecordingFilesWithChangedResolutions() {
104044             filesWithChangedSetOfUnresolvedImports = [];
104045         }
104046         function finishRecordingFilesWithChangedResolutions() {
104047             var collected = filesWithChangedSetOfUnresolvedImports;
104048             filesWithChangedSetOfUnresolvedImports = undefined;
104049             return collected;
104050         }
104051         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
104052             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
104053                 return false;
104054             }
104055             // Invalidated if file has unresolved imports
104056             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
104057             return !!value && !!value.length;
104058         }
104059         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
104060             if (forceAllFilesAsInvalidated) {
104061                 // Any file asked would have invalidated resolution
104062                 filesWithInvalidatedResolutions = undefined;
104063                 return ts.returnTrue;
104064             }
104065             var collected = filesWithInvalidatedResolutions;
104066             filesWithInvalidatedResolutions = undefined;
104067             return function (path) { return (!!collected && collected.has(path)) ||
104068                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
104069         }
104070         function clearPerDirectoryResolutions() {
104071             perDirectoryResolvedModuleNames.clear();
104072             nonRelativeModuleNameCache.clear();
104073             perDirectoryResolvedTypeReferenceDirectives.clear();
104074             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
104075             nonRelativeExternalModuleResolutions.clear();
104076         }
104077         function finishCachingPerDirectoryResolution() {
104078             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
104079             clearPerDirectoryResolutions();
104080             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
104081                 if (watcher.refCount === 0) {
104082                     directoryWatchesOfFailedLookups.delete(path);
104083                     watcher.watcher.close();
104084                 }
104085             });
104086         }
104087         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
104088             var _a;
104089             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
104090             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
104091             if (!resolutionHost.getGlobalCache) {
104092                 return primaryResult;
104093             }
104094             // otherwise try to load typings from @types
104095             var globalCache = resolutionHost.getGlobalCache();
104096             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
104097                 // create different collection of failed lookup locations for second pass
104098                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
104099                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
104100                 if (resolvedModule) {
104101                     // Modify existing resolution so its saved in the directory cache as well
104102                     primaryResult.resolvedModule = resolvedModule;
104103                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
104104                     return primaryResult;
104105                 }
104106             }
104107             // Default return the result from the first pass
104108             return primaryResult;
104109         }
104110         function resolveNamesWithLocalCache(_a) {
104111             var _b;
104112             var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges;
104113             var path = resolutionHost.toPath(containingFile);
104114             var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
104115             var dirPath = ts.getDirectoryPath(path);
104116             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
104117             var perDirectoryResolution = perDirectoryCache.get(dirPath);
104118             if (!perDirectoryResolution) {
104119                 perDirectoryResolution = ts.createMap();
104120                 perDirectoryCache.set(dirPath, perDirectoryResolution);
104121             }
104122             var resolvedModules = [];
104123             var compilerOptions = resolutionHost.getCompilationSettings();
104124             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
104125             // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
104126             var program = resolutionHost.getCurrentProgram();
104127             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
104128             var unmatchedRedirects = oldRedirect ?
104129                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
104130                 !!redirectedReference;
104131             var seenNamesInFile = ts.createMap();
104132             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
104133                 var name = names_3[_i];
104134                 var resolution = resolutionsInFile.get(name);
104135                 // Resolution is valid if it is present and not invalidated
104136                 if (!seenNamesInFile.has(name) &&
104137                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
104138                     // If the name is unresolved import that was invalidated, recalculate
104139                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
104140                     var existingResolution = resolution;
104141                     var resolutionInDirectory = perDirectoryResolution.get(name);
104142                     if (resolutionInDirectory) {
104143                         resolution = resolutionInDirectory;
104144                     }
104145                     else {
104146                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
104147                         perDirectoryResolution.set(name, resolution);
104148                     }
104149                     resolutionsInFile.set(name, resolution);
104150                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
104151                     if (existingResolution) {
104152                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
104153                     }
104154                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
104155                         filesWithChangedSetOfUnresolvedImports.push(path);
104156                         // reset log changes to avoid recording the same file multiple times
104157                         logChanges = false;
104158                     }
104159                 }
104160                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
104161                 seenNamesInFile.set(name, true);
104162                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
104163             }
104164             // Stop watching and remove the unused name
104165             resolutionsInFile.forEach(function (resolution, name) {
104166                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
104167                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
104168                     resolutionsInFile.delete(name);
104169                 }
104170             });
104171             return resolvedModules;
104172             function resolutionIsEqualTo(oldResolution, newResolution) {
104173                 if (oldResolution === newResolution) {
104174                     return true;
104175                 }
104176                 if (!oldResolution || !newResolution) {
104177                     return false;
104178                 }
104179                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
104180                 var newResult = getResolutionWithResolvedFileName(newResolution);
104181                 if (oldResult === newResult) {
104182                     return true;
104183                 }
104184                 if (!oldResult || !newResult) {
104185                     return false;
104186                 }
104187                 return oldResult.resolvedFileName === newResult.resolvedFileName;
104188             }
104189         }
104190         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
104191             return resolveNamesWithLocalCache({
104192                 names: typeDirectiveNames,
104193                 containingFile: containingFile,
104194                 redirectedReference: redirectedReference,
104195                 cache: resolvedTypeReferenceDirectives,
104196                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
104197                 loader: ts.resolveTypeReferenceDirective,
104198                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
104199                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
104200             });
104201         }
104202         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
104203             return resolveNamesWithLocalCache({
104204                 names: moduleNames,
104205                 containingFile: containingFile,
104206                 redirectedReference: redirectedReference,
104207                 cache: resolvedModuleNames,
104208                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
104209                 loader: resolveModuleName,
104210                 getResolutionWithResolvedFileName: getResolvedModule,
104211                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
104212                 reusedNames: reusedNames,
104213                 logChanges: logChangesWhenResolvingModule
104214             });
104215         }
104216         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
104217             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
104218             return cache && cache.get(moduleName);
104219         }
104220         function isNodeModulesAtTypesDirectory(dirPath) {
104221             return ts.endsWith(dirPath, "/node_modules/@types");
104222         }
104223         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
104224             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
104225                 // Ensure failed look up is normalized path
104226                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
104227                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
104228                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
104229                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
104230                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
104231                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
104232                     return {
104233                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
104234                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
104235                     };
104236                 }
104237                 else {
104238                     // Always watch root directory non recursively
104239                     return {
104240                         dir: rootDir,
104241                         dirPath: rootPath,
104242                         nonRecursive: false
104243                     };
104244                 }
104245             }
104246             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
104247         }
104248         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
104249             // If directory path contains node module, get the most parent node_modules directory for watching
104250             while (ts.pathContainsNodeModules(dirPath)) {
104251                 dir = ts.getDirectoryPath(dir);
104252                 dirPath = ts.getDirectoryPath(dirPath);
104253             }
104254             // If the directory is node_modules use it to watch, always watch it recursively
104255             if (ts.isNodeModulesDirectory(dirPath)) {
104256                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
104257             }
104258             var nonRecursive = true;
104259             // Use some ancestor of the root directory
104260             var subDirectoryPath, subDirectory;
104261             if (rootPath !== undefined) {
104262                 while (!isInDirectoryPath(dirPath, rootPath)) {
104263                     var parentPath = ts.getDirectoryPath(dirPath);
104264                     if (parentPath === dirPath) {
104265                         break;
104266                     }
104267                     nonRecursive = false;
104268                     subDirectoryPath = dirPath;
104269                     subDirectory = dir;
104270                     dirPath = parentPath;
104271                     dir = ts.getDirectoryPath(dir);
104272                 }
104273             }
104274             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
104275         }
104276         function isPathWithDefaultFailedLookupExtension(path) {
104277             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
104278         }
104279         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
104280             if (resolution.refCount) {
104281                 resolution.refCount++;
104282                 ts.Debug.assertDefined(resolution.files);
104283             }
104284             else {
104285                 resolution.refCount = 1;
104286                 ts.Debug.assert(resolution.files === undefined);
104287                 if (ts.isExternalModuleNameRelative(name)) {
104288                     watchFailedLookupLocationOfResolution(resolution);
104289                 }
104290                 else {
104291                     nonRelativeExternalModuleResolutions.add(name, resolution);
104292                 }
104293                 var resolved = getResolutionWithResolvedFileName(resolution);
104294                 if (resolved && resolved.resolvedFileName) {
104295                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104296                 }
104297             }
104298             (resolution.files || (resolution.files = [])).push(filePath);
104299         }
104300         function watchFailedLookupLocationOfResolution(resolution) {
104301             ts.Debug.assert(!!resolution.refCount);
104302             var failedLookupLocations = resolution.failedLookupLocations;
104303             if (!failedLookupLocations.length)
104304                 return;
104305             resolutionsWithFailedLookups.push(resolution);
104306             var setAtRoot = false;
104307             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
104308                 var failedLookupLocation = failedLookupLocations_1[_i];
104309                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104310                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104311                 if (toWatch) {
104312                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
104313                     // If the failed lookup location path is not one of the supported extensions,
104314                     // store it in the custom path
104315                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
104316                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
104317                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
104318                     }
104319                     if (dirPath === rootPath) {
104320                         ts.Debug.assert(!nonRecursive);
104321                         setAtRoot = true;
104322                     }
104323                     else {
104324                         setDirectoryWatcher(dir, dirPath, nonRecursive);
104325                     }
104326                 }
104327             }
104328             if (setAtRoot) {
104329                 // This is always non recursive
104330                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
104331             }
104332         }
104333         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
104334             var program = resolutionHost.getCurrentProgram();
104335             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
104336                 resolutions.forEach(watchFailedLookupLocationOfResolution);
104337             }
104338         }
104339         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
104340             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104341             if (dirWatcher) {
104342                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
104343                 dirWatcher.refCount++;
104344             }
104345             else {
104346                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
104347             }
104348         }
104349         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
104350             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
104351             resolution.refCount--;
104352             if (resolution.refCount) {
104353                 return;
104354             }
104355             var resolved = getResolutionWithResolvedFileName(resolution);
104356             if (resolved && resolved.resolvedFileName) {
104357                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104358             }
104359             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
104360                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
104361                 return;
104362             }
104363             var failedLookupLocations = resolution.failedLookupLocations;
104364             var removeAtRoot = false;
104365             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
104366                 var failedLookupLocation = failedLookupLocations_2[_i];
104367                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104368                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104369                 if (toWatch) {
104370                     var dirPath = toWatch.dirPath;
104371                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
104372                     if (refCount) {
104373                         if (refCount === 1) {
104374                             customFailedLookupPaths.delete(failedLookupLocationPath);
104375                         }
104376                         else {
104377                             ts.Debug.assert(refCount > 1);
104378                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
104379                         }
104380                     }
104381                     if (dirPath === rootPath) {
104382                         removeAtRoot = true;
104383                     }
104384                     else {
104385                         removeDirectoryWatcher(dirPath);
104386                     }
104387                 }
104388             }
104389             if (removeAtRoot) {
104390                 removeDirectoryWatcher(rootPath);
104391             }
104392         }
104393         function removeDirectoryWatcher(dirPath) {
104394             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104395             // Do not close the watcher yet since it might be needed by other failed lookup locations.
104396             dirWatcher.refCount--;
104397         }
104398         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
104399             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
104400                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104401                 if (cachedDirectoryStructureHost) {
104402                     // Since the file existence changed, update the sourceFiles cache
104403                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104404                 }
104405                 if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104406                     resolutionHost.onInvalidatedResolution();
104407                 }
104408             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
104409         }
104410         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
104411             // Deleted file, stop watching failed lookups for all the resolutions in the file
104412             var resolutions = cache.get(filePath);
104413             if (resolutions) {
104414                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
104415                 cache.delete(filePath);
104416             }
104417         }
104418         function removeResolutionsFromProjectReferenceRedirects(filePath) {
104419             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
104420                 return;
104421             }
104422             var program = resolutionHost.getCurrentProgram();
104423             if (!program) {
104424                 return;
104425             }
104426             // If this file is input file for the referenced project, get it
104427             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
104428             if (!resolvedProjectReference) {
104429                 return;
104430             }
104431             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
104432             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
104433         }
104434         function removeResolutionsOfFile(filePath) {
104435             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
104436             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
104437         }
104438         function invalidateResolution(resolution) {
104439             resolution.isInvalidated = true;
104440             var changedInAutoTypeReferenced = false;
104441             for (var _i = 0, _a = ts.Debug.assertDefined(resolution.files); _i < _a.length; _i++) {
104442                 var containingFilePath = _a[_i];
104443                 (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
104444                 // When its a file with inferred types resolution, invalidate type reference directive resolution
104445                 changedInAutoTypeReferenced = changedInAutoTypeReferenced || containingFilePath.endsWith(ts.inferredTypesContainingFile);
104446             }
104447             if (changedInAutoTypeReferenced) {
104448                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104449             }
104450         }
104451         function invalidateResolutionOfFile(filePath) {
104452             removeResolutionsOfFile(filePath);
104453             // Resolution is invalidated if the resulting file name is same as the deleted file path
104454             ts.forEach(resolvedFileToResolution.get(filePath), invalidateResolution);
104455         }
104456         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
104457             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
104458             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
104459         }
104460         function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
104461             var isChangedFailedLookupLocation;
104462             if (isCreatingWatchedDirectory) {
104463                 // Watching directory is created
104464                 // Invalidate any resolution has failed lookup in this directory
104465                 isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
104466             }
104467             else {
104468                 // If something to do with folder/file starting with "." in node_modules folder, skip it
104469                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
104470                 if (!updatedPath)
104471                     return false;
104472                 fileOrDirectoryPath = updatedPath;
104473                 // prevent saving an open file from over-eagerly triggering invalidation
104474                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
104475                     return false;
104476                 }
104477                 // Some file or directory in the watching directory is created
104478                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
104479                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
104480                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
104481                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
104482                     // Invalidate any resolution from this directory
104483                     isChangedFailedLookupLocation = function (location) {
104484                         var locationPath = resolutionHost.toPath(location);
104485                         return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
104486                     };
104487                 }
104488                 else {
104489                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
104490                         return false;
104491                     }
104492                     // Ignore emits from the program
104493                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
104494                         return false;
104495                     }
104496                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
104497                     isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
104498                 }
104499             }
104500             var invalidated = false;
104501             // Resolution is invalidated if the resulting file name is same as the deleted file path
104502             for (var _i = 0, resolutionsWithFailedLookups_1 = resolutionsWithFailedLookups; _i < resolutionsWithFailedLookups_1.length; _i++) {
104503                 var resolution = resolutionsWithFailedLookups_1[_i];
104504                 if (resolution.failedLookupLocations.some(isChangedFailedLookupLocation)) {
104505                     invalidateResolution(resolution);
104506                     invalidated = true;
104507                 }
104508             }
104509             return invalidated;
104510         }
104511         function closeTypeRootsWatch() {
104512             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
104513         }
104514         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
104515             if (isInDirectoryPath(rootPath, typeRootPath)) {
104516                 return rootPath;
104517             }
104518             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
104519             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
104520         }
104521         function createTypeRootsWatch(typeRootPath, typeRoot) {
104522             // Create new watch and recursive info
104523             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
104524                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104525                 if (cachedDirectoryStructureHost) {
104526                     // Since the file existence changed, update the sourceFiles cache
104527                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104528                 }
104529                 // For now just recompile
104530                 // We could potentially store more data here about whether it was/would be really be used or not
104531                 // and with that determine to trigger compilation but for now this is enough
104532                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104533                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
104534                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
104535                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
104536                 if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104537                     resolutionHost.onInvalidatedResolution();
104538                 }
104539             }, 1 /* Recursive */);
104540         }
104541         /**
104542          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
104543          * To be called when compiler options change
104544          */
104545         function updateTypeRootsWatch() {
104546             var options = resolutionHost.getCompilationSettings();
104547             if (options.types) {
104548                 // No need to do any watch since resolution cache is going to handle the failed lookups
104549                 // for the types added by this
104550                 closeTypeRootsWatch();
104551                 return;
104552             }
104553             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
104554             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
104555             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
104556             if (typeRoots) {
104557                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
104558                     createNewValue: createTypeRootsWatch,
104559                     onDeleteValue: ts.closeFileWatcher
104560                 });
104561             }
104562             else {
104563                 closeTypeRootsWatch();
104564             }
104565         }
104566         /**
104567          * Use this function to return if directory exists to get type roots to watch
104568          * If we return directory exists then only the paths will be added to type roots
104569          * Hence return true for all directories except root directories which are filtered from watching
104570          */
104571         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
104572             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
104573             var dirPath = resolutionHost.toPath(dir);
104574             return dirPath === rootPath || canWatchDirectory(dirPath);
104575         }
104576     }
104577     ts.createResolutionCache = createResolutionCache;
104578 })(ts || (ts = {}));
104579 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
104580 /* @internal */
104581 var ts;
104582 (function (ts) {
104583     var moduleSpecifiers;
104584     (function (moduleSpecifiers) {
104585         var RelativePreference;
104586         (function (RelativePreference) {
104587             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
104588             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
104589             RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
104590         })(RelativePreference || (RelativePreference = {}));
104591         // See UserPreferences#importPathEnding
104592         var Ending;
104593         (function (Ending) {
104594             Ending[Ending["Minimal"] = 0] = "Minimal";
104595             Ending[Ending["Index"] = 1] = "Index";
104596             Ending[Ending["JsExtension"] = 2] = "JsExtension";
104597         })(Ending || (Ending = {}));
104598         function getPreferences(_a, compilerOptions, importingSourceFile) {
104599             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
104600             return {
104601                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
104602                 ending: getEnding(),
104603             };
104604             function getEnding() {
104605                 switch (importModuleSpecifierEnding) {
104606                     case "minimal": return 0 /* Minimal */;
104607                     case "index": return 1 /* Index */;
104608                     case "js": return 2 /* JsExtension */;
104609                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
104610                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
104611                 }
104612             }
104613         }
104614         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
104615             return {
104616                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
104617                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
104618                     2 /* JsExtension */ :
104619                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
104620             };
104621         }
104622         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
104623             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
104624             if (res === oldImportSpecifier)
104625                 return undefined;
104626             return res;
104627         }
104628         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
104629         // Note: importingSourceFile is just for usesJsExtensionOnImports
104630         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
104631             if (preferences === void 0) { preferences = {}; }
104632             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
104633         }
104634         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
104635         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
104636             var info = getInfo(importingSourceFileName, host);
104637             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
104638             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); });
104639         }
104640         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
104641         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
104642             var info = getInfo(importingSourceFileName, host);
104643             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
104644             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
104645                 getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
104646         }
104647         /** Returns an import for each symlink and for the realpath. */
104648         function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
104649             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
104650             if (ambient)
104651                 return [ambient];
104652             var info = getInfo(importingSourceFile.path, host);
104653             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
104654             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
104655             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
104656             var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
104657             return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
104658         }
104659         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
104660         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
104661         function getInfo(importingSourceFileName, host) {
104662             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
104663             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
104664             return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
104665         }
104666         function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
104667             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104668             var ending = _b.ending, relativePreference = _b.relativePreference;
104669             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
104670             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
104671                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
104672             if (!baseUrl || relativePreference === 0 /* Relative */) {
104673                 return relativePath;
104674             }
104675             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
104676             if (!relativeToBaseUrl) {
104677                 return relativePath;
104678             }
104679             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
104680             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
104681             var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
104682             if (relativePreference === 1 /* NonRelative */) {
104683                 return nonRelative;
104684             }
104685             if (relativePreference !== 2 /* Auto */)
104686                 ts.Debug.assertNever(relativePreference);
104687             // Prefer a relative import over a baseUrl import if it has fewer components.
104688             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
104689         }
104690         function countPathComponents(path) {
104691             var count = 0;
104692             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
104693                 if (path.charCodeAt(i) === 47 /* slash */)
104694                     count++;
104695             }
104696             return count;
104697         }
104698         moduleSpecifiers.countPathComponents = countPathComponents;
104699         function usesJsExtensionOnImports(_a) {
104700             var imports = _a.imports;
104701             return ts.firstDefined(imports, function (_a) {
104702                 var text = _a.text;
104703                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
104704             }) || false;
104705         }
104706         function numberOfDirectorySeparators(str) {
104707             var match = str.match(/\//g);
104708             return match ? match.length : 0;
104709         }
104710         function comparePathsByNumberOfDirectorySeparators(a, b) {
104711             return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b));
104712         }
104713         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
104714             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104715             var cwd = host.getCurrentDirectory();
104716             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
104717             var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
104718             var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
104719             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
104720             if (!preferSymlinks) {
104721                 var result_12 = ts.forEach(targets, cb);
104722                 if (result_12)
104723                     return result_12;
104724             }
104725             var links = host.getProbableSymlinks
104726                 ? host.getProbableSymlinks(host.getSourceFiles())
104727                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
104728             var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
104729             var result = ts.forEachEntry(links, function (resolved, path) {
104730                 if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
104731                     return undefined; // Don't want to a package to globally import from itself
104732                 }
104733                 var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
104734                 if (target === undefined)
104735                     return undefined;
104736                 var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
104737                 var option = ts.resolvePath(path, relative);
104738                 if (!host.fileExists || host.fileExists(option)) {
104739                     var result_13 = cb(option);
104740                     if (result_13)
104741                         return result_13;
104742                 }
104743             });
104744             return result ||
104745                 (preferSymlinks ? ts.forEach(targets, cb) : undefined);
104746         }
104747         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
104748         /**
104749          * Looks for existing imports that use symlinks to this module.
104750          * Symlinks will be returned first so they are preferred over the real path.
104751          */
104752         function getAllModulePaths(importingFileName, importedFileName, host) {
104753             var cwd = host.getCurrentDirectory();
104754             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104755             var allFileNames = ts.createMap();
104756             var importedFileFromNodeModules = false;
104757             forEachFileNameOfModule(importingFileName, importedFileName, host, 
104758             /*preferSymlinks*/ true, function (path) {
104759                 // dont return value, so we collect everything
104760                 allFileNames.set(path, getCanonicalFileName(path));
104761                 importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path);
104762             });
104763             // Sort by paths closest to importing file Name directory
104764             var sortedPaths = [];
104765             var _loop_20 = function (directory) {
104766                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
104767                 var pathsInDirectory;
104768                 allFileNames.forEach(function (canonicalFileName, fileName) {
104769                     if (ts.startsWith(canonicalFileName, directoryStart)) {
104770                         // If the importedFile is from node modules, use only paths in node_modules folder as option
104771                         if (!importedFileFromNodeModules || ts.pathContainsNodeModules(fileName)) {
104772                             (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
104773                         }
104774                         allFileNames.delete(fileName);
104775                     }
104776                 });
104777                 if (pathsInDirectory) {
104778                     if (pathsInDirectory.length > 1) {
104779                         pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
104780                     }
104781                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
104782                 }
104783                 var newDirectory = ts.getDirectoryPath(directory);
104784                 if (newDirectory === directory)
104785                     return out_directory_1 = directory, "break";
104786                 directory = newDirectory;
104787                 out_directory_1 = directory;
104788             };
104789             var out_directory_1;
104790             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
104791                 var state_8 = _loop_20(directory);
104792                 directory = out_directory_1;
104793                 if (state_8 === "break")
104794                     break;
104795             }
104796             if (allFileNames.size) {
104797                 var remainingPaths = ts.arrayFrom(allFileNames.values());
104798                 if (remainingPaths.length > 1)
104799                     remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
104800                 sortedPaths.push.apply(sortedPaths, remainingPaths);
104801             }
104802             return sortedPaths;
104803         }
104804         function tryGetModuleNameFromAmbientModule(moduleSymbol) {
104805             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
104806             if (decl) {
104807                 return decl.name.text;
104808             }
104809         }
104810         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
104811             for (var key in paths) {
104812                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
104813                     var patternText_1 = _a[_i];
104814                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
104815                     var indexOfStar = pattern.indexOf("*");
104816                     if (indexOfStar !== -1) {
104817                         var prefix = pattern.substr(0, indexOfStar);
104818                         var suffix = pattern.substr(indexOfStar + 1);
104819                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
104820                             ts.startsWith(relativeToBaseUrl, prefix) &&
104821                             ts.endsWith(relativeToBaseUrl, suffix) ||
104822                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
104823                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
104824                             return key.replace("*", matchedStar);
104825                         }
104826                     }
104827                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
104828                         return key;
104829                     }
104830                 }
104831             }
104832         }
104833         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
104834             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
104835             if (normalizedTargetPath === undefined) {
104836                 return undefined;
104837             }
104838             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
104839             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
104840             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
104841                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
104842                 : ts.removeFileExtension(relativePath);
104843         }
104844         function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options, packageNameOnly) {
104845             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104846             if (!host.fileExists || !host.readFile) {
104847                 return undefined;
104848             }
104849             var parts = getNodeModulePathParts(moduleFileName);
104850             if (!parts) {
104851                 return undefined;
104852             }
104853             // Simplify the full file path to something that can be resolved by Node.
104854             var moduleSpecifier = moduleFileName;
104855             if (!packageNameOnly) {
104856                 var packageRootIndex = parts.packageRootIndex;
104857                 var moduleFileNameForExtensionless = void 0;
104858                 while (true) {
104859                     // If the module could be imported by a directory name, use that directory's name
104860                     var _b = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _b.moduleFileToTry, packageRootPath = _b.packageRootPath;
104861                     if (packageRootPath) {
104862                         moduleSpecifier = packageRootPath;
104863                         break;
104864                     }
104865                     if (!moduleFileNameForExtensionless)
104866                         moduleFileNameForExtensionless = moduleFileToTry;
104867                     // try with next level of directory
104868                     packageRootIndex = moduleFileName.indexOf(ts.directorySeparator, packageRootIndex + 1);
104869                     if (packageRootIndex === -1) {
104870                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
104871                         break;
104872                     }
104873                 }
104874             }
104875             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
104876             // Get a path that's relative to node_modules or the importing file's path
104877             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
104878             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
104879             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
104880                 return undefined;
104881             }
104882             // If the module was found in @types, get the actual Node package name
104883             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
104884             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
104885             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
104886             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
104887             function tryDirectoryWithPackageJson(packageRootIndex) {
104888                 var packageRootPath = moduleFileName.substring(0, packageRootIndex);
104889                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
104890                 var moduleFileToTry = moduleFileName;
104891                 if (host.fileExists(packageJsonPath)) {
104892                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
104893                     var versionPaths = packageJsonContent.typesVersions
104894                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
104895                         : undefined;
104896                     if (versionPaths) {
104897                         var subModuleName = moduleFileName.slice(packageRootPath.length + 1);
104898                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
104899                         if (fromPaths !== undefined) {
104900                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
104901                         }
104902                     }
104903                     // If the file is the main module, it can be imported by the package name
104904                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
104905                     if (ts.isString(mainFileRelative)) {
104906                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
104907                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
104908                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
104909                         }
104910                     }
104911                 }
104912                 return { moduleFileToTry: moduleFileToTry };
104913             }
104914             function getExtensionlessFileName(path) {
104915                 // We still have a file name - remove the extension
104916                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
104917                 // If the file is /index, it can be imported by its directory name
104918                 // IFF there is not _also_ a file by the same name
104919                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
104920                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
104921                 }
104922                 return fullModulePathWithoutExtension;
104923             }
104924         }
104925         function tryGetAnyFileFromPath(host, path) {
104926             if (!host.fileExists)
104927                 return;
104928             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
104929             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
104930             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
104931                 var e = extensions_3[_i];
104932                 var fullPath = path + e;
104933                 if (host.fileExists(fullPath)) {
104934                     return fullPath;
104935                 }
104936             }
104937         }
104938         function getNodeModulePathParts(fullPath) {
104939             // If fullPath can't be valid module file within node_modules, returns undefined.
104940             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
104941             // Returns indices:                       ^            ^                                                      ^             ^
104942             var topLevelNodeModulesIndex = 0;
104943             var topLevelPackageNameIndex = 0;
104944             var packageRootIndex = 0;
104945             var fileNameIndex = 0;
104946             var States;
104947             (function (States) {
104948                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
104949                 States[States["NodeModules"] = 1] = "NodeModules";
104950                 States[States["Scope"] = 2] = "Scope";
104951                 States[States["PackageContent"] = 3] = "PackageContent";
104952             })(States || (States = {}));
104953             var partStart = 0;
104954             var partEnd = 0;
104955             var state = 0 /* BeforeNodeModules */;
104956             while (partEnd >= 0) {
104957                 partStart = partEnd;
104958                 partEnd = fullPath.indexOf("/", partStart + 1);
104959                 switch (state) {
104960                     case 0 /* BeforeNodeModules */:
104961                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104962                             topLevelNodeModulesIndex = partStart;
104963                             topLevelPackageNameIndex = partEnd;
104964                             state = 1 /* NodeModules */;
104965                         }
104966                         break;
104967                     case 1 /* NodeModules */:
104968                     case 2 /* Scope */:
104969                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
104970                             state = 2 /* Scope */;
104971                         }
104972                         else {
104973                             packageRootIndex = partEnd;
104974                             state = 3 /* PackageContent */;
104975                         }
104976                         break;
104977                     case 3 /* PackageContent */:
104978                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104979                             state = 1 /* NodeModules */;
104980                         }
104981                         else {
104982                             state = 3 /* PackageContent */;
104983                         }
104984                         break;
104985                 }
104986             }
104987             fileNameIndex = partStart;
104988             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
104989         }
104990         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
104991             return ts.firstDefined(rootDirs, function (rootDir) {
104992                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
104993                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
104994             });
104995         }
104996         function removeExtensionAndIndexPostFix(fileName, ending, options) {
104997             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
104998                 return fileName;
104999             var noExtension = ts.removeFileExtension(fileName);
105000             switch (ending) {
105001                 case 0 /* Minimal */:
105002                     return ts.removeSuffix(noExtension, "/index");
105003                 case 1 /* Index */:
105004                     return noExtension;
105005                 case 2 /* JsExtension */:
105006                     return noExtension + getJSExtensionForFile(fileName, options);
105007                 default:
105008                     return ts.Debug.assertNever(ending);
105009             }
105010         }
105011         function getJSExtensionForFile(fileName, options) {
105012             var ext = ts.extensionFromPath(fileName);
105013             switch (ext) {
105014                 case ".ts" /* Ts */:
105015                 case ".d.ts" /* Dts */:
105016                     return ".js" /* Js */;
105017                 case ".tsx" /* Tsx */:
105018                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
105019                 case ".js" /* Js */:
105020                 case ".jsx" /* Jsx */:
105021                 case ".json" /* Json */:
105022                     return ext;
105023                 case ".tsbuildinfo" /* TsBuildInfo */:
105024                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
105025                 default:
105026                     return ts.Debug.assertNever(ext);
105027             }
105028         }
105029         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
105030             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
105031             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
105032         }
105033         function isPathRelativeToParent(path) {
105034             return ts.startsWith(path, "..");
105035         }
105036     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
105037 })(ts || (ts = {}));
105038 /*@internal*/
105039 var ts;
105040 (function (ts) {
105041     var sysFormatDiagnosticsHost = ts.sys ? {
105042         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
105043         getNewLine: function () { return ts.sys.newLine; },
105044         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
105045     } : undefined; // TODO: GH#18217
105046     /**
105047      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
105048      */
105049     function createDiagnosticReporter(system, pretty) {
105050         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
105051             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
105052             getNewLine: function () { return system.newLine; },
105053             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
105054         };
105055         if (!pretty) {
105056             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
105057         }
105058         var diagnostics = new Array(1);
105059         return function (diagnostic) {
105060             diagnostics[0] = diagnostic;
105061             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
105062             diagnostics[0] = undefined; // TODO: GH#18217
105063         };
105064     }
105065     ts.createDiagnosticReporter = createDiagnosticReporter;
105066     /**
105067      * @returns Whether the screen was cleared.
105068      */
105069     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
105070         if (system.clearScreen &&
105071             !options.preserveWatchOutput &&
105072             !options.extendedDiagnostics &&
105073             !options.diagnostics &&
105074             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
105075             system.clearScreen();
105076             return true;
105077         }
105078         return false;
105079     }
105080     ts.screenStartingMessageCodes = [
105081         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
105082         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
105083     ];
105084     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
105085         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
105086             ? newLine + newLine
105087             : newLine;
105088     }
105089     /**
105090      * Get locale specific time based on whether we are in test mode
105091      */
105092     function getLocaleTimeString(system) {
105093         return !system.now ?
105094             new Date().toLocaleTimeString() :
105095             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
105096     }
105097     ts.getLocaleTimeString = getLocaleTimeString;
105098     /**
105099      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105100      */
105101     function createWatchStatusReporter(system, pretty) {
105102         return pretty ?
105103             function (diagnostic, newLine, options) {
105104                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
105105                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
105106                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
105107                 system.write(output);
105108             } :
105109             function (diagnostic, newLine, options) {
105110                 var output = "";
105111                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
105112                     output += newLine;
105113                 }
105114                 output += getLocaleTimeString(system) + " - ";
105115                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
105116                 system.write(output);
105117             };
105118     }
105119     ts.createWatchStatusReporter = createWatchStatusReporter;
105120     /** Parses config file using System interface */
105121     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
105122         var host = system;
105123         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
105124         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
105125         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
105126         return result;
105127     }
105128     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
105129     function getErrorCountForSummary(diagnostics) {
105130         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
105131     }
105132     ts.getErrorCountForSummary = getErrorCountForSummary;
105133     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
105134         return errorCount === 1 ?
105135             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
105136             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
105137     }
105138     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
105139     function getErrorSummaryText(errorCount, newLine) {
105140         if (errorCount === 0)
105141             return "";
105142         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
105143         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
105144     }
105145     ts.getErrorSummaryText = getErrorSummaryText;
105146     function listFiles(program, writeFileName) {
105147         if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
105148             ts.forEach(program.getSourceFiles(), function (file) {
105149                 writeFileName(file.fileName);
105150             });
105151         }
105152     }
105153     ts.listFiles = listFiles;
105154     /**
105155      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
105156      */
105157     function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105158         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
105159         // First get and report any syntactic errors.
105160         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
105161         var configFileParsingDiagnosticsLength = allDiagnostics.length;
105162         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105163         // If we didn't have any syntactic errors, then also try getting the global and
105164         // semantic errors.
105165         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105166             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
105167             if (!isListFilesOnly) {
105168                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
105169                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105170                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105171                 }
105172             }
105173         }
105174         // Emit and report any errors we ran into.
105175         var emitResult = isListFilesOnly
105176             ? { emitSkipped: true, diagnostics: ts.emptyArray }
105177             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
105178         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
105179         ts.addRange(allDiagnostics, emitDiagnostics);
105180         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
105181         diagnostics.forEach(reportDiagnostic);
105182         if (writeFileName) {
105183             var currentDir_1 = program.getCurrentDirectory();
105184             ts.forEach(emittedFiles, function (file) {
105185                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
105186                 writeFileName("TSFILE: " + filepath);
105187             });
105188             listFiles(program, writeFileName);
105189         }
105190         if (reportSummary) {
105191             reportSummary(getErrorCountForSummary(diagnostics));
105192         }
105193         return {
105194             emitResult: emitResult,
105195             diagnostics: diagnostics,
105196         };
105197     }
105198     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
105199     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105200         var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
105201         if (emitResult.emitSkipped && diagnostics.length > 0) {
105202             // If the emitter didn't emit anything, then pass that value along.
105203             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
105204         }
105205         else if (diagnostics.length > 0) {
105206             // The emitter emitted something, inform the caller if that happened in the presence
105207             // of diagnostics or not.
105208             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
105209         }
105210         return ts.ExitStatus.Success;
105211     }
105212     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
105213     ts.noopFileWatcher = { close: ts.noop };
105214     function createWatchHost(system, reportWatchStatus) {
105215         if (system === void 0) { system = ts.sys; }
105216         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
105217         return {
105218             onWatchStatusChange: onWatchStatusChange,
105219             watchFile: ts.maybeBind(system, system.watchFile) || (function () { return ts.noopFileWatcher; }),
105220             watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return ts.noopFileWatcher; }),
105221             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
105222             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
105223         };
105224     }
105225     ts.createWatchHost = createWatchHost;
105226     ts.WatchType = {
105227         ConfigFile: "Config file",
105228         SourceFile: "Source file",
105229         MissingFile: "Missing file",
105230         WildcardDirectory: "Wild card directory",
105231         FailedLookupLocations: "Failed Lookup Locations",
105232         TypeRoots: "Type roots"
105233     };
105234     function createWatchFactory(host, options) {
105235         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
105236         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
105237         var result = ts.getWatchFactory(watchLogLevel, writeLog);
105238         result.writeLog = writeLog;
105239         return result;
105240     }
105241     ts.createWatchFactory = createWatchFactory;
105242     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
105243         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
105244         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105245         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
105246         return {
105247             getSourceFile: function (fileName, languageVersion, onError) {
105248                 var text;
105249                 try {
105250                     ts.performance.mark("beforeIORead");
105251                     text = host.readFile(fileName, getCompilerOptions().charset);
105252                     ts.performance.mark("afterIORead");
105253                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
105254                 }
105255                 catch (e) {
105256                     if (onError) {
105257                         onError(e.message);
105258                     }
105259                     text = "";
105260                 }
105261                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
105262             },
105263             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
105264             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
105265             writeFile: writeFile,
105266             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
105267             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
105268             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
105269             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
105270             fileExists: function (f) { return host.fileExists(f); },
105271             readFile: function (f) { return host.readFile(f); },
105272             trace: ts.maybeBind(host, host.trace),
105273             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
105274             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
105275             realpath: ts.maybeBind(host, host.realpath),
105276             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
105277             createHash: ts.maybeBind(host, host.createHash),
105278             readDirectory: ts.maybeBind(host, host.readDirectory),
105279         };
105280         function writeFile(fileName, text, writeByteOrderMark, onError) {
105281             try {
105282                 ts.performance.mark("beforeIOWrite");
105283                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
105284                 // the host.writeFile will do its own directory creation and
105285                 // the ensureDirectoriesExist call will always be redundant.
105286                 ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); });
105287                 ts.performance.mark("afterIOWrite");
105288                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
105289             }
105290             catch (e) {
105291                 if (onError) {
105292                     onError(e.message);
105293                 }
105294             }
105295         }
105296     }
105297     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
105298     function setGetSourceFileAsHashVersioned(compilerHost, host) {
105299         var originalGetSourceFile = compilerHost.getSourceFile;
105300         var computeHash = host.createHash || ts.generateDjb2Hash;
105301         compilerHost.getSourceFile = function () {
105302             var args = [];
105303             for (var _i = 0; _i < arguments.length; _i++) {
105304                 args[_i] = arguments[_i];
105305             }
105306             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
105307             if (result) {
105308                 result.version = computeHash.call(host, result.text);
105309             }
105310             return result;
105311         };
105312     }
105313     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
105314     /**
105315      * Creates the watch compiler host that can be extended with config file or root file names and options host
105316      */
105317     function createProgramHost(system, createProgram) {
105318         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
105319         return {
105320             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
105321             getNewLine: function () { return system.newLine; },
105322             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
105323             getDefaultLibLocation: getDefaultLibLocation,
105324             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
105325             fileExists: function (path) { return system.fileExists(path); },
105326             readFile: function (path, encoding) { return system.readFile(path, encoding); },
105327             directoryExists: function (path) { return system.directoryExists(path); },
105328             getDirectories: function (path) { return system.getDirectories(path); },
105329             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
105330             realpath: ts.maybeBind(system, system.realpath),
105331             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
105332             trace: function (s) { return system.write(s + system.newLine); },
105333             createDirectory: function (path) { return system.createDirectory(path); },
105334             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
105335             createHash: ts.maybeBind(system, system.createHash),
105336             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
105337         };
105338     }
105339     ts.createProgramHost = createProgramHost;
105340     /**
105341      * Creates the watch compiler host that can be extended with config file or root file names and options host
105342      */
105343     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
105344         if (system === void 0) { system = ts.sys; }
105345         var writeFileName = function (s) { return system.write(s + system.newLine); };
105346         var result = createProgramHost(system, createProgram);
105347         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
105348         result.afterProgramCreate = function (builderProgram) {
105349             var compilerOptions = builderProgram.getCompilerOptions();
105350             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
105351             emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
105352         };
105353         return result;
105354     }
105355     /**
105356      * Report error and exit
105357      */
105358     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
105359         reportDiagnostic(diagnostic);
105360         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
105361     }
105362     /**
105363      * Creates the watch compiler host from system for config file in watch mode
105364      */
105365     function createWatchCompilerHostOfConfigFile(_a) {
105366         var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus;
105367         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
105368         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
105369         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
105370         host.configFileName = configFileName;
105371         host.optionsToExtend = optionsToExtend;
105372         host.watchOptionsToExtend = watchOptionsToExtend;
105373         host.extraFileExtensions = extraFileExtensions;
105374         return host;
105375     }
105376     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
105377     /**
105378      * Creates the watch compiler host from system for compiling root files and options in watch mode
105379      */
105380     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
105381         var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus;
105382         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
105383         host.rootFiles = rootFiles;
105384         host.options = options;
105385         host.watchOptions = watchOptions;
105386         host.projectReferences = projectReferences;
105387         return host;
105388     }
105389     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
105390     function performIncrementalCompilation(input) {
105391         var system = input.system || ts.sys;
105392         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
105393         var builderProgram = ts.createIncrementalProgram(input);
105394         var exitStatus = emitFilesAndReportErrorsAndGetExitStatus(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
105395         if (input.afterProgramEmitAndDiagnostics)
105396             input.afterProgramEmitAndDiagnostics(builderProgram);
105397         return exitStatus;
105398     }
105399     ts.performIncrementalCompilation = performIncrementalCompilation;
105400 })(ts || (ts = {}));
105401 var ts;
105402 (function (ts) {
105403     function readBuilderProgram(compilerOptions, host) {
105404         if (compilerOptions.out || compilerOptions.outFile)
105405             return undefined;
105406         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
105407         if (!buildInfoPath)
105408             return undefined;
105409         var content = host.readFile(buildInfoPath);
105410         if (!content)
105411             return undefined;
105412         var buildInfo = ts.getBuildInfo(content);
105413         if (buildInfo.version !== ts.version)
105414             return undefined;
105415         if (!buildInfo.program)
105416             return undefined;
105417         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
105418     }
105419     ts.readBuilderProgram = readBuilderProgram;
105420     function createIncrementalCompilerHost(options, system) {
105421         if (system === void 0) { system = ts.sys; }
105422         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
105423         host.createHash = ts.maybeBind(system, system.createHash);
105424         ts.setGetSourceFileAsHashVersioned(host, system);
105425         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
105426         return host;
105427     }
105428     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
105429     function createIncrementalProgram(_a) {
105430         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
105431         host = host || createIncrementalCompilerHost(options);
105432         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
105433         var oldProgram = readBuilderProgram(options, host);
105434         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
105435     }
105436     ts.createIncrementalProgram = createIncrementalProgram;
105437     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
105438         if (ts.isArray(rootFilesOrConfigFileName)) {
105439             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
105440                 rootFiles: rootFilesOrConfigFileName,
105441                 options: options,
105442                 watchOptions: watchOptionsOrExtraFileExtensions,
105443                 projectReferences: projectReferencesOrWatchOptionsToExtend,
105444                 system: system,
105445                 createProgram: createProgram,
105446                 reportDiagnostic: reportDiagnostic,
105447                 reportWatchStatus: reportWatchStatus,
105448             });
105449         }
105450         else {
105451             return ts.createWatchCompilerHostOfConfigFile({
105452                 configFileName: rootFilesOrConfigFileName,
105453                 optionsToExtend: options,
105454                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
105455                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
105456                 system: system,
105457                 createProgram: createProgram,
105458                 reportDiagnostic: reportDiagnostic,
105459                 reportWatchStatus: reportWatchStatus,
105460             });
105461         }
105462     }
105463     ts.createWatchCompilerHost = createWatchCompilerHost;
105464     function createWatchProgram(host) {
105465         var builderProgram;
105466         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
105467         var missingFilesMap; // Map of file watchers for the missing files
105468         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
105469         var timerToUpdateProgram; // timer callback to recompile the program
105470         var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
105471         var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files
105472         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
105473         var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
105474         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105475         var currentDirectory = host.getCurrentDirectory();
105476         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
105477         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
105478         var configFileSpecs;
105479         var configFileParsingDiagnostics;
105480         var canConfigFileJsonReportNoInputFiles = false;
105481         var hasChangedConfigFileParsingErrors = false;
105482         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
105483         var directoryStructureHost = cachedDirectoryStructureHost || host;
105484         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
105485         // From tsc we want to get already parsed result and hence check for rootFileNames
105486         var newLine = updateNewLine();
105487         if (configFileName && host.configFileParsingResult) {
105488             setConfigFileParsingResult(host.configFileParsingResult);
105489             newLine = updateNewLine();
105490         }
105491         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
105492         if (configFileName && !host.configFileParsingResult) {
105493             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105494             ts.Debug.assert(!rootFileNames);
105495             parseConfigFile();
105496             newLine = updateNewLine();
105497         }
105498         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
105499         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
105500         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
105501         var configFileWatcher;
105502         if (configFileName) {
105503             configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
105504         }
105505         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
105506         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
105507         // Members for CompilerHost
105508         var getNewSourceFile = compilerHost.getSourceFile;
105509         compilerHost.getSourceFile = function (fileName) {
105510             var args = [];
105511             for (var _i = 1; _i < arguments.length; _i++) {
105512                 args[_i - 1] = arguments[_i];
105513             }
105514             return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
105515         };
105516         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
105517         compilerHost.getNewLine = function () { return newLine; };
105518         compilerHost.fileExists = fileExists;
105519         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
105520         // Members for ResolutionCacheHost
105521         compilerHost.toPath = toPath;
105522         compilerHost.getCompilationSettings = function () { return compilerOptions; };
105523         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
105524         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
105525         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
105526         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
105527         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
105528         compilerHost.onChangedAutomaticTypeDirectiveNames = function () {
105529             hasChangedAutomaticTypeDirectiveNames = true;
105530             scheduleProgramUpdate();
105531         };
105532         compilerHost.fileIsOpen = ts.returnFalse;
105533         compilerHost.getCurrentProgram = getCurrentProgram;
105534         compilerHost.writeLog = writeLog;
105535         // Cache for the module resolution
105536         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
105537             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
105538             currentDirectory, 
105539         /*logChangesWhenResolvingModule*/ false);
105540         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
105541         compilerHost.resolveModuleNames = host.resolveModuleNames ?
105542             (function () {
105543                 var args = [];
105544                 for (var _i = 0; _i < arguments.length; _i++) {
105545                     args[_i] = arguments[_i];
105546                 }
105547                 return host.resolveModuleNames.apply(host, args);
105548             }) :
105549             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
105550         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
105551             (function () {
105552                 var args = [];
105553                 for (var _i = 0; _i < arguments.length; _i++) {
105554                     args[_i] = arguments[_i];
105555                 }
105556                 return host.resolveTypeReferenceDirectives.apply(host, args);
105557             }) :
105558             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
105559         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
105560         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
105561         synchronizeProgram();
105562         // Update the wild card directory watch
105563         watchConfigFileWildCardDirectories();
105564         return configFileName ?
105565             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
105566             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
105567         function close() {
105568             resolutionCache.clear();
105569             ts.clearMap(sourceFilesCache, function (value) {
105570                 if (value && value.fileWatcher) {
105571                     value.fileWatcher.close();
105572                     value.fileWatcher = undefined;
105573                 }
105574             });
105575             if (configFileWatcher) {
105576                 configFileWatcher.close();
105577                 configFileWatcher = undefined;
105578             }
105579             if (watchedWildcardDirectories) {
105580                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105581                 watchedWildcardDirectories = undefined;
105582             }
105583             if (missingFilesMap) {
105584                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
105585                 missingFilesMap = undefined;
105586             }
105587         }
105588         function getCurrentBuilderProgram() {
105589             return builderProgram;
105590         }
105591         function getCurrentProgram() {
105592             return builderProgram && builderProgram.getProgramOrUndefined();
105593         }
105594         function synchronizeProgram() {
105595             writeLog("Synchronizing program");
105596             var program = getCurrentBuilderProgram();
105597             if (hasChangedCompilerOptions) {
105598                 newLine = updateNewLine();
105599                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
105600                     resolutionCache.clear();
105601                 }
105602             }
105603             // All resolutions are invalid if user provided resolutions
105604             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
105605             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
105606                 if (hasChangedConfigFileParsingErrors) {
105607                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105608                     hasChangedConfigFileParsingErrors = false;
105609                 }
105610             }
105611             else {
105612                 createNewProgram(hasInvalidatedResolution);
105613             }
105614             if (host.afterProgramCreate && program !== builderProgram) {
105615                 host.afterProgramCreate(builderProgram);
105616             }
105617             return builderProgram;
105618         }
105619         function createNewProgram(hasInvalidatedResolution) {
105620             // Compile the program
105621             writeLog("CreatingProgramWith::");
105622             writeLog("  roots: " + JSON.stringify(rootFileNames));
105623             writeLog("  options: " + JSON.stringify(compilerOptions));
105624             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
105625             hasChangedCompilerOptions = false;
105626             hasChangedConfigFileParsingErrors = false;
105627             resolutionCache.startCachingPerDirectoryResolution();
105628             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
105629             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
105630             hasChangedAutomaticTypeDirectiveNames = false;
105631             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105632             resolutionCache.finishCachingPerDirectoryResolution();
105633             // Update watches
105634             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
105635             if (needsUpdateInTypeRootWatch) {
105636                 resolutionCache.updateTypeRootsWatch();
105637             }
105638             if (missingFilePathsRequestedForRelease) {
105639                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
105640                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
105641                 // if there is already watcher for it (for missing files)
105642                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
105643                 // so that at later time we have correct result of their presence
105644                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
105645                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
105646                     if (!missingFilesMap.has(missingFilePath)) {
105647                         sourceFilesCache.delete(missingFilePath);
105648                     }
105649                 }
105650                 missingFilePathsRequestedForRelease = undefined;
105651             }
105652         }
105653         function updateRootFileNames(files) {
105654             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
105655             rootFileNames = files;
105656             scheduleProgramUpdate();
105657         }
105658         function updateNewLine() {
105659             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105660         }
105661         function toPath(fileName) {
105662             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105663         }
105664         function isFileMissingOnHost(hostSourceFile) {
105665             return typeof hostSourceFile === "boolean";
105666         }
105667         function isFilePresenceUnknownOnHost(hostSourceFile) {
105668             return typeof hostSourceFile.version === "boolean";
105669         }
105670         function fileExists(fileName) {
105671             var path = toPath(fileName);
105672             // If file is missing on host from cache, we can definitely say file doesnt exist
105673             // otherwise we need to ensure from the disk
105674             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
105675                 return false;
105676             }
105677             return directoryStructureHost.fileExists(fileName);
105678         }
105679         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
105680             var hostSourceFile = sourceFilesCache.get(path);
105681             // No source file on the host
105682             if (isFileMissingOnHost(hostSourceFile)) {
105683                 return undefined;
105684             }
105685             // Create new source file if requested or the versions dont match
105686             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
105687                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
105688                 if (hostSourceFile) {
105689                     if (sourceFile) {
105690                         // Set the source file and create file watcher now that file was present on the disk
105691                         hostSourceFile.sourceFile = sourceFile;
105692                         hostSourceFile.version = sourceFile.version;
105693                         if (!hostSourceFile.fileWatcher) {
105694                             hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105695                         }
105696                     }
105697                     else {
105698                         // There is no source file on host any more, close the watch, missing file paths will track it
105699                         if (hostSourceFile.fileWatcher) {
105700                             hostSourceFile.fileWatcher.close();
105701                         }
105702                         sourceFilesCache.set(path, false);
105703                     }
105704                 }
105705                 else {
105706                     if (sourceFile) {
105707                         var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105708                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
105709                     }
105710                     else {
105711                         sourceFilesCache.set(path, false);
105712                     }
105713                 }
105714                 return sourceFile;
105715             }
105716             return hostSourceFile.sourceFile;
105717         }
105718         function nextSourceFileVersion(path) {
105719             var hostSourceFile = sourceFilesCache.get(path);
105720             if (hostSourceFile !== undefined) {
105721                 if (isFileMissingOnHost(hostSourceFile)) {
105722                     // The next version, lets set it as presence unknown file
105723                     sourceFilesCache.set(path, { version: false });
105724                 }
105725                 else {
105726                     hostSourceFile.version = false;
105727                 }
105728             }
105729         }
105730         function getSourceVersion(path) {
105731             var hostSourceFile = sourceFilesCache.get(path);
105732             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
105733         }
105734         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
105735             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
105736             // If this is the source file thats in the cache and new program doesnt need it,
105737             // remove the cached entry.
105738             // Note we arent deleting entry if file became missing in new program or
105739             // there was version update and new source file was created.
105740             if (hostSourceFileInfo !== undefined) {
105741                 // record the missing file paths so they can be removed later if watchers arent tracking them
105742                 if (isFileMissingOnHost(hostSourceFileInfo)) {
105743                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
105744                 }
105745                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
105746                     if (hostSourceFileInfo.fileWatcher) {
105747                         hostSourceFileInfo.fileWatcher.close();
105748                     }
105749                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
105750                     if (!hasSourceFileByPath) {
105751                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
105752                     }
105753                 }
105754             }
105755         }
105756         function reportWatchDiagnostic(message) {
105757             if (host.onWatchStatusChange) {
105758                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
105759             }
105760         }
105761         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
105762         // operations (such as saving all modified files in an editor) a chance to complete before we kick
105763         // off a new compilation.
105764         function scheduleProgramUpdate() {
105765             if (!host.setTimeout || !host.clearTimeout) {
105766                 return;
105767             }
105768             if (timerToUpdateProgram) {
105769                 host.clearTimeout(timerToUpdateProgram);
105770             }
105771             writeLog("Scheduling update");
105772             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
105773         }
105774         function scheduleProgramReload() {
105775             ts.Debug.assert(!!configFileName);
105776             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
105777             scheduleProgramUpdate();
105778         }
105779         function updateProgramWithWatchStatus() {
105780             timerToUpdateProgram = undefined;
105781             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
105782             updateProgram();
105783         }
105784         function updateProgram() {
105785             switch (reloadLevel) {
105786                 case ts.ConfigFileProgramReloadLevel.Partial:
105787                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
105788                     reloadFileNamesFromConfigFile();
105789                     break;
105790                 case ts.ConfigFileProgramReloadLevel.Full:
105791                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
105792                     reloadConfigFile();
105793                     break;
105794                 default:
105795                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
105796                     synchronizeProgram();
105797                     break;
105798             }
105799             ts.perfLogger.logStopUpdateProgram("Done");
105800             return getCurrentBuilderProgram();
105801         }
105802         function reloadFileNamesFromConfigFile() {
105803             writeLog("Reloading new file names and options");
105804             var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
105805             if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
105806                 hasChangedConfigFileParsingErrors = true;
105807             }
105808             rootFileNames = result.fileNames;
105809             // Update the program
105810             synchronizeProgram();
105811         }
105812         function reloadConfigFile() {
105813             writeLog("Reloading config file: " + configFileName);
105814             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
105815             if (cachedDirectoryStructureHost) {
105816                 cachedDirectoryStructureHost.clearCache();
105817             }
105818             parseConfigFile();
105819             hasChangedCompilerOptions = true;
105820             synchronizeProgram();
105821             // Update the wild card directory watch
105822             watchConfigFileWildCardDirectories();
105823         }
105824         function parseConfigFile() {
105825             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
105826         }
105827         function setConfigFileParsingResult(configFileParseResult) {
105828             rootFileNames = configFileParseResult.fileNames;
105829             compilerOptions = configFileParseResult.options;
105830             watchOptions = configFileParseResult.watchOptions;
105831             configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
105832             projectReferences = configFileParseResult.projectReferences;
105833             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
105834             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw);
105835             hasChangedConfigFileParsingErrors = true;
105836         }
105837         function onSourceFileChange(fileName, eventKind, path) {
105838             updateCachedSystemWithFile(fileName, path, eventKind);
105839             // Update the source file cache
105840             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
105841                 resolutionCache.invalidateResolutionOfFile(path);
105842             }
105843             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
105844             nextSourceFileVersion(path);
105845             // Update the program
105846             scheduleProgramUpdate();
105847         }
105848         function updateCachedSystemWithFile(fileName, path, eventKind) {
105849             if (cachedDirectoryStructureHost) {
105850                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
105851             }
105852         }
105853         function watchMissingFilePath(missingFilePath) {
105854             return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
105855         }
105856         function onMissingFileChange(fileName, eventKind, missingFilePath) {
105857             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
105858             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
105859                 missingFilesMap.get(missingFilePath).close();
105860                 missingFilesMap.delete(missingFilePath);
105861                 // Delete the entry in the source files cache so that new source file is created
105862                 nextSourceFileVersion(missingFilePath);
105863                 // When a missing file is created, we should update the graph.
105864                 scheduleProgramUpdate();
105865             }
105866         }
105867         function watchConfigFileWildCardDirectories() {
105868             if (configFileSpecs) {
105869                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
105870             }
105871             else if (watchedWildcardDirectories) {
105872                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105873             }
105874         }
105875         function watchWildcardDirectory(directory, flags) {
105876             return watchDirectory(host, directory, function (fileOrDirectory) {
105877                 ts.Debug.assert(!!configFileName);
105878                 var fileOrDirectoryPath = toPath(fileOrDirectory);
105879                 // Since the file existence changed, update the sourceFiles cache
105880                 if (cachedDirectoryStructureHost) {
105881                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
105882                 }
105883                 nextSourceFileVersion(fileOrDirectoryPath);
105884                 fileOrDirectoryPath = ts.removeIgnoredPath(fileOrDirectoryPath);
105885                 if (!fileOrDirectoryPath)
105886                     return;
105887                 // If the the added or created file or directory is not supported file name, ignore the file
105888                 // But when watched directory is added/removed, we need to reload the file list
105889                 if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
105890                     writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
105891                     return;
105892                 }
105893                 // Reload is pending, do the reload
105894                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
105895                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
105896                     // Schedule Update the program
105897                     scheduleProgramUpdate();
105898                 }
105899             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
105900         }
105901     }
105902     ts.createWatchProgram = createWatchProgram;
105903 })(ts || (ts = {}));
105904 /*@internal*/
105905 var ts;
105906 (function (ts) {
105907     var UpToDateStatusType;
105908     (function (UpToDateStatusType) {
105909         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
105910         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
105911         /**
105912          * The project appears out of date because its upstream inputs are newer than its outputs,
105913          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105914          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
105915          */
105916         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
105917         /**
105918          * The project appears out of date because its upstream inputs are newer than its outputs,
105919          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105920          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
105921          */
105922         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
105923         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
105924         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
105925         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
105926         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
105927         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
105928         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
105929         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
105930         /**
105931          * Projects with no outputs (i.e. "solution" files)
105932          */
105933         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
105934     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
105935     function resolveConfigFileProjectName(project) {
105936         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
105937             return project;
105938         }
105939         return ts.combinePaths(project, "tsconfig.json");
105940     }
105941     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
105942 })(ts || (ts = {}));
105943 var ts;
105944 (function (ts) {
105945     var minimumDate = new Date(-8640000000000000);
105946     var maximumDate = new Date(8640000000000000);
105947     var BuildResultFlags;
105948     (function (BuildResultFlags) {
105949         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
105950         /**
105951          * No errors of any kind occurred during build
105952          */
105953         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
105954         /**
105955          * None of the .d.ts files emitted by this build were
105956          * different from the existing files on disk
105957          */
105958         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
105959         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
105960         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
105961         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
105962         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
105963         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
105964         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
105965     })(BuildResultFlags || (BuildResultFlags = {}));
105966     function createConfigFileMap() {
105967         return ts.createMap();
105968     }
105969     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
105970         var existingValue = configFileMap.get(resolved);
105971         var newValue;
105972         if (!existingValue) {
105973             newValue = createT();
105974             configFileMap.set(resolved, newValue);
105975         }
105976         return existingValue || newValue;
105977     }
105978     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
105979         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
105980     }
105981     function newer(date1, date2) {
105982         return date2 > date1 ? date2 : date1;
105983     }
105984     function isDeclarationFile(fileName) {
105985         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
105986     }
105987     /*@internal*/
105988     function isCircularBuildOrder(buildOrder) {
105989         return !!buildOrder && !!buildOrder.buildOrder;
105990     }
105991     ts.isCircularBuildOrder = isCircularBuildOrder;
105992     /*@internal*/
105993     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
105994         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
105995     }
105996     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
105997     /**
105998      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105999      */
106000     function createBuilderStatusReporter(system, pretty) {
106001         return function (diagnostic) {
106002             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
106003             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
106004             system.write(output);
106005         };
106006     }
106007     ts.createBuilderStatusReporter = createBuilderStatusReporter;
106008     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
106009         var host = ts.createProgramHost(system, createProgram);
106010         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
106011         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
106012         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
106013         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
106014         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
106015         host.now = ts.maybeBind(system, system.now); // For testing
106016         return host;
106017     }
106018     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
106019         if (system === void 0) { system = ts.sys; }
106020         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106021         host.reportErrorSummary = reportErrorSummary;
106022         return host;
106023     }
106024     ts.createSolutionBuilderHost = createSolutionBuilderHost;
106025     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
106026         if (system === void 0) { system = ts.sys; }
106027         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106028         var watchHost = ts.createWatchHost(system, reportWatchStatus);
106029         ts.copyProperties(host, watchHost);
106030         return host;
106031     }
106032     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
106033     function getCompilerOptionsOfBuildOptions(buildOptions) {
106034         var result = {};
106035         ts.commonOptionsWithBuild.forEach(function (option) {
106036             if (ts.hasProperty(buildOptions, option.name))
106037                 result[option.name] = buildOptions[option.name];
106038         });
106039         return result;
106040     }
106041     function createSolutionBuilder(host, rootNames, defaultOptions) {
106042         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
106043     }
106044     ts.createSolutionBuilder = createSolutionBuilder;
106045     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
106046         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
106047     }
106048     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
106049     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
106050         var host = hostOrHostWithWatch;
106051         var hostWithWatch = hostOrHostWithWatch;
106052         var currentDirectory = host.getCurrentDirectory();
106053         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
106054         // State of the solution
106055         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
106056         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
106057         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
106058         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
106059         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
106060         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
106061         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
106062         if (!compilerHost.resolveModuleNames) {
106063             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
106064             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
106065                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
106066             };
106067         }
106068         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
106069         var state = {
106070             host: host,
106071             hostWithWatch: hostWithWatch,
106072             currentDirectory: currentDirectory,
106073             getCanonicalFileName: getCanonicalFileName,
106074             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
106075             writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
106076             // State of solution
106077             options: options,
106078             baseCompilerOptions: baseCompilerOptions,
106079             rootNames: rootNames,
106080             baseWatchOptions: baseWatchOptions,
106081             resolvedConfigFilePaths: ts.createMap(),
106082             configFileCache: createConfigFileMap(),
106083             projectStatus: createConfigFileMap(),
106084             buildInfoChecked: createConfigFileMap(),
106085             extendedConfigCache: ts.createMap(),
106086             builderPrograms: createConfigFileMap(),
106087             diagnostics: createConfigFileMap(),
106088             projectPendingBuild: createConfigFileMap(),
106089             projectErrorsReported: createConfigFileMap(),
106090             compilerHost: compilerHost,
106091             moduleResolutionCache: moduleResolutionCache,
106092             // Mutable state
106093             buildOrder: undefined,
106094             readFileWithCache: function (f) { return host.readFile(f); },
106095             projectCompilerOptions: baseCompilerOptions,
106096             cache: undefined,
106097             allProjectBuildPending: true,
106098             needsSummary: true,
106099             watchAllProjectsPending: watch,
106100             currentInvalidatedProject: undefined,
106101             // Watch state
106102             watch: watch,
106103             allWatchedWildcardDirectories: createConfigFileMap(),
106104             allWatchedInputFiles: createConfigFileMap(),
106105             allWatchedConfigFiles: createConfigFileMap(),
106106             timerToBuildInvalidatedProject: undefined,
106107             reportFileChangeDetected: false,
106108             watchFile: watchFile,
106109             watchFilePath: watchFilePath,
106110             watchDirectory: watchDirectory,
106111             writeLog: writeLog,
106112         };
106113         return state;
106114     }
106115     function toPath(state, fileName) {
106116         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
106117     }
106118     function toResolvedConfigFilePath(state, fileName) {
106119         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
106120         var path = resolvedConfigFilePaths.get(fileName);
106121         if (path !== undefined)
106122             return path;
106123         var resolvedPath = toPath(state, fileName);
106124         resolvedConfigFilePaths.set(fileName, resolvedPath);
106125         return resolvedPath;
106126     }
106127     function isParsedCommandLine(entry) {
106128         return !!entry.options;
106129     }
106130     function parseConfigFile(state, configFileName, configFilePath) {
106131         var configFileCache = state.configFileCache;
106132         var value = configFileCache.get(configFilePath);
106133         if (value) {
106134             return isParsedCommandLine(value) ? value : undefined;
106135         }
106136         var diagnostic;
106137         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
106138         var parsed;
106139         if (host.getParsedCommandLine) {
106140             parsed = host.getParsedCommandLine(configFileName);
106141             if (!parsed)
106142                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
106143         }
106144         else {
106145             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
106146             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
106147             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
106148         }
106149         configFileCache.set(configFilePath, parsed || diagnostic);
106150         return parsed;
106151     }
106152     function resolveProjectName(state, name) {
106153         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
106154     }
106155     function createBuildOrder(state, roots) {
106156         var temporaryMarks = ts.createMap();
106157         var permanentMarks = ts.createMap();
106158         var circularityReportStack = [];
106159         var buildOrder;
106160         var circularDiagnostics;
106161         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
106162             var root = roots_1[_i];
106163             visit(root);
106164         }
106165         return circularDiagnostics ?
106166             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
106167             buildOrder || ts.emptyArray;
106168         function visit(configFileName, inCircularContext) {
106169             var projPath = toResolvedConfigFilePath(state, configFileName);
106170             // Already visited
106171             if (permanentMarks.has(projPath))
106172                 return;
106173             // Circular
106174             if (temporaryMarks.has(projPath)) {
106175                 if (!inCircularContext) {
106176                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
106177                 }
106178                 return;
106179             }
106180             temporaryMarks.set(projPath, true);
106181             circularityReportStack.push(configFileName);
106182             var parsed = parseConfigFile(state, configFileName, projPath);
106183             if (parsed && parsed.projectReferences) {
106184                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
106185                     var ref = _a[_i];
106186                     var resolvedRefPath = resolveProjectName(state, ref.path);
106187                     visit(resolvedRefPath, inCircularContext || ref.circular);
106188                 }
106189             }
106190             circularityReportStack.pop();
106191             permanentMarks.set(projPath, true);
106192             (buildOrder || (buildOrder = [])).push(configFileName);
106193         }
106194     }
106195     function getBuildOrder(state) {
106196         return state.buildOrder || createStateBuildOrder(state);
106197     }
106198     function createStateBuildOrder(state) {
106199         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
106200         // Clear all to ResolvedConfigFilePaths cache to start fresh
106201         state.resolvedConfigFilePaths.clear();
106202         var currentProjects = ts.arrayToSet(getBuildOrderFromAnyBuildOrder(buildOrder), function (resolved) { return toResolvedConfigFilePath(state, resolved); });
106203         var noopOnDelete = { onDeleteValue: ts.noop };
106204         // Config file cache
106205         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
106206         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
106207         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
106208         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
106209         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
106210         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
106211         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
106212         // Remove watches for the program no longer in the solution
106213         if (state.watch) {
106214             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
106215             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
106216             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
106217         }
106218         return state.buildOrder = buildOrder;
106219     }
106220     function getBuildOrderFor(state, project, onlyReferences) {
106221         var resolvedProject = project && resolveProjectName(state, project);
106222         var buildOrderFromState = getBuildOrder(state);
106223         if (isCircularBuildOrder(buildOrderFromState))
106224             return buildOrderFromState;
106225         if (resolvedProject) {
106226             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
106227             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
106228             if (projectIndex === -1)
106229                 return undefined;
106230         }
106231         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
106232         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
106233         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
106234         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
106235         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
106236     }
106237     function enableCache(state) {
106238         if (state.cache) {
106239             disableCache(state);
106240         }
106241         var compilerHost = state.compilerHost, host = state.host;
106242         var originalReadFileWithCache = state.readFileWithCache;
106243         var originalGetSourceFile = compilerHost.getSourceFile;
106244         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
106245             var args = [];
106246             for (var _i = 0; _i < arguments.length; _i++) {
106247                 args[_i] = arguments[_i];
106248             }
106249             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
106250         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
106251         state.readFileWithCache = readFileWithCache;
106252         compilerHost.getSourceFile = getSourceFileWithCache;
106253         state.cache = {
106254             originalReadFile: originalReadFile,
106255             originalFileExists: originalFileExists,
106256             originalDirectoryExists: originalDirectoryExists,
106257             originalCreateDirectory: originalCreateDirectory,
106258             originalWriteFile: originalWriteFile,
106259             originalReadFileWithCache: originalReadFileWithCache,
106260             originalGetSourceFile: originalGetSourceFile,
106261         };
106262     }
106263     function disableCache(state) {
106264         if (!state.cache)
106265             return;
106266         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
106267         host.readFile = cache.originalReadFile;
106268         host.fileExists = cache.originalFileExists;
106269         host.directoryExists = cache.originalDirectoryExists;
106270         host.createDirectory = cache.originalCreateDirectory;
106271         host.writeFile = cache.originalWriteFile;
106272         compilerHost.getSourceFile = cache.originalGetSourceFile;
106273         state.readFileWithCache = cache.originalReadFileWithCache;
106274         extendedConfigCache.clear();
106275         if (moduleResolutionCache) {
106276             moduleResolutionCache.directoryToModuleNameMap.clear();
106277             moduleResolutionCache.moduleNameToDirectoryMap.clear();
106278         }
106279         state.cache = undefined;
106280     }
106281     function clearProjectStatus(state, resolved) {
106282         state.projectStatus.delete(resolved);
106283         state.diagnostics.delete(resolved);
106284     }
106285     function addProjToQueue(_a, proj, reloadLevel) {
106286         var projectPendingBuild = _a.projectPendingBuild;
106287         var value = projectPendingBuild.get(proj);
106288         if (value === undefined) {
106289             projectPendingBuild.set(proj, reloadLevel);
106290         }
106291         else if (value < reloadLevel) {
106292             projectPendingBuild.set(proj, reloadLevel);
106293         }
106294     }
106295     function setupInitialBuild(state, cancellationToken) {
106296         // Set initial build if not already built
106297         if (!state.allProjectBuildPending)
106298             return;
106299         state.allProjectBuildPending = false;
106300         if (state.options.watch) {
106301             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
106302         }
106303         enableCache(state);
106304         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
106305         buildOrder.forEach(function (configFileName) {
106306             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
106307         });
106308         if (cancellationToken) {
106309             cancellationToken.throwIfCancellationRequested();
106310         }
106311     }
106312     var InvalidatedProjectKind;
106313     (function (InvalidatedProjectKind) {
106314         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
106315         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
106316         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
106317     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
106318     function doneInvalidatedProject(state, projectPath) {
106319         state.projectPendingBuild.delete(projectPath);
106320         state.currentInvalidatedProject = undefined;
106321         return state.diagnostics.has(projectPath) ?
106322             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
106323             ts.ExitStatus.Success;
106324     }
106325     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
106326         var updateOutputFileStampsPending = true;
106327         return {
106328             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
106329             project: project,
106330             projectPath: projectPath,
106331             buildOrder: buildOrder,
106332             getCompilerOptions: function () { return config.options; },
106333             getCurrentDirectory: function () { return state.currentDirectory; },
106334             updateOutputFileStatmps: function () {
106335                 updateOutputTimestamps(state, config, projectPath);
106336                 updateOutputFileStampsPending = false;
106337             },
106338             done: function () {
106339                 if (updateOutputFileStampsPending) {
106340                     updateOutputTimestamps(state, config, projectPath);
106341                 }
106342                 return doneInvalidatedProject(state, projectPath);
106343             }
106344         };
106345     }
106346     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
106347         var Step;
106348         (function (Step) {
106349             Step[Step["CreateProgram"] = 0] = "CreateProgram";
106350             Step[Step["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
106351             Step[Step["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
106352             Step[Step["Emit"] = 3] = "Emit";
106353             Step[Step["EmitBundle"] = 4] = "EmitBundle";
106354             Step[Step["BuildInvalidatedProjectOfBundle"] = 5] = "BuildInvalidatedProjectOfBundle";
106355             Step[Step["QueueReferencingProjects"] = 6] = "QueueReferencingProjects";
106356             Step[Step["Done"] = 7] = "Done";
106357         })(Step || (Step = {}));
106358         var step = kind === InvalidatedProjectKind.Build ? Step.CreateProgram : Step.EmitBundle;
106359         var program;
106360         var buildResult;
106361         var invalidatedProjectOfBundle;
106362         return kind === InvalidatedProjectKind.Build ?
106363             {
106364                 kind: kind,
106365                 project: project,
106366                 projectPath: projectPath,
106367                 buildOrder: buildOrder,
106368                 getCompilerOptions: function () { return config.options; },
106369                 getCurrentDirectory: function () { return state.currentDirectory; },
106370                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
106371                 getProgram: function () {
106372                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
106373                 },
106374                 getSourceFile: function (fileName) {
106375                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
106376                 },
106377                 getSourceFiles: function () {
106378                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
106379                 },
106380                 getOptionsDiagnostics: function (cancellationToken) {
106381                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
106382                 },
106383                 getGlobalDiagnostics: function (cancellationToken) {
106384                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
106385                 },
106386                 getConfigFileParsingDiagnostics: function () {
106387                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
106388                 },
106389                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
106390                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
106391                 },
106392                 getAllDependencies: function (sourceFile) {
106393                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
106394                 },
106395                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
106396                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
106397                 },
106398                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
106399                     return withProgramOrUndefined(function (program) {
106400                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
106401                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
106402                     });
106403                 },
106404                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
106405                     if (targetSourceFile || emitOnlyDtsFiles) {
106406                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
106407                     }
106408                     executeSteps(Step.SemanticDiagnostics, cancellationToken);
106409                     if (step !== Step.Emit)
106410                         return undefined;
106411                     return emit(writeFile, cancellationToken, customTransformers);
106412                 },
106413                 done: done
106414             } :
106415             {
106416                 kind: kind,
106417                 project: project,
106418                 projectPath: projectPath,
106419                 buildOrder: buildOrder,
106420                 getCompilerOptions: function () { return config.options; },
106421                 getCurrentDirectory: function () { return state.currentDirectory; },
106422                 emit: function (writeFile, customTransformers) {
106423                     if (step !== Step.EmitBundle)
106424                         return invalidatedProjectOfBundle;
106425                     return emitBundle(writeFile, customTransformers);
106426                 },
106427                 done: done,
106428             };
106429         function done(cancellationToken, writeFile, customTransformers) {
106430             executeSteps(Step.Done, cancellationToken, writeFile, customTransformers);
106431             return doneInvalidatedProject(state, projectPath);
106432         }
106433         function withProgramOrUndefined(action) {
106434             executeSteps(Step.CreateProgram);
106435             return program && action(program);
106436         }
106437         function withProgramOrEmptyArray(action) {
106438             return withProgramOrUndefined(action) || ts.emptyArray;
106439         }
106440         function createProgram() {
106441             ts.Debug.assert(program === undefined);
106442             if (state.options.dry) {
106443                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
106444                 buildResult = BuildResultFlags.Success;
106445                 step = Step.QueueReferencingProjects;
106446                 return;
106447             }
106448             if (state.options.verbose)
106449                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
106450             if (config.fileNames.length === 0) {
106451                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106452                 // Nothing to build - must be a solution file, basically
106453                 buildResult = BuildResultFlags.None;
106454                 step = Step.QueueReferencingProjects;
106455                 return;
106456             }
106457             var host = state.host, compilerHost = state.compilerHost;
106458             state.projectCompilerOptions = config.options;
106459             // Update module resolution cache if needed
106460             updateModuleResolutionCache(state, project, config);
106461             // Create program
106462             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
106463             step++;
106464         }
106465         function handleDiagnostics(diagnostics, errorFlags, errorType) {
106466             if (diagnostics.length) {
106467                 buildResult = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType);
106468                 step = Step.QueueReferencingProjects;
106469             }
106470             else {
106471                 step++;
106472             }
106473         }
106474         function getSyntaxDiagnostics(cancellationToken) {
106475             ts.Debug.assertIsDefined(program);
106476             handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
106477         }
106478         function getSemanticDiagnostics(cancellationToken) {
106479             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
106480         }
106481         function emit(writeFileCallback, cancellationToken, customTransformers) {
106482             ts.Debug.assertIsDefined(program);
106483             ts.Debug.assert(step === Step.Emit);
106484             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
106485             program.backupState();
106486             var declDiagnostics;
106487             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
106488             var outputFiles = [];
106489             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
106490             /*writeFileName*/ undefined, 
106491             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
106492             /*emitOnlyDts*/ false, customTransformers).emitResult;
106493             // Don't emit .d.ts if there are decl file errors
106494             if (declDiagnostics) {
106495                 program.restoreState();
106496                 buildResult = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
106497                 step = Step.QueueReferencingProjects;
106498                 return {
106499                     emitSkipped: true,
106500                     diagnostics: emitResult.diagnostics
106501                 };
106502             }
106503             // Actual Emit
106504             var host = state.host, compilerHost = state.compilerHost;
106505             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
106506             var newestDeclarationFileContentChangedTime = minimumDate;
106507             var anyDtsChanged = false;
106508             var emitterDiagnostics = ts.createDiagnosticCollection();
106509             var emittedOutputs = ts.createMap();
106510             outputFiles.forEach(function (_a) {
106511                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106512                 var priorChangeTime;
106513                 if (!anyDtsChanged && isDeclarationFile(name)) {
106514                     // Check for unchanged .d.ts files
106515                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
106516                         priorChangeTime = host.getModifiedTime(name);
106517                     }
106518                     else {
106519                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
106520                         anyDtsChanged = true;
106521                     }
106522                 }
106523                 emittedOutputs.set(toPath(state, name), name);
106524                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106525                 if (priorChangeTime !== undefined) {
106526                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
106527                 }
106528             });
106529             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
106530             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
106531             return emitResult;
106532         }
106533         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
106534             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
106535             if (emitDiagnostics.length) {
106536                 buildResult = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
106537                 step = Step.QueueReferencingProjects;
106538                 return emitDiagnostics;
106539             }
106540             if (state.writeFileName) {
106541                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
106542                 if (program)
106543                     ts.listFiles(program, state.writeFileName);
106544             }
106545             // Update time stamps for rest of the outputs
106546             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
106547             state.diagnostics.delete(projectPath);
106548             state.projectStatus.set(projectPath, {
106549                 type: ts.UpToDateStatusType.UpToDate,
106550                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
106551                     maximumDate :
106552                     newestDeclarationFileContentChangedTime,
106553                 oldestOutputFileName: oldestOutputFileName
106554             });
106555             afterProgramDone(state, projectPath, program, config);
106556             state.projectCompilerOptions = state.baseCompilerOptions;
106557             step = Step.QueueReferencingProjects;
106558             buildResult = resultFlags;
106559             return emitDiagnostics;
106560         }
106561         function emitBundle(writeFileCallback, customTransformers) {
106562             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
106563             if (state.options.dry) {
106564                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
106565                 buildResult = BuildResultFlags.Success;
106566                 step = Step.QueueReferencingProjects;
106567                 return undefined;
106568             }
106569             if (state.options.verbose)
106570                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
106571             // Update js, and source map
106572             var compilerHost = state.compilerHost;
106573             state.projectCompilerOptions = config.options;
106574             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
106575                 var refName = resolveProjectName(state, ref.path);
106576                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
106577             }, customTransformers);
106578             if (ts.isString(outputFiles)) {
106579                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
106580                 step = Step.BuildInvalidatedProjectOfBundle;
106581                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
106582             }
106583             // Actual Emit
106584             ts.Debug.assert(!!outputFiles.length);
106585             var emitterDiagnostics = ts.createDiagnosticCollection();
106586             var emittedOutputs = ts.createMap();
106587             outputFiles.forEach(function (_a) {
106588                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106589                 emittedOutputs.set(toPath(state, name), name);
106590                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106591             });
106592             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
106593             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
106594             return { emitSkipped: false, diagnostics: emitDiagnostics };
106595         }
106596         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
106597             while (step <= till && step < Step.Done) {
106598                 var currentStep = step;
106599                 switch (step) {
106600                     case Step.CreateProgram:
106601                         createProgram();
106602                         break;
106603                     case Step.SyntaxDiagnostics:
106604                         getSyntaxDiagnostics(cancellationToken);
106605                         break;
106606                     case Step.SemanticDiagnostics:
106607                         getSemanticDiagnostics(cancellationToken);
106608                         break;
106609                     case Step.Emit:
106610                         emit(writeFile, cancellationToken, customTransformers);
106611                         break;
106612                     case Step.EmitBundle:
106613                         emitBundle(writeFile, customTransformers);
106614                         break;
106615                     case Step.BuildInvalidatedProjectOfBundle:
106616                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
106617                         step = Step.Done;
106618                         break;
106619                     case Step.QueueReferencingProjects:
106620                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
106621                         step++;
106622                         break;
106623                     // Should never be done
106624                     case Step.Done:
106625                     default:
106626                         ts.assertType(step);
106627                 }
106628                 ts.Debug.assert(step > currentStep);
106629             }
106630         }
106631     }
106632     function needsBuild(_a, status, config) {
106633         var options = _a.options;
106634         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
106635             return true;
106636         return config.fileNames.length === 0 ||
106637             !!ts.getConfigFileParsingDiagnostics(config).length ||
106638             !ts.isIncrementalCompilation(config.options);
106639     }
106640     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
106641         if (!state.projectPendingBuild.size)
106642             return undefined;
106643         if (isCircularBuildOrder(buildOrder))
106644             return undefined;
106645         if (state.currentInvalidatedProject) {
106646             // Only if same buildOrder the currentInvalidated project can be sent again
106647             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
106648                 state.currentInvalidatedProject :
106649                 undefined;
106650         }
106651         var options = state.options, projectPendingBuild = state.projectPendingBuild;
106652         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
106653             var project = buildOrder[projectIndex];
106654             var projectPath = toResolvedConfigFilePath(state, project);
106655             var reloadLevel = state.projectPendingBuild.get(projectPath);
106656             if (reloadLevel === undefined)
106657                 continue;
106658             if (reportQueue) {
106659                 reportQueue = false;
106660                 reportBuildQueue(state, buildOrder);
106661             }
106662             var config = parseConfigFile(state, project, projectPath);
106663             if (!config) {
106664                 reportParseConfigFileDiagnostic(state, projectPath);
106665                 projectPendingBuild.delete(projectPath);
106666                 continue;
106667             }
106668             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
106669                 watchConfigFile(state, project, projectPath, config);
106670                 watchWildCardDirectories(state, project, projectPath, config);
106671                 watchInputFiles(state, project, projectPath, config);
106672             }
106673             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
106674                 // Update file names
106675                 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
106676                 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInutFiles(config.raw));
106677                 config.fileNames = result.fileNames;
106678                 watchInputFiles(state, project, projectPath, config);
106679             }
106680             var status = getUpToDateStatus(state, config, projectPath);
106681             verboseReportProjectStatus(state, project, status);
106682             if (!options.force) {
106683                 if (status.type === ts.UpToDateStatusType.UpToDate) {
106684                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106685                     projectPendingBuild.delete(projectPath);
106686                     // Up to date, skip
106687                     if (options.dry) {
106688                         // In a dry build, inform the user of this fact
106689                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
106690                     }
106691                     continue;
106692                 }
106693                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
106694                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106695                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
106696                 }
106697             }
106698             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
106699                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106700                 projectPendingBuild.delete(projectPath);
106701                 if (options.verbose) {
106702                     reportStatus(state, status.upstreamProjectBlocked ?
106703                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
106704                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
106705                 }
106706                 continue;
106707             }
106708             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
106709                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106710                 projectPendingBuild.delete(projectPath);
106711                 // Do nothing
106712                 continue;
106713             }
106714             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
106715                 InvalidatedProjectKind.Build :
106716                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
106717         }
106718         return undefined;
106719     }
106720     function listEmittedFile(_a, proj, file) {
106721         var writeFileName = _a.writeFileName;
106722         if (writeFileName && proj.options.listEmittedFiles) {
106723             writeFileName("TSFILE: " + file);
106724         }
106725     }
106726     function getOldProgram(_a, proj, parsed) {
106727         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
106728         if (options.force)
106729             return undefined;
106730         var value = builderPrograms.get(proj);
106731         if (value)
106732             return value;
106733         return ts.readBuilderProgram(parsed.options, compilerHost);
106734     }
106735     function afterProgramDone(_a, proj, program, config) {
106736         var host = _a.host, watch = _a.watch, builderPrograms = _a.builderPrograms;
106737         if (program) {
106738             if (host.afterProgramEmitAndDiagnostics) {
106739                 host.afterProgramEmitAndDiagnostics(program);
106740             }
106741             if (watch) {
106742                 program.releaseProgram();
106743                 builderPrograms.set(proj, program);
106744             }
106745         }
106746         else if (host.afterEmitBundle) {
106747             host.afterEmitBundle(config);
106748         }
106749     }
106750     function buildErrors(state, resolvedPath, program, config, diagnostics, errorFlags, errorType) {
106751         reportAndStoreErrors(state, resolvedPath, diagnostics);
106752         // List files if any other build error using program (emit errors already report files)
106753         if (program && state.writeFileName)
106754             ts.listFiles(program, state.writeFileName);
106755         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
106756         afterProgramDone(state, resolvedPath, program, config);
106757         state.projectCompilerOptions = state.baseCompilerOptions;
106758         return errorFlags;
106759     }
106760     function updateModuleResolutionCache(state, proj, config) {
106761         if (!state.moduleResolutionCache)
106762             return;
106763         // Update module resolution cache if needed
106764         var moduleResolutionCache = state.moduleResolutionCache;
106765         var projPath = toPath(state, proj);
106766         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
106767             // The own map will be for projectCompilerOptions
106768             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
106769             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
106770             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
106771         }
106772         else {
106773             // Set correct own map
106774             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
106775             var ref = {
106776                 sourceFile: config.options.configFile,
106777                 commandLine: config
106778             };
106779             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
106780             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
106781         }
106782         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
106783         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
106784     }
106785     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
106786         // Check tsconfig time
106787         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
106788         if (oldestOutputFileTime < tsconfigTime) {
106789             return {
106790                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106791                 outOfDateOutputFileName: oldestOutputFileName,
106792                 newerInputFileName: configFile
106793             };
106794         }
106795     }
106796     function getUpToDateStatusWorker(state, project, resolvedPath) {
106797         var newestInputFileName = undefined;
106798         var newestInputFileTime = minimumDate;
106799         var host = state.host;
106800         // Get timestamps of input files
106801         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
106802             var inputFile = _a[_i];
106803             if (!host.fileExists(inputFile)) {
106804                 return {
106805                     type: ts.UpToDateStatusType.Unbuildable,
106806                     reason: inputFile + " does not exist"
106807                 };
106808             }
106809             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
106810             if (inputTime > newestInputFileTime) {
106811                 newestInputFileName = inputFile;
106812                 newestInputFileTime = inputTime;
106813             }
106814         }
106815         // Container if no files are specified in the project
106816         if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
106817             return {
106818                 type: ts.UpToDateStatusType.ContainerOnly
106819             };
106820         }
106821         // Collect the expected outputs of this project
106822         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
106823         // Now see if all outputs are newer than the newest input
106824         var oldestOutputFileName = "(none)";
106825         var oldestOutputFileTime = maximumDate;
106826         var newestOutputFileName = "(none)";
106827         var newestOutputFileTime = minimumDate;
106828         var missingOutputFileName;
106829         var newestDeclarationFileContentChangedTime = minimumDate;
106830         var isOutOfDateWithInputs = false;
106831         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
106832             var output = outputs_1[_b];
106833             // Output is missing; can stop checking
106834             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106835             if (!host.fileExists(output)) {
106836                 missingOutputFileName = output;
106837                 break;
106838             }
106839             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106840             if (outputTime < oldestOutputFileTime) {
106841                 oldestOutputFileTime = outputTime;
106842                 oldestOutputFileName = output;
106843             }
106844             // If an output is older than the newest input, we can stop checking
106845             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106846             if (outputTime < newestInputFileTime) {
106847                 isOutOfDateWithInputs = true;
106848                 break;
106849             }
106850             if (outputTime > newestOutputFileTime) {
106851                 newestOutputFileTime = outputTime;
106852                 newestOutputFileName = output;
106853             }
106854             // Keep track of when the most recent time a .d.ts file was changed.
106855             // In addition to file timestamps, we also keep track of when a .d.ts file
106856             // had its file touched but not had its contents changed - this allows us
106857             // to skip a downstream typecheck
106858             if (isDeclarationFile(output)) {
106859                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106860                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
106861             }
106862         }
106863         var pseudoUpToDate = false;
106864         var usesPrepend = false;
106865         var upstreamChangedProject;
106866         if (project.projectReferences) {
106867             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
106868             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
106869                 var ref = _d[_c];
106870                 usesPrepend = usesPrepend || !!(ref.prepend);
106871                 var resolvedRef = ts.resolveProjectReferencePath(ref);
106872                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
106873                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
106874                 // Its a circular reference ignore the status of this project
106875                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
106876                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
106877                     continue;
106878                 }
106879                 // An upstream project is blocked
106880                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
106881                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
106882                     return {
106883                         type: ts.UpToDateStatusType.UpstreamBlocked,
106884                         upstreamProjectName: ref.path,
106885                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
106886                     };
106887                 }
106888                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
106889                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
106890                     return {
106891                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
106892                         upstreamProjectName: ref.path
106893                     };
106894                 }
106895                 // Check oldest output file name only if there is no missing output file name
106896                 if (!missingOutputFileName) {
106897                     // If the upstream project's newest file is older than our oldest output, we
106898                     // can't be out of date because of it
106899                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
106900                         continue;
106901                     }
106902                     // If the upstream project has only change .d.ts files, and we've built
106903                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
106904                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
106905                         pseudoUpToDate = true;
106906                         upstreamChangedProject = ref.path;
106907                         continue;
106908                     }
106909                     // We have an output older than an upstream output - we are out of date
106910                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
106911                     return {
106912                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
106913                         outOfDateOutputFileName: oldestOutputFileName,
106914                         newerProjectName: ref.path
106915                     };
106916                 }
106917             }
106918         }
106919         if (missingOutputFileName !== undefined) {
106920             return {
106921                 type: ts.UpToDateStatusType.OutputMissing,
106922                 missingOutputFileName: missingOutputFileName
106923             };
106924         }
106925         if (isOutOfDateWithInputs) {
106926             return {
106927                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106928                 outOfDateOutputFileName: oldestOutputFileName,
106929                 newerInputFileName: newestInputFileName
106930             };
106931         }
106932         else {
106933             // Check tsconfig time
106934             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
106935             if (configStatus)
106936                 return configStatus;
106937             // Check extended config time
106938             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
106939             if (extendedConfigStatus)
106940                 return extendedConfigStatus;
106941         }
106942         if (!state.buildInfoChecked.has(resolvedPath)) {
106943             state.buildInfoChecked.set(resolvedPath, true);
106944             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
106945             if (buildInfoPath) {
106946                 var value = state.readFileWithCache(buildInfoPath);
106947                 var buildInfo = value && ts.getBuildInfo(value);
106948                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
106949                     return {
106950                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
106951                         version: buildInfo.version
106952                     };
106953                 }
106954             }
106955         }
106956         if (usesPrepend && pseudoUpToDate) {
106957             return {
106958                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
106959                 outOfDateOutputFileName: oldestOutputFileName,
106960                 newerProjectName: upstreamChangedProject
106961             };
106962         }
106963         // Up to date
106964         return {
106965             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
106966             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
106967             newestInputFileTime: newestInputFileTime,
106968             newestOutputFileTime: newestOutputFileTime,
106969             newestInputFileName: newestInputFileName,
106970             newestOutputFileName: newestOutputFileName,
106971             oldestOutputFileName: oldestOutputFileName
106972         };
106973     }
106974     function getUpToDateStatus(state, project, resolvedPath) {
106975         if (project === undefined) {
106976             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
106977         }
106978         var prior = state.projectStatus.get(resolvedPath);
106979         if (prior !== undefined) {
106980             return prior;
106981         }
106982         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
106983         state.projectStatus.set(resolvedPath, actual);
106984         return actual;
106985     }
106986     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
106987         var host = state.host;
106988         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
106989         if (!skipOutputs || outputs.length !== skipOutputs.size) {
106990             var reportVerbose = !!state.options.verbose;
106991             var now = host.now ? host.now() : new Date();
106992             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
106993                 var file = outputs_2[_i];
106994                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
106995                     continue;
106996                 }
106997                 if (reportVerbose) {
106998                     reportVerbose = false;
106999                     reportStatus(state, verboseMessage, proj.options.configFilePath);
107000                 }
107001                 if (isDeclarationFile(file)) {
107002                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
107003                 }
107004                 host.setModifiedTime(file, now);
107005             }
107006         }
107007         return priorNewestUpdateTime;
107008     }
107009     function updateOutputTimestamps(state, proj, resolvedPath) {
107010         if (state.options.dry) {
107011             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
107012         }
107013         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
107014         state.projectStatus.set(resolvedPath, {
107015             type: ts.UpToDateStatusType.UpToDate,
107016             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
107017             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
107018         });
107019     }
107020     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
107021         // Queue only if there are no errors
107022         if (buildResult & BuildResultFlags.AnyErrors)
107023             return;
107024         // Only composite projects can be referenced by other projects
107025         if (!config.options.composite)
107026             return;
107027         // Always use build order to queue projects
107028         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
107029             var nextProject = buildOrder[index];
107030             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
107031             if (state.projectPendingBuild.has(nextProjectPath))
107032                 continue;
107033             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
107034             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
107035                 continue;
107036             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
107037                 var ref = _a[_i];
107038                 var resolvedRefPath = resolveProjectName(state, ref.path);
107039                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
107040                     continue;
107041                 // If the project is referenced with prepend, always build downstream projects,
107042                 // If declaration output is changed, build the project
107043                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
107044                 var status = state.projectStatus.get(nextProjectPath);
107045                 if (status) {
107046                     switch (status.type) {
107047                         case ts.UpToDateStatusType.UpToDate:
107048                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
107049                                 if (ref.prepend) {
107050                                     state.projectStatus.set(nextProjectPath, {
107051                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
107052                                         outOfDateOutputFileName: status.oldestOutputFileName,
107053                                         newerProjectName: project
107054                                     });
107055                                 }
107056                                 else {
107057                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
107058                                 }
107059                                 break;
107060                             }
107061                         // falls through
107062                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107063                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
107064                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
107065                                 state.projectStatus.set(nextProjectPath, {
107066                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
107067                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
107068                                     newerProjectName: project
107069                                 });
107070                             }
107071                             break;
107072                         case ts.UpToDateStatusType.UpstreamBlocked:
107073                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
107074                                 clearProjectStatus(state, nextProjectPath);
107075                             }
107076                             break;
107077                     }
107078                 }
107079                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
107080                 break;
107081             }
107082         }
107083     }
107084     function build(state, project, cancellationToken, onlyReferences) {
107085         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107086         if (!buildOrder)
107087             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107088         setupInitialBuild(state, cancellationToken);
107089         var reportQueue = true;
107090         var successfulProjects = 0;
107091         while (true) {
107092             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
107093             if (!invalidatedProject)
107094                 break;
107095             reportQueue = false;
107096             invalidatedProject.done(cancellationToken);
107097             if (!state.diagnostics.has(invalidatedProject.projectPath))
107098                 successfulProjects++;
107099         }
107100         disableCache(state);
107101         reportErrorSummary(state, buildOrder);
107102         startWatching(state, buildOrder);
107103         return isCircularBuildOrder(buildOrder)
107104             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
107105             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
107106                 ? ts.ExitStatus.Success
107107                 : successfulProjects
107108                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
107109                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
107110     }
107111     function clean(state, project, onlyReferences) {
107112         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107113         if (!buildOrder)
107114             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107115         if (isCircularBuildOrder(buildOrder)) {
107116             reportErrors(state, buildOrder.circularDiagnostics);
107117             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
107118         }
107119         var options = state.options, host = state.host;
107120         var filesToDelete = options.dry ? [] : undefined;
107121         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
107122             var proj = buildOrder_1[_i];
107123             var resolvedPath = toResolvedConfigFilePath(state, proj);
107124             var parsed = parseConfigFile(state, proj, resolvedPath);
107125             if (parsed === undefined) {
107126                 // File has gone missing; fine to ignore here
107127                 reportParseConfigFileDiagnostic(state, resolvedPath);
107128                 continue;
107129             }
107130             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
107131             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
107132                 var output = outputs_3[_a];
107133                 if (host.fileExists(output)) {
107134                     if (filesToDelete) {
107135                         filesToDelete.push(output);
107136                     }
107137                     else {
107138                         host.deleteFile(output);
107139                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
107140                     }
107141                 }
107142             }
107143         }
107144         if (filesToDelete) {
107145             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
107146         }
107147         return ts.ExitStatus.Success;
107148     }
107149     function invalidateProject(state, resolved, reloadLevel) {
107150         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
107151         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
107152             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
107153         }
107154         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
107155             state.configFileCache.delete(resolved);
107156             state.buildOrder = undefined;
107157         }
107158         state.needsSummary = true;
107159         clearProjectStatus(state, resolved);
107160         addProjToQueue(state, resolved, reloadLevel);
107161         enableCache(state);
107162     }
107163     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
107164         state.reportFileChangeDetected = true;
107165         invalidateProject(state, resolvedPath, reloadLevel);
107166         scheduleBuildInvalidatedProject(state);
107167     }
107168     function scheduleBuildInvalidatedProject(state) {
107169         var hostWithWatch = state.hostWithWatch;
107170         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
107171             return;
107172         }
107173         if (state.timerToBuildInvalidatedProject) {
107174             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
107175         }
107176         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
107177     }
107178     function buildNextInvalidatedProject(state) {
107179         state.timerToBuildInvalidatedProject = undefined;
107180         if (state.reportFileChangeDetected) {
107181             state.reportFileChangeDetected = false;
107182             state.projectErrorsReported.clear();
107183             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
107184         }
107185         var buildOrder = getBuildOrder(state);
107186         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
107187         if (invalidatedProject) {
107188             invalidatedProject.done();
107189             if (state.projectPendingBuild.size) {
107190                 // Schedule next project for build
107191                 if (state.watch && !state.timerToBuildInvalidatedProject) {
107192                     scheduleBuildInvalidatedProject(state);
107193                 }
107194                 return;
107195             }
107196         }
107197         disableCache(state);
107198         reportErrorSummary(state, buildOrder);
107199     }
107200     function watchConfigFile(state, resolved, resolvedPath, parsed) {
107201         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
107202             return;
107203         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
107204             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
107205         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
107206     }
107207     function isSameFile(state, file1, file2) {
107208         return ts.comparePaths(file1, file2, state.currentDirectory, !state.host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107209     }
107210     function isOutputFile(state, fileName, configFile) {
107211         if (configFile.options.noEmit)
107212             return false;
107213         // ts or tsx files are not output
107214         if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
107215             (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
107216             return false;
107217         }
107218         // If options have --outFile or --out, check if its that
107219         var out = configFile.options.outFile || configFile.options.out;
107220         if (out && (isSameFile(state, fileName, out) || isSameFile(state, fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
107221             return true;
107222         }
107223         // If declarationDir is specified, return if its a file in that directory
107224         if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107225             return true;
107226         }
107227         // If --outDir, check if file is in that directory
107228         if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107229             return true;
107230         }
107231         return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(state, fileName, inputFile); });
107232     }
107233     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
107234         if (!state.watch)
107235             return;
107236         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
107237             var fileOrDirectoryPath = toPath(state, fileOrDirectory);
107238             if (fileOrDirectoryPath !== toPath(state, dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
107239                 state.writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory);
107240                 return;
107241             }
107242             if (isOutputFile(state, fileOrDirectory, parsed)) {
107243                 state.writeLog(fileOrDirectory + " is output file");
107244                 return;
107245             }
107246             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
107247         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
107248     }
107249     function watchInputFiles(state, resolved, resolvedPath, parsed) {
107250         if (!state.watch)
107251             return;
107252         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
107253             createNewValue: function (path, input) { return state.watchFilePath(state.hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, path, ts.WatchType.SourceFile, resolved); },
107254             onDeleteValue: ts.closeFileWatcher,
107255         });
107256     }
107257     function startWatching(state, buildOrder) {
107258         if (!state.watchAllProjectsPending)
107259             return;
107260         state.watchAllProjectsPending = false;
107261         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
107262             var resolved = _a[_i];
107263             var resolvedPath = toResolvedConfigFilePath(state, resolved);
107264             var cfg = parseConfigFile(state, resolved, resolvedPath);
107265             // Watch this file
107266             watchConfigFile(state, resolved, resolvedPath, cfg);
107267             if (cfg) {
107268                 // Update watchers for wildcard directories
107269                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
107270                 // Watch input files
107271                 watchInputFiles(state, resolved, resolvedPath, cfg);
107272             }
107273         }
107274     }
107275     function stopWatching(state) {
107276         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
107277         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
107278         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
107279     }
107280     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
107281         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
107282         return {
107283             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
107284             clean: function (project) { return clean(state, project); },
107285             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
107286             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
107287             getNextInvalidatedProject: function (cancellationToken) {
107288                 setupInitialBuild(state, cancellationToken);
107289                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
107290             },
107291             getBuildOrder: function () { return getBuildOrder(state); },
107292             getUpToDateStatusOfProject: function (project) {
107293                 var configFileName = resolveProjectName(state, project);
107294                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
107295                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
107296             },
107297             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
107298             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
107299             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
107300             close: function () { return stopWatching(state); },
107301         };
107302     }
107303     function relName(state, path) {
107304         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
107305     }
107306     function reportStatus(state, message) {
107307         var args = [];
107308         for (var _i = 2; _i < arguments.length; _i++) {
107309             args[_i - 2] = arguments[_i];
107310         }
107311         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
107312     }
107313     function reportWatchStatus(state, message) {
107314         var args = [];
107315         for (var _i = 2; _i < arguments.length; _i++) {
107316             args[_i - 2] = arguments[_i];
107317         }
107318         if (state.hostWithWatch.onWatchStatusChange) {
107319             state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
107320         }
107321     }
107322     function reportErrors(_a, errors) {
107323         var host = _a.host;
107324         errors.forEach(function (err) { return host.reportDiagnostic(err); });
107325     }
107326     function reportAndStoreErrors(state, proj, errors) {
107327         reportErrors(state, errors);
107328         state.projectErrorsReported.set(proj, true);
107329         if (errors.length) {
107330             state.diagnostics.set(proj, errors);
107331         }
107332     }
107333     function reportParseConfigFileDiagnostic(state, proj) {
107334         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
107335     }
107336     function reportErrorSummary(state, buildOrder) {
107337         if (!state.needsSummary)
107338             return;
107339         state.needsSummary = false;
107340         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
107341         var diagnostics = state.diagnostics;
107342         var totalErrors = 0;
107343         if (isCircularBuildOrder(buildOrder)) {
107344             reportBuildQueue(state, buildOrder.buildOrder);
107345             reportErrors(state, buildOrder.circularDiagnostics);
107346             if (canReportSummary)
107347                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
107348         }
107349         else {
107350             // Report errors from the other projects
107351             buildOrder.forEach(function (project) {
107352                 var projectPath = toResolvedConfigFilePath(state, project);
107353                 if (!state.projectErrorsReported.has(projectPath)) {
107354                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
107355                 }
107356             });
107357             if (canReportSummary)
107358                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
107359         }
107360         if (state.watch) {
107361             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
107362         }
107363         else if (state.host.reportErrorSummary) {
107364             state.host.reportErrorSummary(totalErrors);
107365         }
107366     }
107367     /**
107368      * Report the build ordering inferred from the current project graph if we're in verbose mode
107369      */
107370     function reportBuildQueue(state, buildQueue) {
107371         if (state.options.verbose) {
107372             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
107373         }
107374     }
107375     function reportUpToDateStatus(state, configFileName, status) {
107376         switch (status.type) {
107377             case ts.UpToDateStatusType.OutOfDateWithSelf:
107378                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName));
107379             case ts.UpToDateStatusType.OutOfDateWithUpstream:
107380                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName));
107381             case ts.UpToDateStatusType.OutputMissing:
107382                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName));
107383             case ts.UpToDateStatusType.UpToDate:
107384                 if (status.newestInputFileTime !== undefined) {
107385                     return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || ""));
107386                 }
107387                 // Don't report anything for "up to date because it was already built" -- too verbose
107388                 break;
107389             case ts.UpToDateStatusType.OutOfDateWithPrepend:
107390                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName));
107391             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107392                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
107393             case ts.UpToDateStatusType.UpstreamOutOfDate:
107394                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName));
107395             case ts.UpToDateStatusType.UpstreamBlocked:
107396                 return reportStatus(state, status.upstreamProjectBlocked ?
107397                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
107398                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
107399             case ts.UpToDateStatusType.Unbuildable:
107400                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
107401             case ts.UpToDateStatusType.TsVersionOutputOfDate:
107402                 return reportStatus(state, ts.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, ts.version);
107403             case ts.UpToDateStatusType.ContainerOnly:
107404             // Don't report status on "solution" projects
107405             // falls through
107406             case ts.UpToDateStatusType.ComputingUpstream:
107407                 // Should never leak from getUptoDateStatusWorker
107408                 break;
107409             default:
107410                 ts.assertType(status);
107411         }
107412     }
107413     /**
107414      * Report the up-to-date status of a project if we're in verbose mode
107415      */
107416     function verboseReportProjectStatus(state, configFileName, status) {
107417         if (state.options.verbose) {
107418             reportUpToDateStatus(state, configFileName, status);
107419         }
107420     }
107421 })(ts || (ts = {}));
107422 var ts;
107423 (function (ts) {
107424     var ScriptSnapshot;
107425     (function (ScriptSnapshot) {
107426         var StringScriptSnapshot = /** @class */ (function () {
107427             function StringScriptSnapshot(text) {
107428                 this.text = text;
107429             }
107430             StringScriptSnapshot.prototype.getText = function (start, end) {
107431                 return start === 0 && end === this.text.length
107432                     ? this.text
107433                     : this.text.substring(start, end);
107434             };
107435             StringScriptSnapshot.prototype.getLength = function () {
107436                 return this.text.length;
107437             };
107438             StringScriptSnapshot.prototype.getChangeRange = function () {
107439                 // Text-based snapshots do not support incremental parsing. Return undefined
107440                 // to signal that to the caller.
107441                 return undefined;
107442             };
107443             return StringScriptSnapshot;
107444         }());
107445         function fromString(text) {
107446             return new StringScriptSnapshot(text);
107447         }
107448         ScriptSnapshot.fromString = fromString;
107449     })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {}));
107450     /* @internal */
107451     var PackageJsonDependencyGroup;
107452     (function (PackageJsonDependencyGroup) {
107453         PackageJsonDependencyGroup[PackageJsonDependencyGroup["Dependencies"] = 1] = "Dependencies";
107454         PackageJsonDependencyGroup[PackageJsonDependencyGroup["DevDependencies"] = 2] = "DevDependencies";
107455         PackageJsonDependencyGroup[PackageJsonDependencyGroup["PeerDependencies"] = 4] = "PeerDependencies";
107456         PackageJsonDependencyGroup[PackageJsonDependencyGroup["OptionalDependencies"] = 8] = "OptionalDependencies";
107457         PackageJsonDependencyGroup[PackageJsonDependencyGroup["All"] = 15] = "All";
107458     })(PackageJsonDependencyGroup = ts.PackageJsonDependencyGroup || (ts.PackageJsonDependencyGroup = {}));
107459     /* @internal */
107460     ts.emptyOptions = {};
107461     var HighlightSpanKind;
107462     (function (HighlightSpanKind) {
107463         HighlightSpanKind["none"] = "none";
107464         HighlightSpanKind["definition"] = "definition";
107465         HighlightSpanKind["reference"] = "reference";
107466         HighlightSpanKind["writtenReference"] = "writtenReference";
107467     })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {}));
107468     var IndentStyle;
107469     (function (IndentStyle) {
107470         IndentStyle[IndentStyle["None"] = 0] = "None";
107471         IndentStyle[IndentStyle["Block"] = 1] = "Block";
107472         IndentStyle[IndentStyle["Smart"] = 2] = "Smart";
107473     })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {}));
107474     var SemicolonPreference;
107475     (function (SemicolonPreference) {
107476         SemicolonPreference["Ignore"] = "ignore";
107477         SemicolonPreference["Insert"] = "insert";
107478         SemicolonPreference["Remove"] = "remove";
107479     })(SemicolonPreference = ts.SemicolonPreference || (ts.SemicolonPreference = {}));
107480     function getDefaultFormatCodeSettings(newLineCharacter) {
107481         return {
107482             indentSize: 4,
107483             tabSize: 4,
107484             newLineCharacter: newLineCharacter || "\n",
107485             convertTabsToSpaces: true,
107486             indentStyle: IndentStyle.Smart,
107487             insertSpaceAfterConstructor: false,
107488             insertSpaceAfterCommaDelimiter: true,
107489             insertSpaceAfterSemicolonInForStatements: true,
107490             insertSpaceBeforeAndAfterBinaryOperators: true,
107491             insertSpaceAfterKeywordsInControlFlowStatements: true,
107492             insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
107493             insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
107494             insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
107495             insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
107496             insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
107497             insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
107498             insertSpaceBeforeFunctionParenthesis: false,
107499             placeOpenBraceOnNewLineForFunctions: false,
107500             placeOpenBraceOnNewLineForControlBlocks: false,
107501             semicolons: SemicolonPreference.Ignore,
107502             trimTrailingWhitespace: true
107503         };
107504     }
107505     ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings;
107506     /* @internal */
107507     ts.testFormatSettings = getDefaultFormatCodeSettings("\n");
107508     var SymbolDisplayPartKind;
107509     (function (SymbolDisplayPartKind) {
107510         SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName";
107511         SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className";
107512         SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName";
107513         SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName";
107514         SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName";
107515         SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword";
107516         SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak";
107517         SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral";
107518         SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral";
107519         SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName";
107520         SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName";
107521         SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName";
107522         SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator";
107523         SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName";
107524         SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName";
107525         SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation";
107526         SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space";
107527         SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text";
107528         SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName";
107529         SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName";
107530         SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName";
107531         SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
107532     })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {}));
107533     var OutliningSpanKind;
107534     (function (OutliningSpanKind) {
107535         /** Single or multi-line comments */
107536         OutliningSpanKind["Comment"] = "comment";
107537         /** Sections marked by '// #region' and '// #endregion' comments */
107538         OutliningSpanKind["Region"] = "region";
107539         /** Declarations and expressions */
107540         OutliningSpanKind["Code"] = "code";
107541         /** Contiguous blocks of import declarations */
107542         OutliningSpanKind["Imports"] = "imports";
107543     })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {}));
107544     var OutputFileType;
107545     (function (OutputFileType) {
107546         OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript";
107547         OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap";
107548         OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration";
107549     })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {}));
107550     var EndOfLineState;
107551     (function (EndOfLineState) {
107552         EndOfLineState[EndOfLineState["None"] = 0] = "None";
107553         EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia";
107554         EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral";
107555         EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral";
107556         EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate";
107557         EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail";
107558         EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition";
107559     })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {}));
107560     var TokenClass;
107561     (function (TokenClass) {
107562         TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation";
107563         TokenClass[TokenClass["Keyword"] = 1] = "Keyword";
107564         TokenClass[TokenClass["Operator"] = 2] = "Operator";
107565         TokenClass[TokenClass["Comment"] = 3] = "Comment";
107566         TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace";
107567         TokenClass[TokenClass["Identifier"] = 5] = "Identifier";
107568         TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral";
107569         TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral";
107570         TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral";
107571         TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral";
107572     })(TokenClass = ts.TokenClass || (ts.TokenClass = {}));
107573     var ScriptElementKind;
107574     (function (ScriptElementKind) {
107575         ScriptElementKind["unknown"] = "";
107576         ScriptElementKind["warning"] = "warning";
107577         /** predefined type (void) or keyword (class) */
107578         ScriptElementKind["keyword"] = "keyword";
107579         /** top level script node */
107580         ScriptElementKind["scriptElement"] = "script";
107581         /** module foo {} */
107582         ScriptElementKind["moduleElement"] = "module";
107583         /** class X {} */
107584         ScriptElementKind["classElement"] = "class";
107585         /** var x = class X {} */
107586         ScriptElementKind["localClassElement"] = "local class";
107587         /** interface Y {} */
107588         ScriptElementKind["interfaceElement"] = "interface";
107589         /** type T = ... */
107590         ScriptElementKind["typeElement"] = "type";
107591         /** enum E */
107592         ScriptElementKind["enumElement"] = "enum";
107593         ScriptElementKind["enumMemberElement"] = "enum member";
107594         /**
107595          * Inside module and script only
107596          * const v = ..
107597          */
107598         ScriptElementKind["variableElement"] = "var";
107599         /** Inside function */
107600         ScriptElementKind["localVariableElement"] = "local var";
107601         /**
107602          * Inside module and script only
107603          * function f() { }
107604          */
107605         ScriptElementKind["functionElement"] = "function";
107606         /** Inside function */
107607         ScriptElementKind["localFunctionElement"] = "local function";
107608         /** class X { [public|private]* foo() {} } */
107609         ScriptElementKind["memberFunctionElement"] = "method";
107610         /** class X { [public|private]* [get|set] foo:number; } */
107611         ScriptElementKind["memberGetAccessorElement"] = "getter";
107612         ScriptElementKind["memberSetAccessorElement"] = "setter";
107613         /**
107614          * class X { [public|private]* foo:number; }
107615          * interface Y { foo:number; }
107616          */
107617         ScriptElementKind["memberVariableElement"] = "property";
107618         /** class X { constructor() { } } */
107619         ScriptElementKind["constructorImplementationElement"] = "constructor";
107620         /** interface Y { ():number; } */
107621         ScriptElementKind["callSignatureElement"] = "call";
107622         /** interface Y { []:number; } */
107623         ScriptElementKind["indexSignatureElement"] = "index";
107624         /** interface Y { new():Y; } */
107625         ScriptElementKind["constructSignatureElement"] = "construct";
107626         /** function foo(*Y*: string) */
107627         ScriptElementKind["parameterElement"] = "parameter";
107628         ScriptElementKind["typeParameterElement"] = "type parameter";
107629         ScriptElementKind["primitiveType"] = "primitive type";
107630         ScriptElementKind["label"] = "label";
107631         ScriptElementKind["alias"] = "alias";
107632         ScriptElementKind["constElement"] = "const";
107633         ScriptElementKind["letElement"] = "let";
107634         ScriptElementKind["directory"] = "directory";
107635         ScriptElementKind["externalModuleName"] = "external module name";
107636         /**
107637          * <JsxTagName attribute1 attribute2={0} />
107638          */
107639         ScriptElementKind["jsxAttribute"] = "JSX attribute";
107640         /** String literal */
107641         ScriptElementKind["string"] = "string";
107642     })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
107643     var ScriptElementKindModifier;
107644     (function (ScriptElementKindModifier) {
107645         ScriptElementKindModifier["none"] = "";
107646         ScriptElementKindModifier["publicMemberModifier"] = "public";
107647         ScriptElementKindModifier["privateMemberModifier"] = "private";
107648         ScriptElementKindModifier["protectedMemberModifier"] = "protected";
107649         ScriptElementKindModifier["exportedModifier"] = "export";
107650         ScriptElementKindModifier["ambientModifier"] = "declare";
107651         ScriptElementKindModifier["staticModifier"] = "static";
107652         ScriptElementKindModifier["abstractModifier"] = "abstract";
107653         ScriptElementKindModifier["optionalModifier"] = "optional";
107654         ScriptElementKindModifier["dtsModifier"] = ".d.ts";
107655         ScriptElementKindModifier["tsModifier"] = ".ts";
107656         ScriptElementKindModifier["tsxModifier"] = ".tsx";
107657         ScriptElementKindModifier["jsModifier"] = ".js";
107658         ScriptElementKindModifier["jsxModifier"] = ".jsx";
107659         ScriptElementKindModifier["jsonModifier"] = ".json";
107660     })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {}));
107661     var ClassificationTypeNames;
107662     (function (ClassificationTypeNames) {
107663         ClassificationTypeNames["comment"] = "comment";
107664         ClassificationTypeNames["identifier"] = "identifier";
107665         ClassificationTypeNames["keyword"] = "keyword";
107666         ClassificationTypeNames["numericLiteral"] = "number";
107667         ClassificationTypeNames["bigintLiteral"] = "bigint";
107668         ClassificationTypeNames["operator"] = "operator";
107669         ClassificationTypeNames["stringLiteral"] = "string";
107670         ClassificationTypeNames["whiteSpace"] = "whitespace";
107671         ClassificationTypeNames["text"] = "text";
107672         ClassificationTypeNames["punctuation"] = "punctuation";
107673         ClassificationTypeNames["className"] = "class name";
107674         ClassificationTypeNames["enumName"] = "enum name";
107675         ClassificationTypeNames["interfaceName"] = "interface name";
107676         ClassificationTypeNames["moduleName"] = "module name";
107677         ClassificationTypeNames["typeParameterName"] = "type parameter name";
107678         ClassificationTypeNames["typeAliasName"] = "type alias name";
107679         ClassificationTypeNames["parameterName"] = "parameter name";
107680         ClassificationTypeNames["docCommentTagName"] = "doc comment tag name";
107681         ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name";
107682         ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name";
107683         ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name";
107684         ClassificationTypeNames["jsxAttribute"] = "jsx attribute";
107685         ClassificationTypeNames["jsxText"] = "jsx text";
107686         ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value";
107687     })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {}));
107688     var ClassificationType;
107689     (function (ClassificationType) {
107690         ClassificationType[ClassificationType["comment"] = 1] = "comment";
107691         ClassificationType[ClassificationType["identifier"] = 2] = "identifier";
107692         ClassificationType[ClassificationType["keyword"] = 3] = "keyword";
107693         ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral";
107694         ClassificationType[ClassificationType["operator"] = 5] = "operator";
107695         ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral";
107696         ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral";
107697         ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace";
107698         ClassificationType[ClassificationType["text"] = 9] = "text";
107699         ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation";
107700         ClassificationType[ClassificationType["className"] = 11] = "className";
107701         ClassificationType[ClassificationType["enumName"] = 12] = "enumName";
107702         ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName";
107703         ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName";
107704         ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName";
107705         ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName";
107706         ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName";
107707         ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName";
107708         ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName";
107709         ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName";
107710         ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
107711         ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute";
107712         ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText";
107713         ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue";
107714         ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral";
107715     })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {}));
107716 })(ts || (ts = {}));
107717 /* @internal */
107718 var ts;
107719 (function (ts) {
107720     // These utilities are common to multiple language service features.
107721     //#region
107722     ts.scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
107723     var SemanticMeaning;
107724     (function (SemanticMeaning) {
107725         SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
107726         SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value";
107727         SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type";
107728         SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace";
107729         SemanticMeaning[SemanticMeaning["All"] = 7] = "All";
107730     })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {}));
107731     function getMeaningFromDeclaration(node) {
107732         switch (node.kind) {
107733             case 242 /* VariableDeclaration */:
107734                 return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */;
107735             case 156 /* Parameter */:
107736             case 191 /* BindingElement */:
107737             case 159 /* PropertyDeclaration */:
107738             case 158 /* PropertySignature */:
107739             case 281 /* PropertyAssignment */:
107740             case 282 /* ShorthandPropertyAssignment */:
107741             case 161 /* MethodDeclaration */:
107742             case 160 /* MethodSignature */:
107743             case 162 /* Constructor */:
107744             case 163 /* GetAccessor */:
107745             case 164 /* SetAccessor */:
107746             case 244 /* FunctionDeclaration */:
107747             case 201 /* FunctionExpression */:
107748             case 202 /* ArrowFunction */:
107749             case 280 /* CatchClause */:
107750             case 273 /* JsxAttribute */:
107751                 return 1 /* Value */;
107752             case 155 /* TypeParameter */:
107753             case 246 /* InterfaceDeclaration */:
107754             case 247 /* TypeAliasDeclaration */:
107755             case 173 /* TypeLiteral */:
107756                 return 2 /* Type */;
107757             case 322 /* JSDocTypedefTag */:
107758                 // If it has no name node, it shares the name with the value declaration below it.
107759                 return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
107760             case 284 /* EnumMember */:
107761             case 245 /* ClassDeclaration */:
107762                 return 1 /* Value */ | 2 /* Type */;
107763             case 249 /* ModuleDeclaration */:
107764                 if (ts.isAmbientModule(node)) {
107765                     return 4 /* Namespace */ | 1 /* Value */;
107766                 }
107767                 else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) {
107768                     return 4 /* Namespace */ | 1 /* Value */;
107769                 }
107770                 else {
107771                     return 4 /* Namespace */;
107772                 }
107773             case 248 /* EnumDeclaration */:
107774             case 257 /* NamedImports */:
107775             case 258 /* ImportSpecifier */:
107776             case 253 /* ImportEqualsDeclaration */:
107777             case 254 /* ImportDeclaration */:
107778             case 259 /* ExportAssignment */:
107779             case 260 /* ExportDeclaration */:
107780                 return 7 /* All */;
107781             // An external module can be a Value
107782             case 290 /* SourceFile */:
107783                 return 4 /* Namespace */ | 1 /* Value */;
107784         }
107785         return 7 /* All */;
107786     }
107787     ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
107788     function getMeaningFromLocation(node) {
107789         node = getAdjustedReferenceLocation(node);
107790         if (node.kind === 290 /* SourceFile */) {
107791             return 1 /* Value */;
107792         }
107793         else if (node.parent.kind === 259 /* ExportAssignment */
107794             || node.parent.kind === 265 /* ExternalModuleReference */
107795             || node.parent.kind === 258 /* ImportSpecifier */
107796             || node.parent.kind === 255 /* ImportClause */
107797             || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) {
107798             return 7 /* All */;
107799         }
107800         else if (isInRightSideOfInternalImportEqualsDeclaration(node)) {
107801             return getMeaningFromRightHandSideOfImportEquals(node);
107802         }
107803         else if (ts.isDeclarationName(node)) {
107804             return getMeaningFromDeclaration(node.parent);
107805         }
107806         else if (isTypeReference(node)) {
107807             return 2 /* Type */;
107808         }
107809         else if (isNamespaceReference(node)) {
107810             return 4 /* Namespace */;
107811         }
107812         else if (ts.isTypeParameterDeclaration(node.parent)) {
107813             ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName
107814             return 2 /* Type */;
107815         }
107816         else if (ts.isLiteralTypeNode(node.parent)) {
107817             // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings.
107818             return 2 /* Type */ | 1 /* Value */;
107819         }
107820         else {
107821             return 1 /* Value */;
107822         }
107823     }
107824     ts.getMeaningFromLocation = getMeaningFromLocation;
107825     function getMeaningFromRightHandSideOfImportEquals(node) {
107826         //     import a = |b|; // Namespace
107827         //     import a = |b.c|; // Value, type, namespace
107828         //     import a = |b.c|.d; // Namespace
107829         var name = node.kind === 153 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined;
107830         return name && name.parent.kind === 253 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */;
107831     }
107832     function isInRightSideOfInternalImportEqualsDeclaration(node) {
107833         while (node.parent.kind === 153 /* QualifiedName */) {
107834             node = node.parent;
107835         }
107836         return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
107837     }
107838     ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration;
107839     function isNamespaceReference(node) {
107840         return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node);
107841     }
107842     function isQualifiedNameNamespaceReference(node) {
107843         var root = node;
107844         var isLastClause = true;
107845         if (root.parent.kind === 153 /* QualifiedName */) {
107846             while (root.parent && root.parent.kind === 153 /* QualifiedName */) {
107847                 root = root.parent;
107848             }
107849             isLastClause = root.right === node;
107850         }
107851         return root.parent.kind === 169 /* TypeReference */ && !isLastClause;
107852     }
107853     function isPropertyAccessNamespaceReference(node) {
107854         var root = node;
107855         var isLastClause = true;
107856         if (root.parent.kind === 194 /* PropertyAccessExpression */) {
107857             while (root.parent && root.parent.kind === 194 /* PropertyAccessExpression */) {
107858                 root = root.parent;
107859             }
107860             isLastClause = root.name === node;
107861         }
107862         if (!isLastClause && root.parent.kind === 216 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 279 /* HeritageClause */) {
107863             var decl = root.parent.parent.parent;
107864             return (decl.kind === 245 /* ClassDeclaration */ && root.parent.parent.token === 113 /* ImplementsKeyword */) ||
107865                 (decl.kind === 246 /* InterfaceDeclaration */ && root.parent.parent.token === 90 /* ExtendsKeyword */);
107866         }
107867         return false;
107868     }
107869     function isTypeReference(node) {
107870         if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
107871             node = node.parent;
107872         }
107873         switch (node.kind) {
107874             case 104 /* ThisKeyword */:
107875                 return !ts.isExpressionNode(node);
107876             case 183 /* ThisType */:
107877                 return true;
107878         }
107879         switch (node.parent.kind) {
107880             case 169 /* TypeReference */:
107881                 return true;
107882             case 188 /* ImportType */:
107883                 return !node.parent.isTypeOf;
107884             case 216 /* ExpressionWithTypeArguments */:
107885                 return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent);
107886         }
107887         return false;
107888     }
107889     function isCallExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
107890         if (includeElementAccess === void 0) { includeElementAccess = false; }
107891         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
107892         return isCalleeWorker(node, ts.isCallExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
107893     }
107894     ts.isCallExpressionTarget = isCallExpressionTarget;
107895     function isNewExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
107896         if (includeElementAccess === void 0) { includeElementAccess = false; }
107897         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
107898         return isCalleeWorker(node, ts.isNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
107899     }
107900     ts.isNewExpressionTarget = isNewExpressionTarget;
107901     function isCallOrNewExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
107902         if (includeElementAccess === void 0) { includeElementAccess = false; }
107903         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
107904         return isCalleeWorker(node, ts.isCallOrNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
107905     }
107906     ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget;
107907     function isTaggedTemplateTag(node, includeElementAccess, skipPastOuterExpressions) {
107908         if (includeElementAccess === void 0) { includeElementAccess = false; }
107909         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
107910         return isCalleeWorker(node, ts.isTaggedTemplateExpression, selectTagOfTaggedTemplateExpression, includeElementAccess, skipPastOuterExpressions);
107911     }
107912     ts.isTaggedTemplateTag = isTaggedTemplateTag;
107913     function isDecoratorTarget(node, includeElementAccess, skipPastOuterExpressions) {
107914         if (includeElementAccess === void 0) { includeElementAccess = false; }
107915         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
107916         return isCalleeWorker(node, ts.isDecorator, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
107917     }
107918     ts.isDecoratorTarget = isDecoratorTarget;
107919     function isJsxOpeningLikeElementTagName(node, includeElementAccess, skipPastOuterExpressions) {
107920         if (includeElementAccess === void 0) { includeElementAccess = false; }
107921         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
107922         return isCalleeWorker(node, ts.isJsxOpeningLikeElement, selectTagNameOfJsxOpeningLikeElement, includeElementAccess, skipPastOuterExpressions);
107923     }
107924     ts.isJsxOpeningLikeElementTagName = isJsxOpeningLikeElementTagName;
107925     function selectExpressionOfCallOrNewExpressionOrDecorator(node) {
107926         return node.expression;
107927     }
107928     function selectTagOfTaggedTemplateExpression(node) {
107929         return node.tag;
107930     }
107931     function selectTagNameOfJsxOpeningLikeElement(node) {
107932         return node.tagName;
107933     }
107934     function isCalleeWorker(node, pred, calleeSelector, includeElementAccess, skipPastOuterExpressions) {
107935         var target = includeElementAccess ? climbPastPropertyOrElementAccess(node) : climbPastPropertyAccess(node);
107936         if (skipPastOuterExpressions) {
107937             target = ts.skipOuterExpressions(target);
107938         }
107939         return !!target && !!target.parent && pred(target.parent) && calleeSelector(target.parent) === target;
107940     }
107941     function climbPastPropertyAccess(node) {
107942         return isRightSideOfPropertyAccess(node) ? node.parent : node;
107943     }
107944     ts.climbPastPropertyAccess = climbPastPropertyAccess;
107945     function climbPastPropertyOrElementAccess(node) {
107946         return isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node) ? node.parent : node;
107947     }
107948     ts.climbPastPropertyOrElementAccess = climbPastPropertyOrElementAccess;
107949     function getTargetLabel(referenceNode, labelName) {
107950         while (referenceNode) {
107951             if (referenceNode.kind === 238 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) {
107952                 return referenceNode.label;
107953             }
107954             referenceNode = referenceNode.parent;
107955         }
107956         return undefined;
107957     }
107958     ts.getTargetLabel = getTargetLabel;
107959     function hasPropertyAccessExpressionWithName(node, funcName) {
107960         if (!ts.isPropertyAccessExpression(node.expression)) {
107961             return false;
107962         }
107963         return node.expression.name.text === funcName;
107964     }
107965     ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName;
107966     function isJumpStatementTarget(node) {
107967         var _a;
107968         return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isBreakOrContinueStatement)) === null || _a === void 0 ? void 0 : _a.label) === node;
107969     }
107970     ts.isJumpStatementTarget = isJumpStatementTarget;
107971     function isLabelOfLabeledStatement(node) {
107972         var _a;
107973         return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isLabeledStatement)) === null || _a === void 0 ? void 0 : _a.label) === node;
107974     }
107975     ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement;
107976     function isLabelName(node) {
107977         return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
107978     }
107979     ts.isLabelName = isLabelName;
107980     function isTagName(node) {
107981         var _a;
107982         return ((_a = ts.tryCast(node.parent, ts.isJSDocTag)) === null || _a === void 0 ? void 0 : _a.tagName) === node;
107983     }
107984     ts.isTagName = isTagName;
107985     function isRightSideOfQualifiedName(node) {
107986         var _a;
107987         return ((_a = ts.tryCast(node.parent, ts.isQualifiedName)) === null || _a === void 0 ? void 0 : _a.right) === node;
107988     }
107989     ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName;
107990     function isRightSideOfPropertyAccess(node) {
107991         var _a;
107992         return ((_a = ts.tryCast(node.parent, ts.isPropertyAccessExpression)) === null || _a === void 0 ? void 0 : _a.name) === node;
107993     }
107994     ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess;
107995     function isArgumentExpressionOfElementAccess(node) {
107996         var _a;
107997         return ((_a = ts.tryCast(node.parent, ts.isElementAccessExpression)) === null || _a === void 0 ? void 0 : _a.argumentExpression) === node;
107998     }
107999     ts.isArgumentExpressionOfElementAccess = isArgumentExpressionOfElementAccess;
108000     function isNameOfModuleDeclaration(node) {
108001         var _a;
108002         return ((_a = ts.tryCast(node.parent, ts.isModuleDeclaration)) === null || _a === void 0 ? void 0 : _a.name) === node;
108003     }
108004     ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration;
108005     function isNameOfFunctionDeclaration(node) {
108006         var _a;
108007         return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isFunctionLike)) === null || _a === void 0 ? void 0 : _a.name) === node;
108008     }
108009     ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration;
108010     function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
108011         switch (node.parent.kind) {
108012             case 159 /* PropertyDeclaration */:
108013             case 158 /* PropertySignature */:
108014             case 281 /* PropertyAssignment */:
108015             case 284 /* EnumMember */:
108016             case 161 /* MethodDeclaration */:
108017             case 160 /* MethodSignature */:
108018             case 163 /* GetAccessor */:
108019             case 164 /* SetAccessor */:
108020             case 249 /* ModuleDeclaration */:
108021                 return ts.getNameOfDeclaration(node.parent) === node;
108022             case 195 /* ElementAccessExpression */:
108023                 return node.parent.argumentExpression === node;
108024             case 154 /* ComputedPropertyName */:
108025                 return true;
108026             case 187 /* LiteralType */:
108027                 return node.parent.parent.kind === 185 /* IndexedAccessType */;
108028             default:
108029                 return false;
108030         }
108031     }
108032     ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess;
108033     function isExpressionOfExternalModuleImportEqualsDeclaration(node) {
108034         return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) &&
108035             ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
108036     }
108037     ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration;
108038     function getContainerNode(node) {
108039         if (ts.isJSDocTypeAlias(node)) {
108040             // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
108041             // node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
108042             // Then we get parent again in the loop.
108043             node = node.parent.parent;
108044         }
108045         while (true) {
108046             node = node.parent;
108047             if (!node) {
108048                 return undefined;
108049             }
108050             switch (node.kind) {
108051                 case 290 /* SourceFile */:
108052                 case 161 /* MethodDeclaration */:
108053                 case 160 /* MethodSignature */:
108054                 case 244 /* FunctionDeclaration */:
108055                 case 201 /* FunctionExpression */:
108056                 case 163 /* GetAccessor */:
108057                 case 164 /* SetAccessor */:
108058                 case 245 /* ClassDeclaration */:
108059                 case 246 /* InterfaceDeclaration */:
108060                 case 248 /* EnumDeclaration */:
108061                 case 249 /* ModuleDeclaration */:
108062                     return node;
108063             }
108064         }
108065     }
108066     ts.getContainerNode = getContainerNode;
108067     function getNodeKind(node) {
108068         switch (node.kind) {
108069             case 290 /* SourceFile */:
108070                 return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
108071             case 249 /* ModuleDeclaration */:
108072                 return "module" /* moduleElement */;
108073             case 245 /* ClassDeclaration */:
108074             case 214 /* ClassExpression */:
108075                 return "class" /* classElement */;
108076             case 246 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
108077             case 247 /* TypeAliasDeclaration */:
108078             case 315 /* JSDocCallbackTag */:
108079             case 322 /* JSDocTypedefTag */:
108080                 return "type" /* typeElement */;
108081             case 248 /* EnumDeclaration */: return "enum" /* enumElement */;
108082             case 242 /* VariableDeclaration */:
108083                 return getKindOfVariableDeclaration(node);
108084             case 191 /* BindingElement */:
108085                 return getKindOfVariableDeclaration(ts.getRootDeclaration(node));
108086             case 202 /* ArrowFunction */:
108087             case 244 /* FunctionDeclaration */:
108088             case 201 /* FunctionExpression */:
108089                 return "function" /* functionElement */;
108090             case 163 /* GetAccessor */: return "getter" /* memberGetAccessorElement */;
108091             case 164 /* SetAccessor */: return "setter" /* memberSetAccessorElement */;
108092             case 161 /* MethodDeclaration */:
108093             case 160 /* MethodSignature */:
108094                 return "method" /* memberFunctionElement */;
108095             case 281 /* PropertyAssignment */:
108096                 var initializer = node.initializer;
108097                 return ts.isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
108098             case 159 /* PropertyDeclaration */:
108099             case 158 /* PropertySignature */:
108100             case 282 /* ShorthandPropertyAssignment */:
108101             case 283 /* SpreadAssignment */:
108102                 return "property" /* memberVariableElement */;
108103             case 167 /* IndexSignature */: return "index" /* indexSignatureElement */;
108104             case 166 /* ConstructSignature */: return "construct" /* constructSignatureElement */;
108105             case 165 /* CallSignature */: return "call" /* callSignatureElement */;
108106             case 162 /* Constructor */: return "constructor" /* constructorImplementationElement */;
108107             case 155 /* TypeParameter */: return "type parameter" /* typeParameterElement */;
108108             case 284 /* EnumMember */: return "enum member" /* enumMemberElement */;
108109             case 156 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */;
108110             case 253 /* ImportEqualsDeclaration */:
108111             case 258 /* ImportSpecifier */:
108112             case 263 /* ExportSpecifier */:
108113             case 256 /* NamespaceImport */:
108114             case 262 /* NamespaceExport */:
108115                 return "alias" /* alias */;
108116             case 209 /* BinaryExpression */:
108117                 var kind = ts.getAssignmentDeclarationKind(node);
108118                 var right = node.right;
108119                 switch (kind) {
108120                     case 7 /* ObjectDefinePropertyValue */:
108121                     case 8 /* ObjectDefinePropertyExports */:
108122                     case 9 /* ObjectDefinePrototypeProperty */:
108123                     case 0 /* None */:
108124                         return "" /* unknown */;
108125                     case 1 /* ExportsProperty */:
108126                     case 2 /* ModuleExports */:
108127                         var rightKind = getNodeKind(right);
108128                         return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind;
108129                     case 3 /* PrototypeProperty */:
108130                         return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
108131                     case 4 /* ThisProperty */:
108132                         return "property" /* memberVariableElement */; // property
108133                     case 5 /* Property */:
108134                         // static method / property
108135                         return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
108136                     case 6 /* Prototype */:
108137                         return "local class" /* localClassElement */;
108138                     default: {
108139                         ts.assertType(kind);
108140                         return "" /* unknown */;
108141                     }
108142                 }
108143             case 75 /* Identifier */:
108144                 return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */;
108145             case 259 /* ExportAssignment */:
108146                 var scriptKind = getNodeKind(node.expression);
108147                 // If the expression didn't come back with something (like it does for an identifiers)
108148                 return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind;
108149             default:
108150                 return "" /* unknown */;
108151         }
108152         function getKindOfVariableDeclaration(v) {
108153             return ts.isVarConst(v)
108154                 ? "const" /* constElement */
108155                 : ts.isLet(v)
108156                     ? "let" /* letElement */
108157                     : "var" /* variableElement */;
108158         }
108159     }
108160     ts.getNodeKind = getNodeKind;
108161     function isThis(node) {
108162         switch (node.kind) {
108163             case 104 /* ThisKeyword */:
108164                 // case SyntaxKind.ThisType: TODO: GH#9267
108165                 return true;
108166             case 75 /* Identifier */:
108167                 // 'this' as a parameter
108168                 return ts.identifierIsThisKeyword(node) && node.parent.kind === 156 /* Parameter */;
108169             default:
108170                 return false;
108171         }
108172     }
108173     ts.isThis = isThis;
108174     // Matches the beginning of a triple slash directive
108175     var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
108176     function getLineStartPositionForPosition(position, sourceFile) {
108177         var lineStarts = ts.getLineStarts(sourceFile);
108178         var line = sourceFile.getLineAndCharacterOfPosition(position).line;
108179         return lineStarts[line];
108180     }
108181     ts.getLineStartPositionForPosition = getLineStartPositionForPosition;
108182     function rangeContainsRange(r1, r2) {
108183         return startEndContainsRange(r1.pos, r1.end, r2);
108184     }
108185     ts.rangeContainsRange = rangeContainsRange;
108186     function rangeContainsRangeExclusive(r1, r2) {
108187         return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end);
108188     }
108189     ts.rangeContainsRangeExclusive = rangeContainsRangeExclusive;
108190     function rangeContainsPosition(r, pos) {
108191         return r.pos <= pos && pos <= r.end;
108192     }
108193     ts.rangeContainsPosition = rangeContainsPosition;
108194     function rangeContainsPositionExclusive(r, pos) {
108195         return r.pos < pos && pos < r.end;
108196     }
108197     ts.rangeContainsPositionExclusive = rangeContainsPositionExclusive;
108198     function startEndContainsRange(start, end, range) {
108199         return start <= range.pos && end >= range.end;
108200     }
108201     ts.startEndContainsRange = startEndContainsRange;
108202     function rangeContainsStartEnd(range, start, end) {
108203         return range.pos <= start && range.end >= end;
108204     }
108205     ts.rangeContainsStartEnd = rangeContainsStartEnd;
108206     function rangeOverlapsWithStartEnd(r1, start, end) {
108207         return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end);
108208     }
108209     ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd;
108210     function nodeOverlapsWithStartEnd(node, sourceFile, start, end) {
108211         return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end);
108212     }
108213     ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd;
108214     function startEndOverlapsWithStartEnd(start1, end1, start2, end2) {
108215         var start = Math.max(start1, start2);
108216         var end = Math.min(end1, end2);
108217         return start < end;
108218     }
108219     ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd;
108220     /**
108221      * Assumes `candidate.start <= position` holds.
108222      */
108223     function positionBelongsToNode(candidate, position, sourceFile) {
108224         ts.Debug.assert(candidate.pos <= position);
108225         return position < candidate.end || !isCompletedNode(candidate, sourceFile);
108226     }
108227     ts.positionBelongsToNode = positionBelongsToNode;
108228     function isCompletedNode(n, sourceFile) {
108229         if (n === undefined || ts.nodeIsMissing(n)) {
108230             return false;
108231         }
108232         switch (n.kind) {
108233             case 245 /* ClassDeclaration */:
108234             case 246 /* InterfaceDeclaration */:
108235             case 248 /* EnumDeclaration */:
108236             case 193 /* ObjectLiteralExpression */:
108237             case 189 /* ObjectBindingPattern */:
108238             case 173 /* TypeLiteral */:
108239             case 223 /* Block */:
108240             case 250 /* ModuleBlock */:
108241             case 251 /* CaseBlock */:
108242             case 257 /* NamedImports */:
108243             case 261 /* NamedExports */:
108244                 return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile);
108245             case 280 /* CatchClause */:
108246                 return isCompletedNode(n.block, sourceFile);
108247             case 197 /* NewExpression */:
108248                 if (!n.arguments) {
108249                     return true;
108250                 }
108251             // falls through
108252             case 196 /* CallExpression */:
108253             case 200 /* ParenthesizedExpression */:
108254             case 182 /* ParenthesizedType */:
108255                 return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile);
108256             case 170 /* FunctionType */:
108257             case 171 /* ConstructorType */:
108258                 return isCompletedNode(n.type, sourceFile);
108259             case 162 /* Constructor */:
108260             case 163 /* GetAccessor */:
108261             case 164 /* SetAccessor */:
108262             case 244 /* FunctionDeclaration */:
108263             case 201 /* FunctionExpression */:
108264             case 161 /* MethodDeclaration */:
108265             case 160 /* MethodSignature */:
108266             case 166 /* ConstructSignature */:
108267             case 165 /* CallSignature */:
108268             case 202 /* ArrowFunction */:
108269                 if (n.body) {
108270                     return isCompletedNode(n.body, sourceFile);
108271                 }
108272                 if (n.type) {
108273                     return isCompletedNode(n.type, sourceFile);
108274                 }
108275                 // Even though type parameters can be unclosed, we can get away with
108276                 // having at least a closing paren.
108277                 return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile);
108278             case 249 /* ModuleDeclaration */:
108279                 return !!n.body && isCompletedNode(n.body, sourceFile);
108280             case 227 /* IfStatement */:
108281                 if (n.elseStatement) {
108282                     return isCompletedNode(n.elseStatement, sourceFile);
108283                 }
108284                 return isCompletedNode(n.thenStatement, sourceFile);
108285             case 226 /* ExpressionStatement */:
108286                 return isCompletedNode(n.expression, sourceFile) ||
108287                     hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile);
108288             case 192 /* ArrayLiteralExpression */:
108289             case 190 /* ArrayBindingPattern */:
108290             case 195 /* ElementAccessExpression */:
108291             case 154 /* ComputedPropertyName */:
108292             case 175 /* TupleType */:
108293                 return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile);
108294             case 167 /* IndexSignature */:
108295                 if (n.type) {
108296                     return isCompletedNode(n.type, sourceFile);
108297                 }
108298                 return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile);
108299             case 277 /* CaseClause */:
108300             case 278 /* DefaultClause */:
108301                 // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed
108302                 return false;
108303             case 230 /* ForStatement */:
108304             case 231 /* ForInStatement */:
108305             case 232 /* ForOfStatement */:
108306             case 229 /* WhileStatement */:
108307                 return isCompletedNode(n.statement, sourceFile);
108308             case 228 /* DoStatement */:
108309                 // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
108310                 return hasChildOfKind(n, 111 /* WhileKeyword */, sourceFile)
108311                     ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile)
108312                     : isCompletedNode(n.statement, sourceFile);
108313             case 172 /* TypeQuery */:
108314                 return isCompletedNode(n.exprName, sourceFile);
108315             case 204 /* TypeOfExpression */:
108316             case 203 /* DeleteExpression */:
108317             case 205 /* VoidExpression */:
108318             case 212 /* YieldExpression */:
108319             case 213 /* SpreadElement */:
108320                 var unaryWordExpression = n;
108321                 return isCompletedNode(unaryWordExpression.expression, sourceFile);
108322             case 198 /* TaggedTemplateExpression */:
108323                 return isCompletedNode(n.template, sourceFile);
108324             case 211 /* TemplateExpression */:
108325                 var lastSpan = ts.lastOrUndefined(n.templateSpans);
108326                 return isCompletedNode(lastSpan, sourceFile);
108327             case 221 /* TemplateSpan */:
108328                 return ts.nodeIsPresent(n.literal);
108329             case 260 /* ExportDeclaration */:
108330             case 254 /* ImportDeclaration */:
108331                 return ts.nodeIsPresent(n.moduleSpecifier);
108332             case 207 /* PrefixUnaryExpression */:
108333                 return isCompletedNode(n.operand, sourceFile);
108334             case 209 /* BinaryExpression */:
108335                 return isCompletedNode(n.right, sourceFile);
108336             case 210 /* ConditionalExpression */:
108337                 return isCompletedNode(n.whenFalse, sourceFile);
108338             default:
108339                 return true;
108340         }
108341     }
108342     /*
108343      * Checks if node ends with 'expectedLastToken'.
108344      * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'.
108345      */
108346     function nodeEndsWith(n, expectedLastToken, sourceFile) {
108347         var children = n.getChildren(sourceFile);
108348         if (children.length) {
108349             var lastChild = ts.last(children);
108350             if (lastChild.kind === expectedLastToken) {
108351                 return true;
108352             }
108353             else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) {
108354                 return children[children.length - 2].kind === expectedLastToken;
108355             }
108356         }
108357         return false;
108358     }
108359     function findListItemInfo(node) {
108360         var list = findContainingList(node);
108361         // It is possible at this point for syntaxList to be undefined, either if
108362         // node.parent had no list child, or if none of its list children contained
108363         // the span of node. If this happens, return undefined. The caller should
108364         // handle this case.
108365         if (!list) {
108366             return undefined;
108367         }
108368         var children = list.getChildren();
108369         var listItemIndex = ts.indexOfNode(children, node);
108370         return {
108371             listItemIndex: listItemIndex,
108372             list: list
108373         };
108374     }
108375     ts.findListItemInfo = findListItemInfo;
108376     function hasChildOfKind(n, kind, sourceFile) {
108377         return !!findChildOfKind(n, kind, sourceFile);
108378     }
108379     ts.hasChildOfKind = hasChildOfKind;
108380     function findChildOfKind(n, kind, sourceFile) {
108381         return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; });
108382     }
108383     ts.findChildOfKind = findChildOfKind;
108384     function findContainingList(node) {
108385         // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will
108386         // be parented by the container of the SyntaxList, not the SyntaxList itself.
108387         // In order to find the list item index, we first need to locate SyntaxList itself and then search
108388         // for the position of the relevant node (or comma).
108389         var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); });
108390         // Either we didn't find an appropriate list, or the list must contain us.
108391         ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
108392         return syntaxList;
108393     }
108394     ts.findContainingList = findContainingList;
108395     function isDefaultModifier(node) {
108396         return node.kind === 84 /* DefaultKeyword */;
108397     }
108398     function isClassKeyword(node) {
108399         return node.kind === 80 /* ClassKeyword */;
108400     }
108401     function isFunctionKeyword(node) {
108402         return node.kind === 94 /* FunctionKeyword */;
108403     }
108404     function getAdjustedLocationForClass(node) {
108405         if (ts.isNamedDeclaration(node)) {
108406             return node.name;
108407         }
108408         if (ts.isClassDeclaration(node)) {
108409             // for class and function declarations, use the `default` modifier
108410             // when the declaration is unnamed.
108411             var defaultModifier = ts.find(node.modifiers, isDefaultModifier);
108412             if (defaultModifier)
108413                 return defaultModifier;
108414         }
108415         if (ts.isClassExpression(node)) {
108416             // for class expressions, use the `class` keyword when the class is unnamed
108417             var classKeyword = ts.find(node.getChildren(), isClassKeyword);
108418             if (classKeyword)
108419                 return classKeyword;
108420         }
108421     }
108422     function getAdjustedLocationForFunction(node) {
108423         if (ts.isNamedDeclaration(node)) {
108424             return node.name;
108425         }
108426         if (ts.isFunctionDeclaration(node)) {
108427             // for class and function declarations, use the `default` modifier
108428             // when the declaration is unnamed.
108429             var defaultModifier = ts.find(node.modifiers, isDefaultModifier);
108430             if (defaultModifier)
108431                 return defaultModifier;
108432         }
108433         if (ts.isFunctionExpression(node)) {
108434             // for function expressions, use the `function` keyword when the function is unnamed
108435             var functionKeyword = ts.find(node.getChildren(), isFunctionKeyword);
108436             if (functionKeyword)
108437                 return functionKeyword;
108438         }
108439     }
108440     function getAdjustedLocationForDeclaration(node, forRename) {
108441         if (!forRename) {
108442             switch (node.kind) {
108443                 case 245 /* ClassDeclaration */:
108444                 case 214 /* ClassExpression */:
108445                     return getAdjustedLocationForClass(node);
108446                 case 244 /* FunctionDeclaration */:
108447                 case 201 /* FunctionExpression */:
108448                     return getAdjustedLocationForFunction(node);
108449             }
108450         }
108451         if (ts.isNamedDeclaration(node)) {
108452             return node.name;
108453         }
108454     }
108455     function getAdjustedLocationForImportDeclaration(node, forRename) {
108456         if (node.importClause) {
108457             if (node.importClause.name && node.importClause.namedBindings) {
108458                 // do not adjust if we have both a name and named bindings
108459                 return;
108460             }
108461             // /**/import [|name|] from ...;
108462             // import /**/type [|name|] from ...;
108463             if (node.importClause.name) {
108464                 return node.importClause.name;
108465             }
108466             // /**/import { [|name|] } from ...;
108467             // /**/import { propertyName as [|name|] } from ...;
108468             // /**/import * as [|name|] from ...;
108469             // import /**/type { [|name|] } from ...;
108470             // import /**/type { propertyName as [|name|] } from ...;
108471             // import /**/type * as [|name|] from ...;
108472             if (node.importClause.namedBindings) {
108473                 if (ts.isNamedImports(node.importClause.namedBindings)) {
108474                     // do nothing if there is more than one binding
108475                     var onlyBinding = ts.singleOrUndefined(node.importClause.namedBindings.elements);
108476                     if (!onlyBinding) {
108477                         return;
108478                     }
108479                     return onlyBinding.name;
108480                 }
108481                 else if (ts.isNamespaceImport(node.importClause.namedBindings)) {
108482                     return node.importClause.namedBindings.name;
108483                 }
108484             }
108485         }
108486         if (!forRename) {
108487             // /**/import "[|module|]";
108488             // /**/import ... from "[|module|]";
108489             // import /**/type ... from "[|module|]";
108490             return node.moduleSpecifier;
108491         }
108492     }
108493     function getAdjustedLocationForExportDeclaration(node, forRename) {
108494         if (node.exportClause) {
108495             // /**/export { [|name|] } ...
108496             // /**/export { propertyName as [|name|] } ...
108497             // /**/export * as [|name|] ...
108498             // export /**/type { [|name|] } from ...
108499             // export /**/type { propertyName as [|name|] } from ...
108500             // export /**/type * as [|name|] ...
108501             if (ts.isNamedExports(node.exportClause)) {
108502                 // do nothing if there is more than one binding
108503                 var onlyBinding = ts.singleOrUndefined(node.exportClause.elements);
108504                 if (!onlyBinding) {
108505                     return;
108506                 }
108507                 return node.exportClause.elements[0].name;
108508             }
108509             else if (ts.isNamespaceExport(node.exportClause)) {
108510                 return node.exportClause.name;
108511             }
108512         }
108513         if (!forRename) {
108514             // /**/export * from "[|module|]";
108515             // export /**/type * from "[|module|]";
108516             return node.moduleSpecifier;
108517         }
108518     }
108519     function getAdjustedLocationForHeritageClause(node) {
108520         // /**/extends [|name|]
108521         // /**/implements [|name|]
108522         if (node.types.length === 1) {
108523             return node.types[0].expression;
108524         }
108525         // /**/extends name1, name2 ...
108526         // /**/implements name1, name2 ...
108527     }
108528     function getAdjustedLocation(node, forRename) {
108529         var parent = node.parent;
108530         // /**/<modifier> [|name|] ...
108531         // /**/<modifier> <class|interface|type|enum|module|namespace|function|get|set> [|name|] ...
108532         // /**/<class|interface|type|enum|module|namespace|function|get|set> [|name|] ...
108533         // /**/import [|name|] = ...
108534         //
108535         // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled
108536         // specially by `getSymbolAtLocation`.
108537         if (ts.isModifier(node) && (forRename || node.kind !== 84 /* DefaultKeyword */) ? ts.contains(parent.modifiers, node) :
108538             node.kind === 80 /* ClassKeyword */ ? ts.isClassDeclaration(parent) || ts.isClassExpression(node) :
108539                 node.kind === 94 /* FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) :
108540                     node.kind === 114 /* InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) :
108541                         node.kind === 88 /* EnumKeyword */ ? ts.isEnumDeclaration(parent) :
108542                             node.kind === 145 /* TypeKeyword */ ? ts.isTypeAliasDeclaration(parent) :
108543                                 node.kind === 136 /* NamespaceKeyword */ || node.kind === 135 /* ModuleKeyword */ ? ts.isModuleDeclaration(parent) :
108544                                     node.kind === 96 /* ImportKeyword */ ? ts.isImportEqualsDeclaration(parent) :
108545                                         node.kind === 131 /* GetKeyword */ ? ts.isGetAccessorDeclaration(parent) :
108546                                             node.kind === 142 /* SetKeyword */ && ts.isSetAccessorDeclaration(parent)) {
108547             var location = getAdjustedLocationForDeclaration(parent, forRename);
108548             if (location) {
108549                 return location;
108550             }
108551         }
108552         // /**/<var|let|const> [|name|] ...
108553         if ((node.kind === 109 /* VarKeyword */ || node.kind === 81 /* ConstKeyword */ || node.kind === 115 /* LetKeyword */) &&
108554             ts.isVariableDeclarationList(parent) && parent.declarations.length === 1) {
108555             var decl = parent.declarations[0];
108556             if (ts.isIdentifier(decl.name)) {
108557                 return decl.name;
108558             }
108559         }
108560         if (node.kind === 145 /* TypeKeyword */) {
108561             // import /**/type [|name|] from ...;
108562             // import /**/type { [|name|] } from ...;
108563             // import /**/type { propertyName as [|name|] } from ...;
108564             // import /**/type ... from "[|module|]";
108565             if (ts.isImportClause(parent) && parent.isTypeOnly) {
108566                 var location = getAdjustedLocationForImportDeclaration(parent.parent, forRename);
108567                 if (location) {
108568                     return location;
108569                 }
108570             }
108571             // export /**/type { [|name|] } from ...;
108572             // export /**/type { propertyName as [|name|] } from ...;
108573             // export /**/type * from "[|module|]";
108574             // export /**/type * as ... from "[|module|]";
108575             if (ts.isExportDeclaration(parent) && parent.isTypeOnly) {
108576                 var location = getAdjustedLocationForExportDeclaration(parent, forRename);
108577                 if (location) {
108578                     return location;
108579                 }
108580             }
108581         }
108582         // import { propertyName /**/as [|name|] } ...
108583         // import * /**/as [|name|] ...
108584         // export { propertyName /**/as [|name|] } ...
108585         // export * /**/as [|name|] ...
108586         if (node.kind === 123 /* AsKeyword */) {
108587             if (ts.isImportSpecifier(parent) && parent.propertyName ||
108588                 ts.isExportSpecifier(parent) && parent.propertyName ||
108589                 ts.isNamespaceImport(parent) ||
108590                 ts.isNamespaceExport(parent)) {
108591                 return parent.name;
108592             }
108593             if (ts.isExportDeclaration(parent) && parent.exportClause && ts.isNamespaceExport(parent.exportClause)) {
108594                 return parent.exportClause.name;
108595             }
108596         }
108597         // /**/import [|name|] from ...;
108598         // /**/import { [|name|] } from ...;
108599         // /**/import { propertyName as [|name|] } from ...;
108600         // /**/import ... from "[|module|]";
108601         // /**/import "[|module|]";
108602         if (node.kind === 96 /* ImportKeyword */ && ts.isImportDeclaration(parent)) {
108603             var location = getAdjustedLocationForImportDeclaration(parent, forRename);
108604             if (location) {
108605                 return location;
108606             }
108607         }
108608         if (node.kind === 89 /* ExportKeyword */) {
108609             // /**/export { [|name|] } ...;
108610             // /**/export { propertyName as [|name|] } ...;
108611             // /**/export * from "[|module|]";
108612             // /**/export * as ... from "[|module|]";
108613             if (ts.isExportDeclaration(parent)) {
108614                 var location = getAdjustedLocationForExportDeclaration(parent, forRename);
108615                 if (location) {
108616                     return location;
108617                 }
108618             }
108619             // NOTE: We don't adjust the location of the `default` keyword as that is handled specially by `getSymbolAtLocation`.
108620             // /**/export default [|name|];
108621             // /**/export = [|name|];
108622             if (ts.isExportAssignment(parent)) {
108623                 return ts.skipOuterExpressions(parent.expression);
108624             }
108625         }
108626         // import name = /**/require("[|module|]");
108627         if (node.kind === 139 /* RequireKeyword */ && ts.isExternalModuleReference(parent)) {
108628             return parent.expression;
108629         }
108630         // import ... /**/from "[|module|]";
108631         // export ... /**/from "[|module|]";
108632         if (node.kind === 149 /* FromKeyword */ && (ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) && parent.moduleSpecifier) {
108633             return parent.moduleSpecifier;
108634         }
108635         // class ... /**/extends [|name|] ...
108636         // class ... /**/implements [|name|] ...
108637         // class ... /**/implements name1, name2 ...
108638         // interface ... /**/extends [|name|] ...
108639         // interface ... /**/extends name1, name2 ...
108640         if ((node.kind === 90 /* ExtendsKeyword */ || node.kind === 113 /* ImplementsKeyword */) && ts.isHeritageClause(parent) && parent.token === node.kind) {
108641             var location = getAdjustedLocationForHeritageClause(parent);
108642             if (location) {
108643                 return location;
108644             }
108645         }
108646         if (node.kind === 90 /* ExtendsKeyword */) {
108647             // ... <T /**/extends [|U|]> ...
108648             if (ts.isTypeParameterDeclaration(parent) && parent.constraint && ts.isTypeReferenceNode(parent.constraint)) {
108649                 return parent.constraint.typeName;
108650             }
108651             // ... T /**/extends [|U|] ? ...
108652             if (ts.isConditionalTypeNode(parent) && ts.isTypeReferenceNode(parent.extendsType)) {
108653                 return parent.extendsType.typeName;
108654             }
108655         }
108656         // ... T extends /**/infer [|U|] ? ...
108657         if (node.kind === 132 /* InferKeyword */ && ts.isInferTypeNode(parent)) {
108658             return parent.typeParameter.name;
108659         }
108660         // { [ [|K|] /**/in keyof T]: ... }
108661         if (node.kind === 97 /* InKeyword */ && ts.isTypeParameterDeclaration(parent) && ts.isMappedTypeNode(parent.parent)) {
108662             return parent.name;
108663         }
108664         // /**/keyof [|T|]
108665         if (node.kind === 134 /* KeyOfKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 134 /* KeyOfKeyword */ &&
108666             ts.isTypeReferenceNode(parent.type)) {
108667             return parent.type.typeName;
108668         }
108669         // /**/readonly [|name|][]
108670         if (node.kind === 138 /* ReadonlyKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 138 /* ReadonlyKeyword */ &&
108671             ts.isArrayTypeNode(parent.type) && ts.isTypeReferenceNode(parent.type.elementType)) {
108672             return parent.type.elementType.typeName;
108673         }
108674         if (!forRename) {
108675             // /**/new [|name|]
108676             // /**/void [|name|]
108677             // /**/void obj.[|name|]
108678             // /**/typeof [|name|]
108679             // /**/typeof obj.[|name|]
108680             // /**/await [|name|]
108681             // /**/await obj.[|name|]
108682             // /**/yield [|name|]
108683             // /**/yield obj.[|name|]
108684             // /**/delete obj.[|name|]
108685             if (node.kind === 99 /* NewKeyword */ && ts.isNewExpression(parent) ||
108686                 node.kind === 110 /* VoidKeyword */ && ts.isVoidExpression(parent) ||
108687                 node.kind === 108 /* TypeOfKeyword */ && ts.isTypeOfExpression(parent) ||
108688                 node.kind === 127 /* AwaitKeyword */ && ts.isAwaitExpression(parent) ||
108689                 node.kind === 121 /* YieldKeyword */ && ts.isYieldExpression(parent) ||
108690                 node.kind === 85 /* DeleteKeyword */ && ts.isDeleteExpression(parent)) {
108691                 if (parent.expression) {
108692                     return ts.skipOuterExpressions(parent.expression);
108693                 }
108694             }
108695             // left /**/in [|name|]
108696             // left /**/instanceof [|name|]
108697             if ((node.kind === 97 /* InKeyword */ || node.kind === 98 /* InstanceOfKeyword */) && ts.isBinaryExpression(parent) && parent.operatorToken === node) {
108698                 return ts.skipOuterExpressions(parent.right);
108699             }
108700             // left /**/as [|name|]
108701             if (node.kind === 123 /* AsKeyword */ && ts.isAsExpression(parent) && ts.isTypeReferenceNode(parent.type)) {
108702                 return parent.type.typeName;
108703             }
108704             // for (... /**/in [|name|])
108705             // for (... /**/of [|name|])
108706             if (node.kind === 97 /* InKeyword */ && ts.isForInStatement(parent) ||
108707                 node.kind === 152 /* OfKeyword */ && ts.isForOfStatement(parent)) {
108708                 return ts.skipOuterExpressions(parent.expression);
108709             }
108710         }
108711         return node;
108712     }
108713     /**
108714      * Adjusts the location used for "find references" and "go to definition" when the cursor was not
108715      * on a property name.
108716      */
108717     function getAdjustedReferenceLocation(node) {
108718         return getAdjustedLocation(node, /*forRename*/ false);
108719     }
108720     ts.getAdjustedReferenceLocation = getAdjustedReferenceLocation;
108721     /**
108722      * Adjusts the location used for "rename" when the cursor was not on a property name.
108723      */
108724     function getAdjustedRenameLocation(node) {
108725         return getAdjustedLocation(node, /*forRename*/ true);
108726     }
108727     ts.getAdjustedRenameLocation = getAdjustedRenameLocation;
108728     /**
108729      * Gets the token whose text has range [start, end) and
108730      * position >= start and (position < end or (position === end && token is literal or keyword or identifier))
108731      */
108732     function getTouchingPropertyName(sourceFile, position) {
108733         return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind) || ts.isPrivateIdentifier(n); });
108734     }
108735     ts.getTouchingPropertyName = getTouchingPropertyName;
108736     /**
108737      * Returns the token if position is in [start, end).
108738      * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true
108739      */
108740     function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) {
108741         return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false);
108742     }
108743     ts.getTouchingToken = getTouchingToken;
108744     /** Returns a token if position is in [start-of-leading-trivia, end) */
108745     function getTokenAtPosition(sourceFile, position) {
108746         return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false);
108747     }
108748     ts.getTokenAtPosition = getTokenAtPosition;
108749     /** Get the token whose text contains the position */
108750     function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) {
108751         var current = sourceFile;
108752         outer: while (true) {
108753             // find the child that contains 'position'
108754             for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) {
108755                 var child = _a[_i];
108756                 var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true);
108757                 if (start > position) {
108758                     // If this child begins after position, then all subsequent children will as well.
108759                     break;
108760                 }
108761                 var end = child.getEnd();
108762                 if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) {
108763                     current = child;
108764                     continue outer;
108765                 }
108766                 else if (includePrecedingTokenAtEndPosition && end === position) {
108767                     var previousToken = findPrecedingToken(position, sourceFile, child);
108768                     if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) {
108769                         return previousToken;
108770                     }
108771                 }
108772             }
108773             return current;
108774         }
108775     }
108776     /**
108777      * The token on the left of the position is the token that strictly includes the position
108778      * or sits to the left of the cursor if it is on a boundary. For example
108779      *
108780      *   fo|o               -> will return foo
108781      *   foo <comment> |bar -> will return foo
108782      *
108783      */
108784     function findTokenOnLeftOfPosition(file, position) {
108785         // Ideally, getTokenAtPosition should return a token. However, it is currently
108786         // broken, so we do a check to make sure the result was indeed a token.
108787         var tokenAtPosition = getTokenAtPosition(file, position);
108788         if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
108789             return tokenAtPosition;
108790         }
108791         return findPrecedingToken(position, file);
108792     }
108793     ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition;
108794     function findNextToken(previousToken, parent, sourceFile) {
108795         return find(parent);
108796         function find(n) {
108797             if (ts.isToken(n) && n.pos === previousToken.end) {
108798                 // this is token that starts at the end of previous token - return it
108799                 return n;
108800             }
108801             return ts.firstDefined(n.getChildren(sourceFile), function (child) {
108802                 var shouldDiveInChildNode = 
108803                 // previous token is enclosed somewhere in the child
108804                 (child.pos <= previousToken.pos && child.end > previousToken.end) ||
108805                     // previous token ends exactly at the beginning of child
108806                     (child.pos === previousToken.end);
108807                 return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined;
108808             });
108809         }
108810     }
108811     ts.findNextToken = findNextToken;
108812     /**
108813      * Finds the rightmost token satisfying `token.end <= position`,
108814      * excluding `JsxText` tokens containing only whitespace.
108815      */
108816     function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) {
108817         var result = find(startNode || sourceFile);
108818         ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result)));
108819         return result;
108820         function find(n) {
108821             if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) {
108822                 return n;
108823             }
108824             var children = n.getChildren(sourceFile);
108825             for (var i = 0; i < children.length; i++) {
108826                 var child = children[i];
108827                 // Note that the span of a node's tokens is [node.getStart(...), node.end).
108828                 // Given that `position < child.end` and child has constituent tokens, we distinguish these cases:
108829                 // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`):
108830                 // we need to find the last token in a previous child.
108831                 // 2) `position` is within the same span: we recurse on `child`.
108832                 if (position < child.end) {
108833                     var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc);
108834                     var lookInPreviousChild = (start >= position) || // cursor in the leading trivia
108835                         !nodeHasTokens(child, sourceFile) ||
108836                         isWhiteSpaceOnlyJsxText(child);
108837                     if (lookInPreviousChild) {
108838                         // actual start of the node is past the position - previous token should be at the end of previous child
108839                         var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
108840                         return candidate_1 && findRightmostToken(candidate_1, sourceFile);
108841                     }
108842                     else {
108843                         // candidate should be in this node
108844                         return find(child);
108845                     }
108846                 }
108847             }
108848             ts.Debug.assert(startNode !== undefined || n.kind === 290 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
108849             // Here we know that none of child token nodes embrace the position,
108850             // the only known case is when position is at the end of the file.
108851             // Try to find the rightmost token in the file without filtering.
108852             // Namely we are skipping the check: 'position < node.end'
108853             var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
108854             return candidate && findRightmostToken(candidate, sourceFile);
108855         }
108856     }
108857     ts.findPrecedingToken = findPrecedingToken;
108858     function isNonWhitespaceToken(n) {
108859         return ts.isToken(n) && !isWhiteSpaceOnlyJsxText(n);
108860     }
108861     function findRightmostToken(n, sourceFile) {
108862         if (isNonWhitespaceToken(n)) {
108863             return n;
108864         }
108865         var children = n.getChildren(sourceFile);
108866         var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
108867         return candidate && findRightmostToken(candidate, sourceFile);
108868     }
108869     /**
108870      * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens.
108871      */
108872     function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) {
108873         for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
108874             var child = children[i];
108875             if (isWhiteSpaceOnlyJsxText(child)) {
108876                 ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
108877             }
108878             else if (nodeHasTokens(children[i], sourceFile)) {
108879                 return children[i];
108880             }
108881         }
108882     }
108883     function isInString(sourceFile, position, previousToken) {
108884         if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); }
108885         if (previousToken && ts.isStringTextContainingNode(previousToken)) {
108886             var start = previousToken.getStart(sourceFile);
108887             var end = previousToken.getEnd();
108888             // To be "in" one of these literals, the position has to be:
108889             //   1. entirely within the token text.
108890             //   2. at the end position of an unterminated token.
108891             //   3. at the end of a regular expression (due to trailing flags like '/foo/g').
108892             if (start < position && position < end) {
108893                 return true;
108894             }
108895             if (position === end) {
108896                 return !!previousToken.isUnterminated;
108897             }
108898         }
108899         return false;
108900     }
108901     ts.isInString = isInString;
108902     /**
108903      * returns true if the position is in between the open and close elements of an JSX expression.
108904      */
108905     function isInsideJsxElementOrAttribute(sourceFile, position) {
108906         var token = getTokenAtPosition(sourceFile, position);
108907         if (!token) {
108908             return false;
108909         }
108910         if (token.kind === 11 /* JsxText */) {
108911             return true;
108912         }
108913         // <div>Hello |</div>
108914         if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) {
108915             return true;
108916         }
108917         // <div> { | </div> or <div a={| </div>
108918         if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 276 /* JsxExpression */) {
108919             return true;
108920         }
108921         // <div> {
108922         // |
108923         // } < /div>
108924         if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 276 /* JsxExpression */) {
108925             return true;
108926         }
108927         // <div>|</div>
108928         if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 269 /* JsxClosingElement */) {
108929             return true;
108930         }
108931         return false;
108932     }
108933     ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
108934     function isWhiteSpaceOnlyJsxText(node) {
108935         return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
108936     }
108937     function isInTemplateString(sourceFile, position) {
108938         var token = getTokenAtPosition(sourceFile, position);
108939         return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
108940     }
108941     ts.isInTemplateString = isInTemplateString;
108942     function isInJSXText(sourceFile, position) {
108943         var token = getTokenAtPosition(sourceFile, position);
108944         if (ts.isJsxText(token)) {
108945             return true;
108946         }
108947         if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) {
108948             return true;
108949         }
108950         if (token.kind === 29 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) {
108951             return true;
108952         }
108953         return false;
108954     }
108955     ts.isInJSXText = isInJSXText;
108956     function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) {
108957         var tokenKind = token.kind;
108958         var remainingMatchingTokens = 0;
108959         while (true) {
108960             var preceding = findPrecedingToken(token.getFullStart(), sourceFile);
108961             if (!preceding) {
108962                 return undefined;
108963             }
108964             token = preceding;
108965             if (token.kind === matchingTokenKind) {
108966                 if (remainingMatchingTokens === 0) {
108967                     return token;
108968                 }
108969                 remainingMatchingTokens--;
108970             }
108971             else if (token.kind === tokenKind) {
108972                 remainingMatchingTokens++;
108973             }
108974         }
108975     }
108976     ts.findPrecedingMatchingToken = findPrecedingMatchingToken;
108977     function removeOptionality(type, isOptionalExpression, isOptionalChain) {
108978         return isOptionalExpression ? type.getNonNullableType() :
108979             isOptionalChain ? type.getNonOptionalType() :
108980                 type;
108981     }
108982     ts.removeOptionality = removeOptionality;
108983     function isPossiblyTypeArgumentPosition(token, sourceFile, checker) {
108984         var info = getPossibleTypeArgumentsInfo(token, sourceFile);
108985         return info !== undefined && (ts.isPartOfTypeNode(info.called) ||
108986             getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 ||
108987             isPossiblyTypeArgumentPosition(info.called, sourceFile, checker));
108988     }
108989     ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition;
108990     function getPossibleGenericSignatures(called, typeArgumentCount, checker) {
108991         var type = checker.getTypeAtLocation(called);
108992         if (ts.isOptionalChain(called.parent)) {
108993             type = removeOptionality(type, ts.isOptionalChainRoot(called.parent), /*isOptionalChain*/ true);
108994         }
108995         var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures();
108996         return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; });
108997     }
108998     ts.getPossibleGenericSignatures = getPossibleGenericSignatures;
108999     // Get info for an expression like `f <` that may be the start of type arguments.
109000     function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) {
109001         var token = tokenIn;
109002         // This function determines if the node could be type argument position
109003         // Since during editing, when type argument list is not complete,
109004         // the tree could be of any shape depending on the tokens parsed before current node,
109005         // scanning of the previous identifier followed by "<" before current node would give us better result
109006         // Note that we also balance out the already provided type arguments, arrays, object literals while doing so
109007         var remainingLessThanTokens = 0;
109008         var nTypeArguments = 0;
109009         while (token) {
109010             switch (token.kind) {
109011                 case 29 /* LessThanToken */:
109012                     // Found the beginning of the generic argument expression
109013                     token = findPrecedingToken(token.getFullStart(), sourceFile);
109014                     if (token && token.kind === 28 /* QuestionDotToken */) {
109015                         token = findPrecedingToken(token.getFullStart(), sourceFile);
109016                     }
109017                     if (!token || !ts.isIdentifier(token))
109018                         return undefined;
109019                     if (!remainingLessThanTokens) {
109020                         return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments };
109021                     }
109022                     remainingLessThanTokens--;
109023                     break;
109024                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
109025                     remainingLessThanTokens = +3;
109026                     break;
109027                 case 48 /* GreaterThanGreaterThanToken */:
109028                     remainingLessThanTokens = +2;
109029                     break;
109030                 case 31 /* GreaterThanToken */:
109031                     remainingLessThanTokens++;
109032                     break;
109033                 case 19 /* CloseBraceToken */:
109034                     // This can be object type, skip until we find the matching open brace token
109035                     // Skip until the matching open brace token
109036                     token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile);
109037                     if (!token)
109038                         return undefined;
109039                     break;
109040                 case 21 /* CloseParenToken */:
109041                     // This can be object type, skip until we find the matching open brace token
109042                     // Skip until the matching open brace token
109043                     token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile);
109044                     if (!token)
109045                         return undefined;
109046                     break;
109047                 case 23 /* CloseBracketToken */:
109048                     // This can be object type, skip until we find the matching open brace token
109049                     // Skip until the matching open brace token
109050                     token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile);
109051                     if (!token)
109052                         return undefined;
109053                     break;
109054                 // Valid tokens in a type name. Skip.
109055                 case 27 /* CommaToken */:
109056                     nTypeArguments++;
109057                     break;
109058                 case 38 /* EqualsGreaterThanToken */:
109059                 // falls through
109060                 case 75 /* Identifier */:
109061                 case 10 /* StringLiteral */:
109062                 case 8 /* NumericLiteral */:
109063                 case 9 /* BigIntLiteral */:
109064                 case 106 /* TrueKeyword */:
109065                 case 91 /* FalseKeyword */:
109066                 // falls through
109067                 case 108 /* TypeOfKeyword */:
109068                 case 90 /* ExtendsKeyword */:
109069                 case 134 /* KeyOfKeyword */:
109070                 case 24 /* DotToken */:
109071                 case 51 /* BarToken */:
109072                 case 57 /* QuestionToken */:
109073                 case 58 /* ColonToken */:
109074                     break;
109075                 default:
109076                     if (ts.isTypeNode(token)) {
109077                         break;
109078                     }
109079                     // Invalid token in type
109080                     return undefined;
109081             }
109082             token = findPrecedingToken(token.getFullStart(), sourceFile);
109083         }
109084         return undefined;
109085     }
109086     ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo;
109087     /**
109088      * Returns true if the cursor at position in sourceFile is within a comment.
109089      *
109090      * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position)
109091      * @param predicate Additional predicate to test on the comment range.
109092      */
109093     function isInComment(sourceFile, position, tokenAtPosition) {
109094         return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition);
109095     }
109096     ts.isInComment = isInComment;
109097     function hasDocComment(sourceFile, position) {
109098         var token = getTokenAtPosition(sourceFile, position);
109099         return !!ts.findAncestor(token, ts.isJSDoc);
109100     }
109101     ts.hasDocComment = hasDocComment;
109102     function nodeHasTokens(n, sourceFile) {
109103         // If we have a token or node that has a non-zero width, it must have tokens.
109104         // Note: getWidth() does not take trivia into account.
109105         return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0;
109106     }
109107     function getNodeModifiers(node) {
109108         var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */;
109109         var result = [];
109110         if (flags & 8 /* Private */)
109111             result.push("private" /* privateMemberModifier */);
109112         if (flags & 16 /* Protected */)
109113             result.push("protected" /* protectedMemberModifier */);
109114         if (flags & 4 /* Public */)
109115             result.push("public" /* publicMemberModifier */);
109116         if (flags & 32 /* Static */)
109117             result.push("static" /* staticModifier */);
109118         if (flags & 128 /* Abstract */)
109119             result.push("abstract" /* abstractModifier */);
109120         if (flags & 1 /* Export */)
109121             result.push("export" /* exportedModifier */);
109122         if (node.flags & 8388608 /* Ambient */)
109123             result.push("declare" /* ambientModifier */);
109124         if (node.kind === 259 /* ExportAssignment */)
109125             result.push("export" /* exportedModifier */);
109126         return result.length > 0 ? result.join(",") : "" /* none */;
109127     }
109128     ts.getNodeModifiers = getNodeModifiers;
109129     function getTypeArgumentOrTypeParameterList(node) {
109130         if (node.kind === 169 /* TypeReference */ || node.kind === 196 /* CallExpression */) {
109131             return node.typeArguments;
109132         }
109133         if (ts.isFunctionLike(node) || node.kind === 245 /* ClassDeclaration */ || node.kind === 246 /* InterfaceDeclaration */) {
109134             return node.typeParameters;
109135         }
109136         return undefined;
109137     }
109138     ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList;
109139     function isComment(kind) {
109140         return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */;
109141     }
109142     ts.isComment = isComment;
109143     function isStringOrRegularExpressionOrTemplateLiteral(kind) {
109144         if (kind === 10 /* StringLiteral */
109145             || kind === 13 /* RegularExpressionLiteral */
109146             || ts.isTemplateLiteralKind(kind)) {
109147             return true;
109148         }
109149         return false;
109150     }
109151     ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral;
109152     function isPunctuation(kind) {
109153         return 18 /* FirstPunctuation */ <= kind && kind <= 74 /* LastPunctuation */;
109154     }
109155     ts.isPunctuation = isPunctuation;
109156     function isInsideTemplateLiteral(node, position, sourceFile) {
109157         return ts.isTemplateLiteralKind(node.kind)
109158             && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end);
109159     }
109160     ts.isInsideTemplateLiteral = isInsideTemplateLiteral;
109161     function isAccessibilityModifier(kind) {
109162         switch (kind) {
109163             case 119 /* PublicKeyword */:
109164             case 117 /* PrivateKeyword */:
109165             case 118 /* ProtectedKeyword */:
109166                 return true;
109167         }
109168         return false;
109169     }
109170     ts.isAccessibilityModifier = isAccessibilityModifier;
109171     function cloneCompilerOptions(options) {
109172         var result = ts.clone(options);
109173         ts.setConfigFileInOptions(result, options && options.configFile);
109174         return result;
109175     }
109176     ts.cloneCompilerOptions = cloneCompilerOptions;
109177     function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
109178         if (node.kind === 192 /* ArrayLiteralExpression */ ||
109179             node.kind === 193 /* ObjectLiteralExpression */) {
109180             // [a,b,c] from:
109181             // [a, b, c] = someExpression;
109182             if (node.parent.kind === 209 /* BinaryExpression */ &&
109183                 node.parent.left === node &&
109184                 node.parent.operatorToken.kind === 62 /* EqualsToken */) {
109185                 return true;
109186             }
109187             // [a, b, c] from:
109188             // for([a, b, c] of expression)
109189             if (node.parent.kind === 232 /* ForOfStatement */ &&
109190                 node.parent.initializer === node) {
109191                 return true;
109192             }
109193             // [a, b, c] of
109194             // [x, [a, b, c] ] = someExpression
109195             // or
109196             // {x, a: {a, b, c} } = someExpression
109197             if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 281 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
109198                 return true;
109199             }
109200         }
109201         return false;
109202     }
109203     ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
109204     function isInReferenceComment(sourceFile, position) {
109205         return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true);
109206     }
109207     ts.isInReferenceComment = isInReferenceComment;
109208     function isInNonReferenceComment(sourceFile, position) {
109209         return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false);
109210     }
109211     ts.isInNonReferenceComment = isInNonReferenceComment;
109212     function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) {
109213         var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined);
109214         return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end));
109215     }
109216     function getReplacementSpanForContextToken(contextToken) {
109217         if (!contextToken)
109218             return undefined;
109219         switch (contextToken.kind) {
109220             case 10 /* StringLiteral */:
109221             case 14 /* NoSubstitutionTemplateLiteral */:
109222                 return createTextSpanFromStringLiteralLikeContent(contextToken);
109223             default:
109224                 return createTextSpanFromNode(contextToken);
109225         }
109226     }
109227     ts.getReplacementSpanForContextToken = getReplacementSpanForContextToken;
109228     function createTextSpanFromNode(node, sourceFile, endNode) {
109229         return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd());
109230     }
109231     ts.createTextSpanFromNode = createTextSpanFromNode;
109232     function createTextSpanFromStringLiteralLikeContent(node) {
109233         if (node.isUnterminated)
109234             return undefined;
109235         return ts.createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1);
109236     }
109237     ts.createTextSpanFromStringLiteralLikeContent = createTextSpanFromStringLiteralLikeContent;
109238     function createTextRangeFromNode(node, sourceFile) {
109239         return ts.createRange(node.getStart(sourceFile), node.end);
109240     }
109241     ts.createTextRangeFromNode = createTextRangeFromNode;
109242     function createTextSpanFromRange(range) {
109243         return ts.createTextSpanFromBounds(range.pos, range.end);
109244     }
109245     ts.createTextSpanFromRange = createTextSpanFromRange;
109246     function createTextRangeFromSpan(span) {
109247         return ts.createRange(span.start, span.start + span.length);
109248     }
109249     ts.createTextRangeFromSpan = createTextRangeFromSpan;
109250     function createTextChangeFromStartLength(start, length, newText) {
109251         return createTextChange(ts.createTextSpan(start, length), newText);
109252     }
109253     ts.createTextChangeFromStartLength = createTextChangeFromStartLength;
109254     function createTextChange(span, newText) {
109255         return { span: span, newText: newText };
109256     }
109257     ts.createTextChange = createTextChange;
109258     ts.typeKeywords = [
109259         125 /* AnyKeyword */,
109260         124 /* AssertsKeyword */,
109261         151 /* BigIntKeyword */,
109262         128 /* BooleanKeyword */,
109263         91 /* FalseKeyword */,
109264         134 /* KeyOfKeyword */,
109265         137 /* NeverKeyword */,
109266         100 /* NullKeyword */,
109267         140 /* NumberKeyword */,
109268         141 /* ObjectKeyword */,
109269         138 /* ReadonlyKeyword */,
109270         143 /* StringKeyword */,
109271         144 /* SymbolKeyword */,
109272         106 /* TrueKeyword */,
109273         110 /* VoidKeyword */,
109274         146 /* UndefinedKeyword */,
109275         147 /* UniqueKeyword */,
109276         148 /* UnknownKeyword */,
109277     ];
109278     function isTypeKeyword(kind) {
109279         return ts.contains(ts.typeKeywords, kind);
109280     }
109281     ts.isTypeKeyword = isTypeKeyword;
109282     function isTypeKeywordToken(node) {
109283         return node.kind === 145 /* TypeKeyword */;
109284     }
109285     ts.isTypeKeywordToken = isTypeKeywordToken;
109286     /** True if the symbol is for an external module, as opposed to a namespace. */
109287     function isExternalModuleSymbol(moduleSymbol) {
109288         return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */;
109289     }
109290     ts.isExternalModuleSymbol = isExternalModuleSymbol;
109291     function nodeSeenTracker() {
109292         var seen = [];
109293         return function (node) {
109294             var id = ts.getNodeId(node);
109295             return !seen[id] && (seen[id] = true);
109296         };
109297     }
109298     ts.nodeSeenTracker = nodeSeenTracker;
109299     function getSnapshotText(snap) {
109300         return snap.getText(0, snap.getLength());
109301     }
109302     ts.getSnapshotText = getSnapshotText;
109303     function repeatString(str, count) {
109304         var result = "";
109305         for (var i = 0; i < count; i++) {
109306             result += str;
109307         }
109308         return result;
109309     }
109310     ts.repeatString = repeatString;
109311     function skipConstraint(type) {
109312         return type.isTypeParameter() ? type.getConstraint() || type : type;
109313     }
109314     ts.skipConstraint = skipConstraint;
109315     function getNameFromPropertyName(name) {
109316         return name.kind === 154 /* ComputedPropertyName */
109317             // treat computed property names where expression is string/numeric literal as just string/numeric literal
109318             ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined
109319             : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name);
109320     }
109321     ts.getNameFromPropertyName = getNameFromPropertyName;
109322     function programContainsModules(program) {
109323         return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); });
109324     }
109325     ts.programContainsModules = programContainsModules;
109326     function programContainsEs6Modules(program) {
109327         return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; });
109328     }
109329     ts.programContainsEs6Modules = programContainsEs6Modules;
109330     function compilerOptionsIndicateEs6Modules(compilerOptions) {
109331         return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit;
109332     }
109333     ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules;
109334     function createModuleSpecifierResolutionHost(program, host) {
109335         // Mix in `getProbableSymlinks` from Program when host doesn't have it
109336         // in order for non-Project hosts to have a symlinks cache.
109337         return {
109338             fileExists: function (fileName) { return program.fileExists(fileName); },
109339             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
109340             readFile: ts.maybeBind(host, host.readFile),
109341             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
109342             getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || (function () { return program.getProbableSymlinks(); }),
109343             getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation),
109344             getSourceFiles: function () { return program.getSourceFiles(); },
109345             redirectTargetsMap: program.redirectTargetsMap,
109346             getProjectReferenceRedirect: function (fileName) { return program.getProjectReferenceRedirect(fileName); },
109347             isSourceOfProjectReferenceRedirect: function (fileName) { return program.isSourceOfProjectReferenceRedirect(fileName); },
109348         };
109349     }
109350     ts.createModuleSpecifierResolutionHost = createModuleSpecifierResolutionHost;
109351     function getModuleSpecifierResolverHost(program, host) {
109352         return __assign(__assign({}, createModuleSpecifierResolutionHost(program, host)), { getCommonSourceDirectory: function () { return program.getCommonSourceDirectory(); } });
109353     }
109354     ts.getModuleSpecifierResolverHost = getModuleSpecifierResolverHost;
109355     function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) {
109356         return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined;
109357     }
109358     ts.makeImportIfNecessary = makeImportIfNecessary;
109359     function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) {
109360         return ts.createImportDeclaration(
109361         /*decorators*/ undefined, 
109362         /*modifiers*/ undefined, defaultImport || namedImports
109363             ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined, isTypeOnly)
109364             : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier);
109365     }
109366     ts.makeImport = makeImport;
109367     function makeStringLiteral(text, quotePreference) {
109368         return ts.createLiteral(text, quotePreference === 0 /* Single */);
109369     }
109370     ts.makeStringLiteral = makeStringLiteral;
109371     var QuotePreference;
109372     (function (QuotePreference) {
109373         QuotePreference[QuotePreference["Single"] = 0] = "Single";
109374         QuotePreference[QuotePreference["Double"] = 1] = "Double";
109375     })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {}));
109376     function quotePreferenceFromString(str, sourceFile) {
109377         return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */;
109378     }
109379     ts.quotePreferenceFromString = quotePreferenceFromString;
109380     function getQuotePreference(sourceFile, preferences) {
109381         if (preferences.quotePreference && preferences.quotePreference !== "auto") {
109382             return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */;
109383         }
109384         else {
109385             var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral);
109386             return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */;
109387         }
109388     }
109389     ts.getQuotePreference = getQuotePreference;
109390     function getQuoteFromPreference(qp) {
109391         switch (qp) {
109392             case 0 /* Single */: return "'";
109393             case 1 /* Double */: return '"';
109394             default: return ts.Debug.assertNever(qp);
109395         }
109396     }
109397     ts.getQuoteFromPreference = getQuoteFromPreference;
109398     function symbolNameNoDefault(symbol) {
109399         var escaped = symbolEscapedNameNoDefault(symbol);
109400         return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped);
109401     }
109402     ts.symbolNameNoDefault = symbolNameNoDefault;
109403     function symbolEscapedNameNoDefault(symbol) {
109404         if (symbol.escapedName !== "default" /* Default */) {
109405             return symbol.escapedName;
109406         }
109407         return ts.firstDefined(symbol.declarations, function (decl) {
109408             var name = ts.getNameOfDeclaration(decl);
109409             return name && name.kind === 75 /* Identifier */ ? name.escapedText : undefined;
109410         });
109411     }
109412     ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault;
109413     function isObjectBindingElementWithoutPropertyName(bindingElement) {
109414         return ts.isBindingElement(bindingElement) &&
109415             ts.isObjectBindingPattern(bindingElement.parent) &&
109416             ts.isIdentifier(bindingElement.name) &&
109417             !bindingElement.propertyName;
109418     }
109419     ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName;
109420     function getPropertySymbolFromBindingElement(checker, bindingElement) {
109421         var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
109422         return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
109423     }
109424     ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
109425     /**
109426      * Find symbol of the given property-name and add the symbol to the given result array
109427      * @param symbol a symbol to start searching for the given propertyName
109428      * @param propertyName a name of property to search for
109429      * @param result an array of symbol of found property symbols
109430      * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
109431      *                                The value of previousIterationSymbol is undefined when the function is first called.
109432      */
109433     function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) {
109434         var seen = ts.createMap();
109435         return recur(symbol);
109436         function recur(symbol) {
109437             // Use `addToSeen` to ensure we don't infinitely recurse in this situation:
109438             //      interface C extends C {
109439             //          /*findRef*/propName: string;
109440             //      }
109441             if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol)))
109442                 return;
109443             return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) {
109444                 var type = checker.getTypeAtLocation(typeReference);
109445                 var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName);
109446                 // Visit the typeReference as well to see if it directly or indirectly uses that property
109447                 return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol));
109448             }); });
109449         }
109450     }
109451     ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes;
109452     function isMemberSymbolInBaseType(memberSymbol, checker) {
109453         return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false;
109454     }
109455     ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType;
109456     function getParentNodeInSpan(node, file, span) {
109457         if (!node)
109458             return undefined;
109459         while (node.parent) {
109460             if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) {
109461                 return node;
109462             }
109463             node = node.parent;
109464         }
109465     }
109466     ts.getParentNodeInSpan = getParentNodeInSpan;
109467     function spanContainsNode(span, node, file) {
109468         return ts.textSpanContainsPosition(span, node.getStart(file)) &&
109469             node.getEnd() <= ts.textSpanEnd(span);
109470     }
109471     function findModifier(node, kind) {
109472         return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; });
109473     }
109474     ts.findModifier = findModifier;
109475     function insertImports(changes, sourceFile, imports, blankLineBetween) {
109476         var decl = ts.isArray(imports) ? imports[0] : imports;
109477         var importKindPredicate = decl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax;
109478         var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); });
109479         if (lastImportDeclaration) {
109480             if (ts.isArray(imports)) {
109481                 changes.insertNodesAfter(sourceFile, lastImportDeclaration, imports);
109482             }
109483             else {
109484                 changes.insertNodeAfter(sourceFile, lastImportDeclaration, imports);
109485             }
109486         }
109487         else if (ts.isArray(imports)) {
109488             changes.insertNodesAtTopOfFile(sourceFile, imports, blankLineBetween);
109489         }
109490         else {
109491             changes.insertNodeAtTopOfFile(sourceFile, imports, blankLineBetween);
109492         }
109493     }
109494     ts.insertImports = insertImports;
109495     function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) {
109496         ts.Debug.assert(importClause.isTypeOnly);
109497         return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken);
109498     }
109499     ts.getTypeKeywordOfTypeOnlyImport = getTypeKeywordOfTypeOnlyImport;
109500     function textSpansEqual(a, b) {
109501         return !!a && !!b && a.start === b.start && a.length === b.length;
109502     }
109503     ts.textSpansEqual = textSpansEqual;
109504     function documentSpansEqual(a, b) {
109505         return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan);
109506     }
109507     ts.documentSpansEqual = documentSpansEqual;
109508     /**
109509      * Iterates through 'array' by index and performs the callback on each element of array until the callback
109510      * returns a truthy value, then returns that value.
109511      * If no such value is found, the callback is applied to each element of array and undefined is returned.
109512      */
109513     function forEachUnique(array, callback) {
109514         if (array) {
109515             for (var i = 0; i < array.length; i++) {
109516                 if (array.indexOf(array[i]) === i) {
109517                     var result = callback(array[i], i);
109518                     if (result) {
109519                         return result;
109520                     }
109521                 }
109522             }
109523         }
109524         return undefined;
109525     }
109526     ts.forEachUnique = forEachUnique;
109527     // #endregion
109528     // Display-part writer helpers
109529     // #region
109530     function isFirstDeclarationOfSymbolParameter(symbol) {
109531         return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 156 /* Parameter */;
109532     }
109533     ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter;
109534     var displayPartWriter = getDisplayPartWriter();
109535     function getDisplayPartWriter() {
109536         var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios
109537         var displayParts;
109538         var lineStart;
109539         var indent;
109540         var length;
109541         resetWriter();
109542         var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); };
109543         return {
109544             displayParts: function () {
109545                 var finalText = displayParts.length && displayParts[displayParts.length - 1].text;
109546                 if (length > absoluteMaximumLength && finalText && finalText !== "...") {
109547                     if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) {
109548                         displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space));
109549                     }
109550                     displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation));
109551                 }
109552                 return displayParts;
109553             },
109554             writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); },
109555             writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); },
109556             writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); },
109557             writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); },
109558             writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); },
109559             writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
109560             writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); },
109561             writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); },
109562             writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
109563             writeSymbol: writeSymbol,
109564             writeLine: writeLine,
109565             write: unknownWrite,
109566             writeComment: unknownWrite,
109567             getText: function () { return ""; },
109568             getTextPos: function () { return 0; },
109569             getColumn: function () { return 0; },
109570             getLine: function () { return 0; },
109571             isAtStartOfLine: function () { return false; },
109572             hasTrailingWhitespace: function () { return false; },
109573             hasTrailingComment: function () { return false; },
109574             rawWrite: ts.notImplemented,
109575             getIndent: function () { return indent; },
109576             increaseIndent: function () { indent++; },
109577             decreaseIndent: function () { indent--; },
109578             clear: resetWriter,
109579             trackSymbol: ts.noop,
109580             reportInaccessibleThisError: ts.noop,
109581             reportInaccessibleUniqueSymbolError: ts.noop,
109582             reportPrivateInBaseOfClassExpression: ts.noop,
109583         };
109584         function writeIndent() {
109585             if (length > absoluteMaximumLength)
109586                 return;
109587             if (lineStart) {
109588                 var indentString = ts.getIndentString(indent);
109589                 if (indentString) {
109590                     length += indentString.length;
109591                     displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space));
109592                 }
109593                 lineStart = false;
109594             }
109595         }
109596         function writeKind(text, kind) {
109597             if (length > absoluteMaximumLength)
109598                 return;
109599             writeIndent();
109600             length += text.length;
109601             displayParts.push(displayPart(text, kind));
109602         }
109603         function writeSymbol(text, symbol) {
109604             if (length > absoluteMaximumLength)
109605                 return;
109606             writeIndent();
109607             length += text.length;
109608             displayParts.push(symbolPart(text, symbol));
109609         }
109610         function writeLine() {
109611             if (length > absoluteMaximumLength)
109612                 return;
109613             length += 1;
109614             displayParts.push(lineBreakPart());
109615             lineStart = true;
109616         }
109617         function resetWriter() {
109618             displayParts = [];
109619             lineStart = true;
109620             indent = 0;
109621             length = 0;
109622         }
109623     }
109624     function symbolPart(text, symbol) {
109625         return displayPart(text, displayPartKind(symbol));
109626         function displayPartKind(symbol) {
109627             var flags = symbol.flags;
109628             if (flags & 3 /* Variable */) {
109629                 return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName;
109630             }
109631             else if (flags & 4 /* Property */) {
109632                 return ts.SymbolDisplayPartKind.propertyName;
109633             }
109634             else if (flags & 32768 /* GetAccessor */) {
109635                 return ts.SymbolDisplayPartKind.propertyName;
109636             }
109637             else if (flags & 65536 /* SetAccessor */) {
109638                 return ts.SymbolDisplayPartKind.propertyName;
109639             }
109640             else if (flags & 8 /* EnumMember */) {
109641                 return ts.SymbolDisplayPartKind.enumMemberName;
109642             }
109643             else if (flags & 16 /* Function */) {
109644                 return ts.SymbolDisplayPartKind.functionName;
109645             }
109646             else if (flags & 32 /* Class */) {
109647                 return ts.SymbolDisplayPartKind.className;
109648             }
109649             else if (flags & 64 /* Interface */) {
109650                 return ts.SymbolDisplayPartKind.interfaceName;
109651             }
109652             else if (flags & 384 /* Enum */) {
109653                 return ts.SymbolDisplayPartKind.enumName;
109654             }
109655             else if (flags & 1536 /* Module */) {
109656                 return ts.SymbolDisplayPartKind.moduleName;
109657             }
109658             else if (flags & 8192 /* Method */) {
109659                 return ts.SymbolDisplayPartKind.methodName;
109660             }
109661             else if (flags & 262144 /* TypeParameter */) {
109662                 return ts.SymbolDisplayPartKind.typeParameterName;
109663             }
109664             else if (flags & 524288 /* TypeAlias */) {
109665                 return ts.SymbolDisplayPartKind.aliasName;
109666             }
109667             else if (flags & 2097152 /* Alias */) {
109668                 return ts.SymbolDisplayPartKind.aliasName;
109669             }
109670             return ts.SymbolDisplayPartKind.text;
109671         }
109672     }
109673     ts.symbolPart = symbolPart;
109674     function displayPart(text, kind) {
109675         return { text: text, kind: ts.SymbolDisplayPartKind[kind] };
109676     }
109677     ts.displayPart = displayPart;
109678     function spacePart() {
109679         return displayPart(" ", ts.SymbolDisplayPartKind.space);
109680     }
109681     ts.spacePart = spacePart;
109682     function keywordPart(kind) {
109683         return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword);
109684     }
109685     ts.keywordPart = keywordPart;
109686     function punctuationPart(kind) {
109687         return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation);
109688     }
109689     ts.punctuationPart = punctuationPart;
109690     function operatorPart(kind) {
109691         return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator);
109692     }
109693     ts.operatorPart = operatorPart;
109694     function textOrKeywordPart(text) {
109695         var kind = ts.stringToToken(text);
109696         return kind === undefined
109697             ? textPart(text)
109698             : keywordPart(kind);
109699     }
109700     ts.textOrKeywordPart = textOrKeywordPart;
109701     function textPart(text) {
109702         return displayPart(text, ts.SymbolDisplayPartKind.text);
109703     }
109704     ts.textPart = textPart;
109705     var carriageReturnLineFeed = "\r\n";
109706     /**
109707      * The default is CRLF.
109708      */
109709     function getNewLineOrDefaultFromHost(host, formatSettings) {
109710         var _a;
109711         return (formatSettings === null || formatSettings === void 0 ? void 0 : formatSettings.newLineCharacter) || ((_a = host.getNewLine) === null || _a === void 0 ? void 0 : _a.call(host)) ||
109712             carriageReturnLineFeed;
109713     }
109714     ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost;
109715     function lineBreakPart() {
109716         return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak);
109717     }
109718     ts.lineBreakPart = lineBreakPart;
109719     function mapToDisplayParts(writeDisplayParts) {
109720         try {
109721             writeDisplayParts(displayPartWriter);
109722             return displayPartWriter.displayParts();
109723         }
109724         finally {
109725             displayPartWriter.clear();
109726         }
109727     }
109728     ts.mapToDisplayParts = mapToDisplayParts;
109729     function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) {
109730         if (flags === void 0) { flags = 0 /* None */; }
109731         return mapToDisplayParts(function (writer) {
109732             typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer);
109733         });
109734     }
109735     ts.typeToDisplayParts = typeToDisplayParts;
109736     function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) {
109737         if (flags === void 0) { flags = 0 /* None */; }
109738         return mapToDisplayParts(function (writer) {
109739             typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer);
109740         });
109741     }
109742     ts.symbolToDisplayParts = symbolToDisplayParts;
109743     function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) {
109744         if (flags === void 0) { flags = 0 /* None */; }
109745         flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */;
109746         return mapToDisplayParts(function (writer) {
109747             typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer);
109748         });
109749     }
109750     ts.signatureToDisplayParts = signatureToDisplayParts;
109751     function isImportOrExportSpecifierName(location) {
109752         return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
109753     }
109754     ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
109755     function scriptKindIs(fileName, host) {
109756         var scriptKinds = [];
109757         for (var _i = 2; _i < arguments.length; _i++) {
109758             scriptKinds[_i - 2] = arguments[_i];
109759         }
109760         var scriptKind = getScriptKind(fileName, host);
109761         return ts.some(scriptKinds, function (k) { return k === scriptKind; });
109762     }
109763     ts.scriptKindIs = scriptKindIs;
109764     function getScriptKind(fileName, host) {
109765         // First check to see if the script kind was specified by the host. Chances are the host
109766         // may override the default script kind for the file extension.
109767         return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
109768     }
109769     ts.getScriptKind = getScriptKind;
109770     function getSymbolTarget(symbol, checker) {
109771         var next = symbol;
109772         while (isAliasSymbol(next) || (isTransientSymbol(next) && next.target)) {
109773             if (isTransientSymbol(next) && next.target) {
109774                 next = next.target;
109775             }
109776             else {
109777                 next = ts.skipAlias(next, checker);
109778             }
109779         }
109780         return next;
109781     }
109782     ts.getSymbolTarget = getSymbolTarget;
109783     function isTransientSymbol(symbol) {
109784         return (symbol.flags & 33554432 /* Transient */) !== 0;
109785     }
109786     function isAliasSymbol(symbol) {
109787         return (symbol.flags & 2097152 /* Alias */) !== 0;
109788     }
109789     function getUniqueSymbolId(symbol, checker) {
109790         return ts.getSymbolId(ts.skipAlias(symbol, checker));
109791     }
109792     ts.getUniqueSymbolId = getUniqueSymbolId;
109793     function getFirstNonSpaceCharacterPosition(text, position) {
109794         while (ts.isWhiteSpaceLike(text.charCodeAt(position))) {
109795             position += 1;
109796         }
109797         return position;
109798     }
109799     ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition;
109800     function getPrecedingNonSpaceCharacterPosition(text, position) {
109801         while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) {
109802             position -= 1;
109803         }
109804         return position + 1;
109805     }
109806     ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition;
109807     /**
109808      * Creates a deep, memberwise clone of a node with no source map location.
109809      *
109810      * WARNING: This is an expensive operation and is only intended to be used in refactorings
109811      * and code fixes (because those are triggered by explicit user actions).
109812      */
109813     function getSynthesizedDeepClone(node, includeTrivia) {
109814         if (includeTrivia === void 0) { includeTrivia = true; }
109815         var clone = node && getSynthesizedDeepCloneWorker(node);
109816         if (clone && !includeTrivia)
109817             suppressLeadingAndTrailingTrivia(clone);
109818         return clone;
109819     }
109820     ts.getSynthesizedDeepClone = getSynthesizedDeepClone;
109821     function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) {
109822         if (includeTrivia === void 0) { includeTrivia = true; }
109823         var clone;
109824         if (renameMap && checker && ts.isBindingElement(node) && ts.isIdentifier(node.name) && ts.isObjectBindingPattern(node.parent)) {
109825             var symbol = checker.getSymbolAtLocation(node.name);
109826             var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol)));
109827             if (renameInfo && renameInfo.text !== (node.name || node.propertyName).getText()) {
109828                 clone = ts.setOriginalNode(ts.createBindingElement(node.dotDotDotToken, node.propertyName || node.name, renameInfo, node.initializer), node);
109829             }
109830         }
109831         else if (renameMap && checker && ts.isIdentifier(node)) {
109832             var symbol = checker.getSymbolAtLocation(node);
109833             var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol)));
109834             if (renameInfo) {
109835                 clone = ts.setOriginalNode(ts.createIdentifier(renameInfo.text), node);
109836             }
109837         }
109838         if (!clone) {
109839             clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback);
109840         }
109841         if (clone && !includeTrivia)
109842             suppressLeadingAndTrailingTrivia(clone);
109843         if (callback && clone)
109844             callback(node, clone);
109845         return clone;
109846     }
109847     ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames;
109848     function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) {
109849         var visited = (renameMap || checker || callback) ?
109850             ts.visitEachChild(node, wrapper, ts.nullTransformationContext) :
109851             ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
109852         if (visited === node) {
109853             // This only happens for leaf nodes - internal nodes always see their children change.
109854             var clone_1 = ts.getSynthesizedClone(node);
109855             if (ts.isStringLiteral(clone_1)) {
109856                 clone_1.textSourceNode = node;
109857             }
109858             else if (ts.isNumericLiteral(clone_1)) {
109859                 clone_1.numericLiteralFlags = node.numericLiteralFlags;
109860             }
109861             return ts.setTextRange(clone_1, node);
109862         }
109863         // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
109864         // the new node created by visitEachChild with the extra changes getSynthesizedClone
109865         // would have made.
109866         visited.parent = undefined;
109867         return visited;
109868         function wrapper(node) {
109869             return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback);
109870         }
109871     }
109872     function getSynthesizedDeepClones(nodes, includeTrivia) {
109873         if (includeTrivia === void 0) { includeTrivia = true; }
109874         return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma);
109875     }
109876     ts.getSynthesizedDeepClones = getSynthesizedDeepClones;
109877     /**
109878      * Sets EmitFlags to suppress leading and trailing trivia on the node.
109879      */
109880     function suppressLeadingAndTrailingTrivia(node) {
109881         suppressLeadingTrivia(node);
109882         suppressTrailingTrivia(node);
109883     }
109884     ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia;
109885     /**
109886      * Sets EmitFlags to suppress leading trivia on the node.
109887      */
109888     function suppressLeadingTrivia(node) {
109889         addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild);
109890     }
109891     ts.suppressLeadingTrivia = suppressLeadingTrivia;
109892     /**
109893      * Sets EmitFlags to suppress trailing trivia on the node.
109894      */
109895     function suppressTrailingTrivia(node) {
109896         addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild);
109897     }
109898     ts.suppressTrailingTrivia = suppressTrailingTrivia;
109899     function copyComments(sourceNode, targetNode) {
109900         var sourceFile = sourceNode.getSourceFile();
109901         var text = sourceFile.text;
109902         if (hasLeadingLineBreak(sourceNode, text)) {
109903             copyLeadingComments(sourceNode, targetNode, sourceFile);
109904         }
109905         else {
109906             copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
109907         }
109908         copyTrailingComments(sourceNode, targetNode, sourceFile);
109909     }
109910     ts.copyComments = copyComments;
109911     function hasLeadingLineBreak(node, text) {
109912         var start = node.getFullStart();
109913         var end = node.getStart();
109914         for (var i = start; i < end; i++) {
109915             if (text.charCodeAt(i) === 10 /* lineFeed */)
109916                 return true;
109917         }
109918         return false;
109919     }
109920     function addEmitFlagsRecursively(node, flag, getChild) {
109921         ts.addEmitFlags(node, flag);
109922         var child = getChild(node);
109923         if (child)
109924             addEmitFlagsRecursively(child, flag, getChild);
109925     }
109926     function getFirstChild(node) {
109927         return node.forEachChild(function (child) { return child; });
109928     }
109929     function getUniqueName(baseName, sourceFile) {
109930         var nameText = baseName;
109931         for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) {
109932             nameText = baseName + "_" + i;
109933         }
109934         return nameText;
109935     }
109936     ts.getUniqueName = getUniqueName;
109937     /**
109938      * @return The index of the (only) reference to the extracted symbol.  We want the cursor
109939      * to be on the reference, rather than the declaration, because it's closer to where the
109940      * user was before extracting it.
109941      */
109942     function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
109943         var delta = 0;
109944         var lastPos = -1;
109945         for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
109946             var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges;
109947             ts.Debug.assert(fileName === renameFilename);
109948             for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) {
109949                 var change = textChanges_1[_b];
109950                 var span = change.span, newText = change.newText;
109951                 var index = indexInTextChange(newText, name);
109952                 if (index !== -1) {
109953                     lastPos = span.start + delta + index;
109954                     // If the reference comes first, return immediately.
109955                     if (!preferLastLocation) {
109956                         return lastPos;
109957                     }
109958                 }
109959                 delta += newText.length - span.length;
109960             }
109961         }
109962         // If the declaration comes first, return the position of the last occurrence.
109963         ts.Debug.assert(preferLastLocation);
109964         ts.Debug.assert(lastPos >= 0);
109965         return lastPos;
109966     }
109967     ts.getRenameLocation = getRenameLocation;
109968     function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
109969         ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
109970     }
109971     ts.copyLeadingComments = copyLeadingComments;
109972     function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
109973         ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
109974     }
109975     ts.copyTrailingComments = copyTrailingComments;
109976     /**
109977      * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
109978      * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
109979      * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
109980      * `function foo(\* not leading comment for a *\ a: string) {}`
109981      * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
109982      */
109983     function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
109984         ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
109985     }
109986     ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
109987     function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
109988         return function (pos, end, kind, htnl) {
109989             if (kind === 3 /* MultiLineCommentTrivia */) {
109990                 // Remove leading /*
109991                 pos += 2;
109992                 // Remove trailing */
109993                 end -= 2;
109994             }
109995             else {
109996                 // Remove leading //
109997                 pos += 2;
109998             }
109999             cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
110000         };
110001     }
110002     function indexInTextChange(change, name) {
110003         if (ts.startsWith(change, name))
110004             return 0;
110005         // Add a " " to avoid references inside words
110006         var idx = change.indexOf(" " + name);
110007         if (idx === -1)
110008             idx = change.indexOf("." + name);
110009         if (idx === -1)
110010             idx = change.indexOf('"' + name);
110011         return idx === -1 ? -1 : idx + 1;
110012     }
110013     /* @internal */
110014     function needsParentheses(expression) {
110015         return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression);
110016     }
110017     ts.needsParentheses = needsParentheses;
110018     function getContextualTypeFromParent(node, checker) {
110019         var parent = node.parent;
110020         switch (parent.kind) {
110021             case 197 /* NewExpression */:
110022                 return checker.getContextualType(parent);
110023             case 209 /* BinaryExpression */: {
110024                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
110025                 return isEqualityOperatorKind(operatorToken.kind)
110026                     ? checker.getTypeAtLocation(node === right ? left : right)
110027                     : checker.getContextualType(node);
110028             }
110029             case 277 /* CaseClause */:
110030                 return parent.expression === node ? getSwitchedType(parent, checker) : undefined;
110031             default:
110032                 return checker.getContextualType(node);
110033         }
110034     }
110035     ts.getContextualTypeFromParent = getContextualTypeFromParent;
110036     function quote(text, preferences) {
110037         // Editors can pass in undefined or empty string - we want to infer the preference in those cases.
110038         var quotePreference = preferences.quotePreference || "auto";
110039         var quoted = JSON.stringify(text);
110040         switch (quotePreference) {
110041             // TODO use getQuotePreference to infer the actual quote style.
110042             case "auto":
110043             case "double":
110044                 return quoted;
110045             case "single":
110046                 return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'";
110047             default:
110048                 return ts.Debug.assertNever(quotePreference);
110049         }
110050     }
110051     ts.quote = quote;
110052     function isEqualityOperatorKind(kind) {
110053         switch (kind) {
110054             case 36 /* EqualsEqualsEqualsToken */:
110055             case 34 /* EqualsEqualsToken */:
110056             case 37 /* ExclamationEqualsEqualsToken */:
110057             case 35 /* ExclamationEqualsToken */:
110058                 return true;
110059             default:
110060                 return false;
110061         }
110062     }
110063     ts.isEqualityOperatorKind = isEqualityOperatorKind;
110064     function isStringLiteralOrTemplate(node) {
110065         switch (node.kind) {
110066             case 10 /* StringLiteral */:
110067             case 14 /* NoSubstitutionTemplateLiteral */:
110068             case 211 /* TemplateExpression */:
110069             case 198 /* TaggedTemplateExpression */:
110070                 return true;
110071             default:
110072                 return false;
110073         }
110074     }
110075     ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate;
110076     function hasIndexSignature(type) {
110077         return !!type.getStringIndexType() || !!type.getNumberIndexType();
110078     }
110079     ts.hasIndexSignature = hasIndexSignature;
110080     function getSwitchedType(caseClause, checker) {
110081         return checker.getTypeAtLocation(caseClause.parent.parent.expression);
110082     }
110083     ts.getSwitchedType = getSwitchedType;
110084     ts.ANONYMOUS = "anonymous function";
110085     function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
110086         var checker = program.getTypeChecker();
110087         var typeIsAccessible = true;
110088         var notAccessible = function () { typeIsAccessible = false; };
110089         var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
110090             trackSymbol: function (symbol, declaration, meaning) {
110091                 typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
110092             },
110093             reportInaccessibleThisError: notAccessible,
110094             reportPrivateInBaseOfClassExpression: notAccessible,
110095             reportInaccessibleUniqueSymbolError: notAccessible,
110096             moduleResolverHost: getModuleSpecifierResolverHost(program, host)
110097         });
110098         return typeIsAccessible ? res : undefined;
110099     }
110100     ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
110101     function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) {
110102         return kind === 165 /* CallSignature */
110103             || kind === 166 /* ConstructSignature */
110104             || kind === 167 /* IndexSignature */
110105             || kind === 158 /* PropertySignature */
110106             || kind === 160 /* MethodSignature */;
110107     }
110108     ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI;
110109     function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) {
110110         return kind === 244 /* FunctionDeclaration */
110111             || kind === 162 /* Constructor */
110112             || kind === 161 /* MethodDeclaration */
110113             || kind === 163 /* GetAccessor */
110114             || kind === 164 /* SetAccessor */;
110115     }
110116     ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI;
110117     function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) {
110118         return kind === 249 /* ModuleDeclaration */;
110119     }
110120     ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI;
110121     function syntaxRequiresTrailingSemicolonOrASI(kind) {
110122         return kind === 225 /* VariableStatement */
110123             || kind === 226 /* ExpressionStatement */
110124             || kind === 228 /* DoStatement */
110125             || kind === 233 /* ContinueStatement */
110126             || kind === 234 /* BreakStatement */
110127             || kind === 235 /* ReturnStatement */
110128             || kind === 239 /* ThrowStatement */
110129             || kind === 241 /* DebuggerStatement */
110130             || kind === 159 /* PropertyDeclaration */
110131             || kind === 247 /* TypeAliasDeclaration */
110132             || kind === 254 /* ImportDeclaration */
110133             || kind === 253 /* ImportEqualsDeclaration */
110134             || kind === 260 /* ExportDeclaration */
110135             || kind === 252 /* NamespaceExportDeclaration */
110136             || kind === 259 /* ExportAssignment */;
110137     }
110138     ts.syntaxRequiresTrailingSemicolonOrASI = syntaxRequiresTrailingSemicolonOrASI;
110139     ts.syntaxMayBeASICandidate = ts.or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI);
110140     function nodeIsASICandidate(node, sourceFile) {
110141         var lastToken = node.getLastToken(sourceFile);
110142         if (lastToken && lastToken.kind === 26 /* SemicolonToken */) {
110143             return false;
110144         }
110145         if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) {
110146             if (lastToken && lastToken.kind === 27 /* CommaToken */) {
110147                 return false;
110148             }
110149         }
110150         else if (syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(node.kind)) {
110151             var lastChild = ts.last(node.getChildren(sourceFile));
110152             if (lastChild && ts.isModuleBlock(lastChild)) {
110153                 return false;
110154             }
110155         }
110156         else if (syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(node.kind)) {
110157             var lastChild = ts.last(node.getChildren(sourceFile));
110158             if (lastChild && ts.isFunctionBlock(lastChild)) {
110159                 return false;
110160             }
110161         }
110162         else if (!syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
110163             return false;
110164         }
110165         // See comment in parser’s `parseDoStatement`
110166         if (node.kind === 228 /* DoStatement */) {
110167             return true;
110168         }
110169         var topNode = ts.findAncestor(node, function (ancestor) { return !ancestor.parent; });
110170         var nextToken = findNextToken(node, topNode, sourceFile);
110171         if (!nextToken || nextToken.kind === 19 /* CloseBraceToken */) {
110172             return true;
110173         }
110174         var startLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
110175         var endLine = sourceFile.getLineAndCharacterOfPosition(nextToken.getStart(sourceFile)).line;
110176         return startLine !== endLine;
110177     }
110178     function positionIsASICandidate(pos, context, sourceFile) {
110179         var contextAncestor = ts.findAncestor(context, function (ancestor) {
110180             if (ancestor.end !== pos) {
110181                 return "quit";
110182             }
110183             return ts.syntaxMayBeASICandidate(ancestor.kind);
110184         });
110185         return !!contextAncestor && nodeIsASICandidate(contextAncestor, sourceFile);
110186     }
110187     ts.positionIsASICandidate = positionIsASICandidate;
110188     function probablyUsesSemicolons(sourceFile) {
110189         var withSemicolon = 0;
110190         var withoutSemicolon = 0;
110191         var nStatementsToObserve = 5;
110192         ts.forEachChild(sourceFile, function visit(node) {
110193             if (syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
110194                 var lastToken = node.getLastToken(sourceFile);
110195                 if (lastToken && lastToken.kind === 26 /* SemicolonToken */) {
110196                     withSemicolon++;
110197                 }
110198                 else {
110199                     withoutSemicolon++;
110200                 }
110201             }
110202             if (withSemicolon + withoutSemicolon >= nStatementsToObserve) {
110203                 return true;
110204             }
110205             return ts.forEachChild(node, visit);
110206         });
110207         // One statement missing a semicolon isn’t sufficient evidence to say the user
110208         // doesn’t want semicolons, because they may not even be done writing that statement.
110209         if (withSemicolon === 0 && withoutSemicolon <= 1) {
110210             return true;
110211         }
110212         // If even 2/5 places have a semicolon, the user probably wants semicolons
110213         return withSemicolon / withoutSemicolon > 1 / nStatementsToObserve;
110214     }
110215     ts.probablyUsesSemicolons = probablyUsesSemicolons;
110216     function tryGetDirectories(host, directoryName) {
110217         return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || [];
110218     }
110219     ts.tryGetDirectories = tryGetDirectories;
110220     function tryReadDirectory(host, path, extensions, exclude, include) {
110221         return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || ts.emptyArray;
110222     }
110223     ts.tryReadDirectory = tryReadDirectory;
110224     function tryFileExists(host, path) {
110225         return tryIOAndConsumeErrors(host, host.fileExists, path);
110226     }
110227     ts.tryFileExists = tryFileExists;
110228     function tryDirectoryExists(host, path) {
110229         return tryAndIgnoreErrors(function () { return ts.directoryProbablyExists(path, host); }) || false;
110230     }
110231     ts.tryDirectoryExists = tryDirectoryExists;
110232     function tryAndIgnoreErrors(cb) {
110233         try {
110234             return cb();
110235         }
110236         catch (_a) {
110237             return undefined;
110238         }
110239     }
110240     ts.tryAndIgnoreErrors = tryAndIgnoreErrors;
110241     function tryIOAndConsumeErrors(host, toApply) {
110242         var args = [];
110243         for (var _i = 2; _i < arguments.length; _i++) {
110244             args[_i - 2] = arguments[_i];
110245         }
110246         return tryAndIgnoreErrors(function () { return toApply && toApply.apply(host, args); });
110247     }
110248     ts.tryIOAndConsumeErrors = tryIOAndConsumeErrors;
110249     function findPackageJsons(startDirectory, host, stopDirectory) {
110250         var paths = [];
110251         ts.forEachAncestorDirectory(startDirectory, function (ancestor) {
110252             if (ancestor === stopDirectory) {
110253                 return true;
110254             }
110255             var currentConfigPath = ts.combinePaths(ancestor, "package.json");
110256             if (tryFileExists(host, currentConfigPath)) {
110257                 paths.push(currentConfigPath);
110258             }
110259         });
110260         return paths;
110261     }
110262     ts.findPackageJsons = findPackageJsons;
110263     function findPackageJson(directory, host) {
110264         var packageJson;
110265         ts.forEachAncestorDirectory(directory, function (ancestor) {
110266             if (ancestor === "node_modules")
110267                 return true;
110268             packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json");
110269             if (packageJson) {
110270                 return true; // break out
110271             }
110272         });
110273         return packageJson;
110274     }
110275     ts.findPackageJson = findPackageJson;
110276     function getPackageJsonsVisibleToFile(fileName, host) {
110277         if (!host.fileExists) {
110278             return [];
110279         }
110280         var packageJsons = [];
110281         ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (ancestor) {
110282             var packageJsonFileName = ts.combinePaths(ancestor, "package.json");
110283             if (host.fileExists(packageJsonFileName)) {
110284                 var info = createPackageJsonInfo(packageJsonFileName, host);
110285                 if (info) {
110286                     packageJsons.push(info);
110287                 }
110288             }
110289         });
110290         return packageJsons;
110291     }
110292     ts.getPackageJsonsVisibleToFile = getPackageJsonsVisibleToFile;
110293     function createPackageJsonInfo(fileName, host) {
110294         if (!host.readFile) {
110295             return undefined;
110296         }
110297         var dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
110298         var stringContent = host.readFile(fileName);
110299         if (!stringContent)
110300             return undefined;
110301         var content = tryParseJson(stringContent);
110302         if (!content)
110303             return false;
110304         var info = {};
110305         for (var _i = 0, dependencyKeys_1 = dependencyKeys; _i < dependencyKeys_1.length; _i++) {
110306             var key = dependencyKeys_1[_i];
110307             var dependencies = content[key];
110308             if (!dependencies) {
110309                 continue;
110310             }
110311             var dependencyMap = ts.createMap();
110312             for (var packageName in dependencies) {
110313                 dependencyMap.set(packageName, dependencies[packageName]);
110314             }
110315             info[key] = dependencyMap;
110316         }
110317         var dependencyGroups = [
110318             [1 /* Dependencies */, info.dependencies],
110319             [2 /* DevDependencies */, info.devDependencies],
110320             [8 /* OptionalDependencies */, info.optionalDependencies],
110321             [4 /* PeerDependencies */, info.peerDependencies],
110322         ];
110323         return __assign(__assign({}, info), { fileName: fileName,
110324             get: get,
110325             has: function (dependencyName, inGroups) {
110326                 return !!get(dependencyName, inGroups);
110327             } });
110328         function get(dependencyName, inGroups) {
110329             if (inGroups === void 0) { inGroups = 15 /* All */; }
110330             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
110331                 var _a = dependencyGroups_1[_i], group_1 = _a[0], deps = _a[1];
110332                 if (deps && (inGroups & group_1)) {
110333                     var dep = deps.get(dependencyName);
110334                     if (dep !== undefined) {
110335                         return dep;
110336                     }
110337                 }
110338             }
110339         }
110340     }
110341     ts.createPackageJsonInfo = createPackageJsonInfo;
110342     function tryParseJson(text) {
110343         try {
110344             return JSON.parse(text);
110345         }
110346         catch (_a) {
110347             return undefined;
110348         }
110349     }
110350     function consumesNodeCoreModules(sourceFile) {
110351         return ts.some(sourceFile.imports, function (_a) {
110352             var text = _a.text;
110353             return ts.JsTyping.nodeCoreModules.has(text);
110354         });
110355     }
110356     ts.consumesNodeCoreModules = consumesNodeCoreModules;
110357     function isInsideNodeModules(fileOrDirectory) {
110358         return ts.contains(ts.getPathComponents(fileOrDirectory), "node_modules");
110359     }
110360     ts.isInsideNodeModules = isInsideNodeModules;
110361     function isDiagnosticWithLocation(diagnostic) {
110362         return diagnostic.file !== undefined && diagnostic.start !== undefined && diagnostic.length !== undefined;
110363     }
110364     ts.isDiagnosticWithLocation = isDiagnosticWithLocation;
110365     function findDiagnosticForNode(node, sortedFileDiagnostics) {
110366         var span = createTextSpanFromNode(node);
110367         var index = ts.binarySearchKey(sortedFileDiagnostics, span, ts.identity, ts.compareTextSpans);
110368         if (index >= 0) {
110369             var diagnostic = sortedFileDiagnostics[index];
110370             ts.Debug.assertEqual(diagnostic.file, node.getSourceFile(), "Diagnostics proided to 'findDiagnosticForNode' must be from a single SourceFile");
110371             return ts.cast(diagnostic, isDiagnosticWithLocation);
110372         }
110373     }
110374     ts.findDiagnosticForNode = findDiagnosticForNode;
110375     function getDiagnosticsWithinSpan(span, sortedFileDiagnostics) {
110376         var _a;
110377         var index = ts.binarySearchKey(sortedFileDiagnostics, span.start, function (diag) { return diag.start; }, ts.compareValues);
110378         if (index < 0) {
110379             index = ~index;
110380         }
110381         while (((_a = sortedFileDiagnostics[index - 1]) === null || _a === void 0 ? void 0 : _a.start) === span.start) {
110382             index--;
110383         }
110384         var result = [];
110385         var end = ts.textSpanEnd(span);
110386         while (true) {
110387             var diagnostic = ts.tryCast(sortedFileDiagnostics[index], isDiagnosticWithLocation);
110388             if (!diagnostic || diagnostic.start > end) {
110389                 break;
110390             }
110391             if (ts.textSpanContainsTextSpan(span, diagnostic)) {
110392                 result.push(diagnostic);
110393             }
110394             index++;
110395         }
110396         return result;
110397     }
110398     ts.getDiagnosticsWithinSpan = getDiagnosticsWithinSpan;
110399     /* @internal */
110400     function getRefactorContextSpan(_a) {
110401         var startPosition = _a.startPosition, endPosition = _a.endPosition;
110402         return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
110403     }
110404     ts.getRefactorContextSpan = getRefactorContextSpan;
110405     function mapOneOrMany(valueOrArray, f, resultSelector) {
110406         if (resultSelector === void 0) { resultSelector = ts.identity; }
110407         return valueOrArray ? ts.isArray(valueOrArray) ? resultSelector(ts.map(valueOrArray, f)) : f(valueOrArray, 0) : undefined;
110408     }
110409     ts.mapOneOrMany = mapOneOrMany;
110410     /**
110411      * If the provided value is an array, the first element of the array is returned; otherwise, the provided value is returned instead.
110412      */
110413     function firstOrOnly(valueOrArray) {
110414         return ts.isArray(valueOrArray) ? ts.first(valueOrArray) : valueOrArray;
110415     }
110416     ts.firstOrOnly = firstOrOnly;
110417     function getNameForExportedSymbol(symbol, scriptTarget) {
110418         if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) {
110419             // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase.
110420             return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; })
110421                 || ts.codefix.moduleSymbolToValidIdentifier(ts.Debug.checkDefined(symbol.parent), scriptTarget);
110422         }
110423         return symbol.name;
110424     }
110425     ts.getNameForExportedSymbol = getNameForExportedSymbol;
110426     /**
110427      * Useful to check whether a string contains another string at a specific index
110428      * without allocating another string or traversing the entire contents of the outer string.
110429      *
110430      * This function is useful in place of either of the following:
110431      *
110432      * ```ts
110433      * // Allocates
110434      * haystack.substr(startIndex, needle.length) === needle
110435      *
110436      * // Full traversal
110437      * haystack.indexOf(needle, startIndex) === startIndex
110438      * ```
110439      *
110440      * @param haystack The string that potentially contains `needle`.
110441      * @param needle The string whose content might sit within `haystack`.
110442      * @param startIndex The index within `haystack` to start searching for `needle`.
110443      */
110444     function stringContainsAt(haystack, needle, startIndex) {
110445         var needleLength = needle.length;
110446         if (needleLength + startIndex > haystack.length) {
110447             return false;
110448         }
110449         for (var i = 0; i < needleLength; i++) {
110450             if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex))
110451                 return false;
110452         }
110453         return true;
110454     }
110455     ts.stringContainsAt = stringContainsAt;
110456     function startsWithUnderscore(name) {
110457         return name.charCodeAt(0) === 95 /* _ */;
110458     }
110459     ts.startsWithUnderscore = startsWithUnderscore;
110460     function isGlobalDeclaration(declaration) {
110461         return !isNonGlobalDeclaration(declaration);
110462     }
110463     ts.isGlobalDeclaration = isGlobalDeclaration;
110464     function isNonGlobalDeclaration(declaration) {
110465         var sourceFile = declaration.getSourceFile();
110466         // If the file is not a module, the declaration is global
110467         if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) {
110468             return false;
110469         }
110470         // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation
110471         return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation);
110472     }
110473     ts.isNonGlobalDeclaration = isNonGlobalDeclaration;
110474     // #endregion
110475 })(ts || (ts = {}));
110476 var ts;
110477 (function (ts) {
110478     /** The classifier is used for syntactic highlighting in editors via the TSServer */
110479     function createClassifier() {
110480         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false);
110481         function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
110482             return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
110483         }
110484         // If there is a syntactic classifier ('syntacticClassifierAbsent' is false),
110485         // we will be more conservative in order to avoid conflicting with the syntactic classifier.
110486         function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) {
110487             var token = 0 /* Unknown */;
110488             var lastNonTriviaToken = 0 /* Unknown */;
110489             // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact)
110490             // classification on template strings. Because of the context free nature of templates,
110491             // the only precise way to classify a template portion would be by propagating the stack across
110492             // lines, just as we do with the end-of-line state. However, this is a burden for implementers,
110493             // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead
110494             // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state.
110495             // Situations in which this fails are
110496             //  1) When template strings are nested across different lines:
110497             //          `hello ${ `world
110498             //          ` }`
110499             //
110500             //     Where on the second line, you will get the closing of a template,
110501             //     a closing curly, and a new template.
110502             //
110503             //  2) When substitution expressions have curly braces and the curly brace falls on the next line:
110504             //          `hello ${ () => {
110505             //          return "world" } } `
110506             //
110507             //     Where on the second line, you will get the 'return' keyword,
110508             //     a string literal, and a template end consisting of '} } `'.
110509             var templateStack = [];
110510             var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate;
110511             text = prefix + text;
110512             var offset = prefix.length;
110513             if (pushTemplate) {
110514                 templateStack.push(15 /* TemplateHead */);
110515             }
110516             scanner.setText(text);
110517             var endOfLineState = 0 /* None */;
110518             var spans = [];
110519             // We can run into an unfortunate interaction between the lexical and syntactic classifier
110520             // when the user is typing something generic.  Consider the case where the user types:
110521             //
110522             //      Foo<number
110523             //
110524             // From the lexical classifier's perspective, 'number' is a keyword, and so the word will
110525             // be classified as such.  However, from the syntactic classifier's tree-based perspective
110526             // this is simply an expression with the identifier 'number' on the RHS of the less than
110527             // token.  So the classification will go back to being an identifier.  The moment the user
110528             // types again, number will become a keyword, then an identifier, etc. etc.
110529             //
110530             // To try to avoid this problem, we avoid classifying contextual keywords as keywords
110531             // when the user is potentially typing something generic.  We just can't do a good enough
110532             // job at the lexical level, and so well leave it up to the syntactic classifier to make
110533             // the determination.
110534             //
110535             // In order to determine if the user is potentially typing something generic, we use a
110536             // weak heuristic where we track < and > tokens.  It's a weak heuristic, but should
110537             // work well enough in practice.
110538             var angleBracketStack = 0;
110539             do {
110540                 token = scanner.scan();
110541                 if (!ts.isTrivia(token)) {
110542                     handleToken();
110543                     lastNonTriviaToken = token;
110544                 }
110545                 var end = scanner.getTextPos();
110546                 pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans);
110547                 if (end >= text.length) {
110548                     var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack));
110549                     if (end_1 !== undefined) {
110550                         endOfLineState = end_1;
110551                     }
110552                 }
110553             } while (token !== 1 /* EndOfFileToken */);
110554             function handleToken() {
110555                 switch (token) {
110556                     case 43 /* SlashToken */:
110557                     case 67 /* SlashEqualsToken */:
110558                         if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
110559                             token = 13 /* RegularExpressionLiteral */;
110560                         }
110561                         break;
110562                     case 29 /* LessThanToken */:
110563                         if (lastNonTriviaToken === 75 /* Identifier */) {
110564                             // Could be the start of something generic.  Keep track of that by bumping
110565                             // up the current count of generic contexts we may be in.
110566                             angleBracketStack++;
110567                         }
110568                         break;
110569                     case 31 /* GreaterThanToken */:
110570                         if (angleBracketStack > 0) {
110571                             // If we think we're currently in something generic, then mark that that
110572                             // generic entity is complete.
110573                             angleBracketStack--;
110574                         }
110575                         break;
110576                     case 125 /* AnyKeyword */:
110577                     case 143 /* StringKeyword */:
110578                     case 140 /* NumberKeyword */:
110579                     case 128 /* BooleanKeyword */:
110580                     case 144 /* SymbolKeyword */:
110581                         if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
110582                             // If it looks like we're could be in something generic, don't classify this
110583                             // as a keyword.  We may just get overwritten by the syntactic classifier,
110584                             // causing a noisy experience for the user.
110585                             token = 75 /* Identifier */;
110586                         }
110587                         break;
110588                     case 15 /* TemplateHead */:
110589                         templateStack.push(token);
110590                         break;
110591                     case 18 /* OpenBraceToken */:
110592                         // If we don't have anything on the template stack,
110593                         // then we aren't trying to keep track of a previously scanned template head.
110594                         if (templateStack.length > 0) {
110595                             templateStack.push(token);
110596                         }
110597                         break;
110598                     case 19 /* CloseBraceToken */:
110599                         // If we don't have anything on the template stack,
110600                         // then we aren't trying to keep track of a previously scanned template head.
110601                         if (templateStack.length > 0) {
110602                             var lastTemplateStackToken = ts.lastOrUndefined(templateStack);
110603                             if (lastTemplateStackToken === 15 /* TemplateHead */) {
110604                                 token = scanner.reScanTemplateToken(/* isTaggedTemplate */ false);
110605                                 // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us.
110606                                 if (token === 17 /* TemplateTail */) {
110607                                     templateStack.pop();
110608                                 }
110609                                 else {
110610                                     ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle.");
110611                                 }
110612                             }
110613                             else {
110614                                 ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace");
110615                                 templateStack.pop();
110616                             }
110617                         }
110618                         break;
110619                     default:
110620                         if (!ts.isKeyword(token)) {
110621                             break;
110622                         }
110623                         if (lastNonTriviaToken === 24 /* DotToken */) {
110624                             token = 75 /* Identifier */;
110625                         }
110626                         else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) {
110627                             // We have two keywords in a row.  Only treat the second as a keyword if
110628                             // it's a sequence that could legally occur in the language.  Otherwise
110629                             // treat it as an identifier.  This way, if someone writes "private var"
110630                             // we recognize that 'var' is actually an identifier here.
110631                             token = 75 /* Identifier */;
110632                         }
110633                 }
110634             }
110635             return { endOfLineState: endOfLineState, spans: spans };
110636         }
110637         return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications };
110638     }
110639     ts.createClassifier = createClassifier;
110640     /// We do not have a full parser support to know when we should parse a regex or not
110641     /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where
110642     /// we have a series of divide operator. this list allows us to be more accurate by ruling out
110643     /// locations where a regexp cannot exist.
110644     var noRegexTable = ts.arrayToNumericMap([
110645         75 /* Identifier */,
110646         10 /* StringLiteral */,
110647         8 /* NumericLiteral */,
110648         9 /* BigIntLiteral */,
110649         13 /* RegularExpressionLiteral */,
110650         104 /* ThisKeyword */,
110651         45 /* PlusPlusToken */,
110652         46 /* MinusMinusToken */,
110653         21 /* CloseParenToken */,
110654         23 /* CloseBracketToken */,
110655         19 /* CloseBraceToken */,
110656         106 /* TrueKeyword */,
110657         91 /* FalseKeyword */,
110658     ], function (token) { return token; }, function () { return true; });
110659     function getNewEndOfLineState(scanner, token, lastOnTemplateStack) {
110660         switch (token) {
110661             case 10 /* StringLiteral */: {
110662                 // Check to see if we finished up on a multiline string literal.
110663                 if (!scanner.isUnterminated())
110664                     return undefined;
110665                 var tokenText = scanner.getTokenText();
110666                 var lastCharIndex = tokenText.length - 1;
110667                 var numBackslashes = 0;
110668                 while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) {
110669                     numBackslashes++;
110670                 }
110671                 // If we have an odd number of backslashes, then the multiline string is unclosed
110672                 if ((numBackslashes & 1) === 0)
110673                     return undefined;
110674                 return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */;
110675             }
110676             case 3 /* MultiLineCommentTrivia */:
110677                 // Check to see if the multiline comment was unclosed.
110678                 return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined;
110679             default:
110680                 if (ts.isTemplateLiteralKind(token)) {
110681                     if (!scanner.isUnterminated()) {
110682                         return undefined;
110683                     }
110684                     switch (token) {
110685                         case 17 /* TemplateTail */:
110686                             return 5 /* InTemplateMiddleOrTail */;
110687                         case 14 /* NoSubstitutionTemplateLiteral */:
110688                             return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
110689                         default:
110690                             return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
110691                     }
110692                 }
110693                 return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined;
110694         }
110695     }
110696     function pushEncodedClassification(start, end, offset, classification, result) {
110697         if (classification === 8 /* whiteSpace */) {
110698             // Don't bother with whitespace classifications.  They're not needed.
110699             return;
110700         }
110701         if (start === 0 && offset > 0) {
110702             // We're classifying the first token, and this was a case where we prepended text.
110703             // We should consider the start of this token to be at the start of the original text.
110704             start += offset;
110705         }
110706         var length = end - start;
110707         if (length > 0) {
110708             // All our tokens are in relation to the augmented text.  Move them back to be
110709             // relative to the original text.
110710             result.push(start - offset, length, classification);
110711         }
110712     }
110713     function convertClassificationsToResult(classifications, text) {
110714         var entries = [];
110715         var dense = classifications.spans;
110716         var lastEnd = 0;
110717         for (var i = 0; i < dense.length; i += 3) {
110718             var start = dense[i];
110719             var length_1 = dense[i + 1];
110720             var type = dense[i + 2];
110721             // Make a whitespace entry between the last item and this one.
110722             if (lastEnd >= 0) {
110723                 var whitespaceLength_1 = start - lastEnd;
110724                 if (whitespaceLength_1 > 0) {
110725                     entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
110726                 }
110727             }
110728             entries.push({ length: length_1, classification: convertClassification(type) });
110729             lastEnd = start + length_1;
110730         }
110731         var whitespaceLength = text.length - lastEnd;
110732         if (whitespaceLength > 0) {
110733             entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace });
110734         }
110735         return { entries: entries, finalLexState: classifications.endOfLineState };
110736     }
110737     function convertClassification(type) {
110738         switch (type) {
110739             case 1 /* comment */: return ts.TokenClass.Comment;
110740             case 3 /* keyword */: return ts.TokenClass.Keyword;
110741             case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral;
110742             case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral;
110743             case 5 /* operator */: return ts.TokenClass.Operator;
110744             case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral;
110745             case 8 /* whiteSpace */: return ts.TokenClass.Whitespace;
110746             case 10 /* punctuation */: return ts.TokenClass.Punctuation;
110747             case 2 /* identifier */:
110748             case 11 /* className */:
110749             case 12 /* enumName */:
110750             case 13 /* interfaceName */:
110751             case 14 /* moduleName */:
110752             case 15 /* typeParameterName */:
110753             case 16 /* typeAliasName */:
110754             case 9 /* text */:
110755             case 17 /* parameterName */:
110756                 return ts.TokenClass.Identifier;
110757             default:
110758                 return undefined; // TODO: GH#18217 Debug.assertNever(type);
110759         }
110760     }
110761     /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */
110762     function canFollow(keyword1, keyword2) {
110763         if (!ts.isAccessibilityModifier(keyword1)) {
110764             // Assume any other keyword combination is legal.
110765             // This can be refined in the future if there are more cases we want the classifier to be better at.
110766             return true;
110767         }
110768         switch (keyword2) {
110769             case 131 /* GetKeyword */:
110770             case 142 /* SetKeyword */:
110771             case 129 /* ConstructorKeyword */:
110772             case 120 /* StaticKeyword */:
110773                 return true; // Allow things like "public get", "public constructor" and "public static".
110774             default:
110775                 return false; // Any other keyword following "public" is actually an identifier, not a real keyword.
110776         }
110777     }
110778     function getPrefixFromLexState(lexState) {
110779         // If we're in a string literal, then prepend: "\
110780         // (and a newline).  That way when we lex we'll think we're still in a string literal.
110781         //
110782         // If we're in a multiline comment, then prepend: /*
110783         // (and a newline).  That way when we lex we'll think we're still in a multiline comment.
110784         switch (lexState) {
110785             case 3 /* InDoubleQuoteStringLiteral */:
110786                 return { prefix: "\"\\\n" };
110787             case 2 /* InSingleQuoteStringLiteral */:
110788                 return { prefix: "'\\\n" };
110789             case 1 /* InMultiLineCommentTrivia */:
110790                 return { prefix: "/*\n" };
110791             case 4 /* InTemplateHeadOrNoSubstitutionTemplate */:
110792                 return { prefix: "`\n" };
110793             case 5 /* InTemplateMiddleOrTail */:
110794                 return { prefix: "}\n", pushTemplate: true };
110795             case 6 /* InTemplateSubstitutionPosition */:
110796                 return { prefix: "", pushTemplate: true };
110797             case 0 /* None */:
110798                 return { prefix: "" };
110799             default:
110800                 return ts.Debug.assertNever(lexState);
110801         }
110802     }
110803     function isBinaryExpressionOperatorToken(token) {
110804         switch (token) {
110805             case 41 /* AsteriskToken */:
110806             case 43 /* SlashToken */:
110807             case 44 /* PercentToken */:
110808             case 39 /* PlusToken */:
110809             case 40 /* MinusToken */:
110810             case 47 /* LessThanLessThanToken */:
110811             case 48 /* GreaterThanGreaterThanToken */:
110812             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
110813             case 29 /* LessThanToken */:
110814             case 31 /* GreaterThanToken */:
110815             case 32 /* LessThanEqualsToken */:
110816             case 33 /* GreaterThanEqualsToken */:
110817             case 98 /* InstanceOfKeyword */:
110818             case 97 /* InKeyword */:
110819             case 123 /* AsKeyword */:
110820             case 34 /* EqualsEqualsToken */:
110821             case 35 /* ExclamationEqualsToken */:
110822             case 36 /* EqualsEqualsEqualsToken */:
110823             case 37 /* ExclamationEqualsEqualsToken */:
110824             case 50 /* AmpersandToken */:
110825             case 52 /* CaretToken */:
110826             case 51 /* BarToken */:
110827             case 55 /* AmpersandAmpersandToken */:
110828             case 56 /* BarBarToken */:
110829             case 73 /* BarEqualsToken */:
110830             case 72 /* AmpersandEqualsToken */:
110831             case 74 /* CaretEqualsToken */:
110832             case 69 /* LessThanLessThanEqualsToken */:
110833             case 70 /* GreaterThanGreaterThanEqualsToken */:
110834             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
110835             case 63 /* PlusEqualsToken */:
110836             case 64 /* MinusEqualsToken */:
110837             case 65 /* AsteriskEqualsToken */:
110838             case 67 /* SlashEqualsToken */:
110839             case 68 /* PercentEqualsToken */:
110840             case 62 /* EqualsToken */:
110841             case 27 /* CommaToken */:
110842             case 60 /* QuestionQuestionToken */:
110843                 return true;
110844             default:
110845                 return false;
110846         }
110847     }
110848     function isPrefixUnaryExpressionOperatorToken(token) {
110849         switch (token) {
110850             case 39 /* PlusToken */:
110851             case 40 /* MinusToken */:
110852             case 54 /* TildeToken */:
110853             case 53 /* ExclamationToken */:
110854             case 45 /* PlusPlusToken */:
110855             case 46 /* MinusMinusToken */:
110856                 return true;
110857             default:
110858                 return false;
110859         }
110860     }
110861     function classFromKind(token) {
110862         if (ts.isKeyword(token)) {
110863             return 3 /* keyword */;
110864         }
110865         else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) {
110866             return 5 /* operator */;
110867         }
110868         else if (token >= 18 /* FirstPunctuation */ && token <= 74 /* LastPunctuation */) {
110869             return 10 /* punctuation */;
110870         }
110871         switch (token) {
110872             case 8 /* NumericLiteral */:
110873                 return 4 /* numericLiteral */;
110874             case 9 /* BigIntLiteral */:
110875                 return 25 /* bigintLiteral */;
110876             case 10 /* StringLiteral */:
110877                 return 6 /* stringLiteral */;
110878             case 13 /* RegularExpressionLiteral */:
110879                 return 7 /* regularExpressionLiteral */;
110880             case 7 /* ConflictMarkerTrivia */:
110881             case 3 /* MultiLineCommentTrivia */:
110882             case 2 /* SingleLineCommentTrivia */:
110883                 return 1 /* comment */;
110884             case 5 /* WhitespaceTrivia */:
110885             case 4 /* NewLineTrivia */:
110886                 return 8 /* whiteSpace */;
110887             case 75 /* Identifier */:
110888             default:
110889                 if (ts.isTemplateLiteralKind(token)) {
110890                     return 6 /* stringLiteral */;
110891                 }
110892                 return 2 /* identifier */;
110893         }
110894     }
110895     /* @internal */
110896     function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
110897         return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span));
110898     }
110899     ts.getSemanticClassifications = getSemanticClassifications;
110900     function checkForClassificationCancellation(cancellationToken, kind) {
110901         // We don't want to actually call back into our host on every node to find out if we've
110902         // been canceled.  That would be an enormous amount of chattyness, along with the all
110903         // the overhead of marshalling the data to/from the host.  So instead we pick a few
110904         // reasonable node kinds to bother checking on.  These node kinds represent high level
110905         // constructs that we would expect to see commonly, but just at a far less frequent
110906         // interval.
110907         //
110908         // For example, in checker.ts (around 750k) we only have around 600 of these constructs.
110909         // That means we're calling back into the host around every 1.2k of the file we process.
110910         // Lib.d.ts has similar numbers.
110911         switch (kind) {
110912             case 249 /* ModuleDeclaration */:
110913             case 245 /* ClassDeclaration */:
110914             case 246 /* InterfaceDeclaration */:
110915             case 244 /* FunctionDeclaration */:
110916                 cancellationToken.throwIfCancellationRequested();
110917         }
110918     }
110919     /* @internal */
110920     function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
110921         var spans = [];
110922         sourceFile.forEachChild(function cb(node) {
110923             // Only walk into nodes that intersect the requested span.
110924             if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
110925                 return;
110926             }
110927             checkForClassificationCancellation(cancellationToken, node.kind);
110928             // Only bother calling into the typechecker if this is an identifier that
110929             // could possibly resolve to a type name.  This makes classification run
110930             // in a third of the time it would normally take.
110931             if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) {
110932                 var symbol = typeChecker.getSymbolAtLocation(node);
110933                 var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker);
110934                 if (type) {
110935                     pushClassification(node.getStart(sourceFile), node.getEnd(), type);
110936                 }
110937             }
110938             node.forEachChild(cb);
110939         });
110940         return { spans: spans, endOfLineState: 0 /* None */ };
110941         function pushClassification(start, end, type) {
110942             var length = end - start;
110943             ts.Debug.assert(length > 0, "Classification had non-positive length of " + length);
110944             spans.push(start);
110945             spans.push(length);
110946             spans.push(type);
110947         }
110948     }
110949     ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications;
110950     function classifySymbol(symbol, meaningAtPosition, checker) {
110951         var flags = symbol.getFlags();
110952         if ((flags & 2885600 /* Classifiable */) === 0 /* None */) {
110953             return undefined;
110954         }
110955         else if (flags & 32 /* Class */) {
110956             return 11 /* className */;
110957         }
110958         else if (flags & 384 /* Enum */) {
110959             return 12 /* enumName */;
110960         }
110961         else if (flags & 524288 /* TypeAlias */) {
110962             return 16 /* typeAliasName */;
110963         }
110964         else if (flags & 1536 /* Module */) {
110965             // Only classify a module as such if
110966             //  - It appears in a namespace context.
110967             //  - There exists a module declaration which actually impacts the value side.
110968             return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined;
110969         }
110970         else if (flags & 2097152 /* Alias */) {
110971             return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker);
110972         }
110973         else if (meaningAtPosition & 2 /* Type */) {
110974             return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined;
110975         }
110976         else {
110977             return undefined;
110978         }
110979     }
110980     /** Returns true if there exists a module that introduces entities on the value side. */
110981     function hasValueSideModule(symbol) {
110982         return ts.some(symbol.declarations, function (declaration) {
110983             return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */;
110984         });
110985     }
110986     function getClassificationTypeName(type) {
110987         switch (type) {
110988             case 1 /* comment */: return "comment" /* comment */;
110989             case 2 /* identifier */: return "identifier" /* identifier */;
110990             case 3 /* keyword */: return "keyword" /* keyword */;
110991             case 4 /* numericLiteral */: return "number" /* numericLiteral */;
110992             case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */;
110993             case 5 /* operator */: return "operator" /* operator */;
110994             case 6 /* stringLiteral */: return "string" /* stringLiteral */;
110995             case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */;
110996             case 9 /* text */: return "text" /* text */;
110997             case 10 /* punctuation */: return "punctuation" /* punctuation */;
110998             case 11 /* className */: return "class name" /* className */;
110999             case 12 /* enumName */: return "enum name" /* enumName */;
111000             case 13 /* interfaceName */: return "interface name" /* interfaceName */;
111001             case 14 /* moduleName */: return "module name" /* moduleName */;
111002             case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */;
111003             case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */;
111004             case 17 /* parameterName */: return "parameter name" /* parameterName */;
111005             case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */;
111006             case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */;
111007             case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */;
111008             case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */;
111009             case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */;
111010             case 23 /* jsxText */: return "jsx text" /* jsxText */;
111011             case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */;
111012             default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type);
111013         }
111014     }
111015     function convertClassificationsToSpans(classifications) {
111016         ts.Debug.assert(classifications.spans.length % 3 === 0);
111017         var dense = classifications.spans;
111018         var result = [];
111019         for (var i = 0; i < dense.length; i += 3) {
111020             result.push({
111021                 textSpan: ts.createTextSpan(dense[i], dense[i + 1]),
111022                 classificationType: getClassificationTypeName(dense[i + 2])
111023             });
111024         }
111025         return result;
111026     }
111027     /* @internal */
111028     function getSyntacticClassifications(cancellationToken, sourceFile, span) {
111029         return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span));
111030     }
111031     ts.getSyntacticClassifications = getSyntacticClassifications;
111032     /* @internal */
111033     function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) {
111034         var spanStart = span.start;
111035         var spanLength = span.length;
111036         // Make a scanner we can get trivia from.
111037         var triviaScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
111038         var mergeConflictScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
111039         var result = [];
111040         processElement(sourceFile);
111041         return { spans: result, endOfLineState: 0 /* None */ };
111042         function pushClassification(start, length, type) {
111043             result.push(start);
111044             result.push(length);
111045             result.push(type);
111046         }
111047         function classifyLeadingTriviaAndGetTokenStart(token) {
111048             triviaScanner.setTextPos(token.pos);
111049             while (true) {
111050                 var start = triviaScanner.getTextPos();
111051                 // only bother scanning if we have something that could be trivia.
111052                 if (!ts.couldStartTrivia(sourceFile.text, start)) {
111053                     return start;
111054                 }
111055                 var kind = triviaScanner.scan();
111056                 var end = triviaScanner.getTextPos();
111057                 var width = end - start;
111058                 // The moment we get something that isn't trivia, then stop processing.
111059                 if (!ts.isTrivia(kind)) {
111060                     return start;
111061                 }
111062                 switch (kind) {
111063                     case 4 /* NewLineTrivia */:
111064                     case 5 /* WhitespaceTrivia */:
111065                         // Don't bother with newlines/whitespace.
111066                         continue;
111067                     case 2 /* SingleLineCommentTrivia */:
111068                     case 3 /* MultiLineCommentTrivia */:
111069                         // Only bother with the trivia if it at least intersects the span of interest.
111070                         classifyComment(token, kind, start, width);
111071                         // Classifying a comment might cause us to reuse the trivia scanner
111072                         // (because of jsdoc comments).  So after we classify the comment make
111073                         // sure we set the scanner position back to where it needs to be.
111074                         triviaScanner.setTextPos(end);
111075                         continue;
111076                     case 7 /* ConflictMarkerTrivia */:
111077                         var text = sourceFile.text;
111078                         var ch = text.charCodeAt(start);
111079                         // for the <<<<<<< and >>>>>>> markers, we just add them in as comments
111080                         // in the classification stream.
111081                         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
111082                             pushClassification(start, width, 1 /* comment */);
111083                             continue;
111084                         }
111085                         // for the ||||||| and ======== markers, add a comment for the first line,
111086                         // and then lex all subsequent lines up until the end of the conflict marker.
111087                         ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
111088                         classifyDisabledMergeCode(text, start, end);
111089                         break;
111090                     case 6 /* ShebangTrivia */:
111091                         // TODO: Maybe we should classify these.
111092                         break;
111093                     default:
111094                         ts.Debug.assertNever(kind);
111095                 }
111096             }
111097         }
111098         function classifyComment(token, kind, start, width) {
111099             if (kind === 3 /* MultiLineCommentTrivia */) {
111100                 // See if this is a doc comment.  If so, we'll classify certain portions of it
111101                 // specially.
111102                 var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width);
111103                 if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) {
111104                     // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]`
111105                     docCommentAndDiagnostics.jsDoc.parent = token;
111106                     classifyJSDocComment(docCommentAndDiagnostics.jsDoc);
111107                     return;
111108                 }
111109             }
111110             else if (kind === 2 /* SingleLineCommentTrivia */) {
111111                 if (tryClassifyTripleSlashComment(start, width)) {
111112                     return;
111113                 }
111114             }
111115             // Simple comment.  Just add as is.
111116             pushCommentRange(start, width);
111117         }
111118         function pushCommentRange(start, width) {
111119             pushClassification(start, width, 1 /* comment */);
111120         }
111121         function classifyJSDocComment(docComment) {
111122             var pos = docComment.pos;
111123             if (docComment.tags) {
111124                 for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) {
111125                     var tag = _a[_i];
111126                     // As we walk through each tag, classify the portion of text from the end of
111127                     // the last tag (or the start of the entire doc comment) as 'comment'.
111128                     if (tag.pos !== pos) {
111129                         pushCommentRange(pos, tag.pos - pos);
111130                     }
111131                     pushClassification(tag.pos, 1, 10 /* punctuation */); // "@"
111132                     pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
111133                     pos = tag.tagName.end;
111134                     switch (tag.kind) {
111135                         case 317 /* JSDocParameterTag */:
111136                             processJSDocParameterTag(tag);
111137                             break;
111138                         case 321 /* JSDocTemplateTag */:
111139                             processJSDocTemplateTag(tag);
111140                             pos = tag.end;
111141                             break;
111142                         case 320 /* JSDocTypeTag */:
111143                             processElement(tag.typeExpression);
111144                             pos = tag.end;
111145                             break;
111146                         case 318 /* JSDocReturnTag */:
111147                             processElement(tag.typeExpression);
111148                             pos = tag.end;
111149                             break;
111150                     }
111151                 }
111152             }
111153             if (pos !== docComment.end) {
111154                 pushCommentRange(pos, docComment.end - pos);
111155             }
111156             return;
111157             function processJSDocParameterTag(tag) {
111158                 if (tag.isNameFirst) {
111159                     pushCommentRange(pos, tag.name.pos - pos);
111160                     pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
111161                     pos = tag.name.end;
111162                 }
111163                 if (tag.typeExpression) {
111164                     pushCommentRange(pos, tag.typeExpression.pos - pos);
111165                     processElement(tag.typeExpression);
111166                     pos = tag.typeExpression.end;
111167                 }
111168                 if (!tag.isNameFirst) {
111169                     pushCommentRange(pos, tag.name.pos - pos);
111170                     pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
111171                     pos = tag.name.end;
111172                 }
111173             }
111174         }
111175         function tryClassifyTripleSlashComment(start, width) {
111176             var tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/im;
111177             var attributeRegex = /(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/img;
111178             var text = sourceFile.text.substr(start, width);
111179             var match = tripleSlashXMLCommentRegEx.exec(text);
111180             if (!match) {
111181                 return false;
111182             }
111183             // Limiting classification to exactly the elements and attributes
111184             // defined in `ts.commentPragmas` would be excessive, but we can avoid
111185             // some obvious false positives (e.g. in XML-like doc comments) by
111186             // checking the element name.
111187             // eslint-disable-next-line no-in-operator
111188             if (!match[3] || !(match[3] in ts.commentPragmas)) {
111189                 return false;
111190             }
111191             var pos = start;
111192             pushCommentRange(pos, match[1].length); // ///
111193             pos += match[1].length;
111194             pushClassification(pos, match[2].length, 10 /* punctuation */); // <
111195             pos += match[2].length;
111196             pushClassification(pos, match[3].length, 21 /* jsxSelfClosingTagName */); // element name
111197             pos += match[3].length;
111198             var attrText = match[4];
111199             var attrPos = pos;
111200             while (true) {
111201                 var attrMatch = attributeRegex.exec(attrText);
111202                 if (!attrMatch) {
111203                     break;
111204                 }
111205                 var newAttrPos = pos + attrMatch.index;
111206                 if (newAttrPos > attrPos) {
111207                     pushCommentRange(attrPos, newAttrPos - attrPos);
111208                     attrPos = newAttrPos;
111209                 }
111210                 pushClassification(attrPos, attrMatch[1].length, 22 /* jsxAttribute */); // attribute name
111211                 attrPos += attrMatch[1].length;
111212                 if (attrMatch[2].length) {
111213                     pushCommentRange(attrPos, attrMatch[2].length); // whitespace
111214                     attrPos += attrMatch[2].length;
111215                 }
111216                 pushClassification(attrPos, attrMatch[3].length, 5 /* operator */); // =
111217                 attrPos += attrMatch[3].length;
111218                 if (attrMatch[4].length) {
111219                     pushCommentRange(attrPos, attrMatch[4].length); // whitespace
111220                     attrPos += attrMatch[4].length;
111221                 }
111222                 pushClassification(attrPos, attrMatch[5].length, 24 /* jsxAttributeStringLiteralValue */); // attribute value
111223                 attrPos += attrMatch[5].length;
111224             }
111225             pos += match[4].length;
111226             if (pos > attrPos) {
111227                 pushCommentRange(attrPos, pos - attrPos);
111228             }
111229             if (match[5]) {
111230                 pushClassification(pos, match[5].length, 10 /* punctuation */); // />
111231                 pos += match[5].length;
111232             }
111233             var end = start + width;
111234             if (pos < end) {
111235                 pushCommentRange(pos, end - pos);
111236             }
111237             return true;
111238         }
111239         function processJSDocTemplateTag(tag) {
111240             for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) {
111241                 var child = _a[_i];
111242                 processElement(child);
111243             }
111244         }
111245         function classifyDisabledMergeCode(text, start, end) {
111246             // Classify the line that the ||||||| or ======= marker is on as a comment.
111247             // Then just lex all further tokens and add them to the result.
111248             var i;
111249             for (i = start; i < end; i++) {
111250                 if (ts.isLineBreak(text.charCodeAt(i))) {
111251                     break;
111252                 }
111253             }
111254             pushClassification(start, i - start, 1 /* comment */);
111255             mergeConflictScanner.setTextPos(i);
111256             while (mergeConflictScanner.getTextPos() < end) {
111257                 classifyDisabledCodeToken();
111258             }
111259         }
111260         function classifyDisabledCodeToken() {
111261             var start = mergeConflictScanner.getTextPos();
111262             var tokenKind = mergeConflictScanner.scan();
111263             var end = mergeConflictScanner.getTextPos();
111264             var type = classifyTokenType(tokenKind);
111265             if (type) {
111266                 pushClassification(start, end - start, type);
111267             }
111268         }
111269         /**
111270          * Returns true if node should be treated as classified and no further processing is required.
111271          * False will mean that node is not classified and traverse routine should recurse into node contents.
111272          */
111273         function tryClassifyNode(node) {
111274             if (ts.isJSDoc(node)) {
111275                 return true;
111276             }
111277             if (ts.nodeIsMissing(node)) {
111278                 return true;
111279             }
111280             var classifiedElementName = tryClassifyJsxElementName(node);
111281             if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) {
111282                 return false;
111283             }
111284             var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node);
111285             var tokenWidth = node.end - tokenStart;
111286             ts.Debug.assert(tokenWidth >= 0);
111287             if (tokenWidth > 0) {
111288                 var type = classifiedElementName || classifyTokenType(node.kind, node);
111289                 if (type) {
111290                     pushClassification(tokenStart, tokenWidth, type);
111291                 }
111292             }
111293             return true;
111294         }
111295         function tryClassifyJsxElementName(token) {
111296             switch (token.parent && token.parent.kind) {
111297                 case 268 /* JsxOpeningElement */:
111298                     if (token.parent.tagName === token) {
111299                         return 19 /* jsxOpenTagName */;
111300                     }
111301                     break;
111302                 case 269 /* JsxClosingElement */:
111303                     if (token.parent.tagName === token) {
111304                         return 20 /* jsxCloseTagName */;
111305                     }
111306                     break;
111307                 case 267 /* JsxSelfClosingElement */:
111308                     if (token.parent.tagName === token) {
111309                         return 21 /* jsxSelfClosingTagName */;
111310                     }
111311                     break;
111312                 case 273 /* JsxAttribute */:
111313                     if (token.parent.name === token) {
111314                         return 22 /* jsxAttribute */;
111315                     }
111316                     break;
111317             }
111318             return undefined;
111319         }
111320         // for accurate classification, the actual token should be passed in.  however, for
111321         // cases like 'disabled merge code' classification, we just get the token kind and
111322         // classify based on that instead.
111323         function classifyTokenType(tokenKind, token) {
111324             if (ts.isKeyword(tokenKind)) {
111325                 return 3 /* keyword */;
111326             }
111327             // Special case `<` and `>`: If they appear in a generic context they are punctuation,
111328             // not operators.
111329             if (tokenKind === 29 /* LessThanToken */ || tokenKind === 31 /* GreaterThanToken */) {
111330                 // If the node owning the token has a type argument list or type parameter list, then
111331                 // we can effectively assume that a '<' and '>' belong to those lists.
111332                 if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) {
111333                     return 10 /* punctuation */;
111334                 }
111335             }
111336             if (ts.isPunctuation(tokenKind)) {
111337                 if (token) {
111338                     var parent = token.parent;
111339                     if (tokenKind === 62 /* EqualsToken */) {
111340                         // the '=' in a variable declaration is special cased here.
111341                         if (parent.kind === 242 /* VariableDeclaration */ ||
111342                             parent.kind === 159 /* PropertyDeclaration */ ||
111343                             parent.kind === 156 /* Parameter */ ||
111344                             parent.kind === 273 /* JsxAttribute */) {
111345                             return 5 /* operator */;
111346                         }
111347                     }
111348                     if (parent.kind === 209 /* BinaryExpression */ ||
111349                         parent.kind === 207 /* PrefixUnaryExpression */ ||
111350                         parent.kind === 208 /* PostfixUnaryExpression */ ||
111351                         parent.kind === 210 /* ConditionalExpression */) {
111352                         return 5 /* operator */;
111353                     }
111354                 }
111355                 return 10 /* punctuation */;
111356             }
111357             else if (tokenKind === 8 /* NumericLiteral */) {
111358                 return 4 /* numericLiteral */;
111359             }
111360             else if (tokenKind === 9 /* BigIntLiteral */) {
111361                 return 25 /* bigintLiteral */;
111362             }
111363             else if (tokenKind === 10 /* StringLiteral */) {
111364                 return token && token.parent.kind === 273 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
111365             }
111366             else if (tokenKind === 13 /* RegularExpressionLiteral */) {
111367                 // TODO: we should get another classification type for these literals.
111368                 return 6 /* stringLiteral */;
111369             }
111370             else if (ts.isTemplateLiteralKind(tokenKind)) {
111371                 // TODO (drosen): we should *also* get another classification type for these literals.
111372                 return 6 /* stringLiteral */;
111373             }
111374             else if (tokenKind === 11 /* JsxText */) {
111375                 return 23 /* jsxText */;
111376             }
111377             else if (tokenKind === 75 /* Identifier */) {
111378                 if (token) {
111379                     switch (token.parent.kind) {
111380                         case 245 /* ClassDeclaration */:
111381                             if (token.parent.name === token) {
111382                                 return 11 /* className */;
111383                             }
111384                             return;
111385                         case 155 /* TypeParameter */:
111386                             if (token.parent.name === token) {
111387                                 return 15 /* typeParameterName */;
111388                             }
111389                             return;
111390                         case 246 /* InterfaceDeclaration */:
111391                             if (token.parent.name === token) {
111392                                 return 13 /* interfaceName */;
111393                             }
111394                             return;
111395                         case 248 /* EnumDeclaration */:
111396                             if (token.parent.name === token) {
111397                                 return 12 /* enumName */;
111398                             }
111399                             return;
111400                         case 249 /* ModuleDeclaration */:
111401                             if (token.parent.name === token) {
111402                                 return 14 /* moduleName */;
111403                             }
111404                             return;
111405                         case 156 /* Parameter */:
111406                             if (token.parent.name === token) {
111407                                 return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */;
111408                             }
111409                             return;
111410                     }
111411                 }
111412                 return 2 /* identifier */;
111413             }
111414         }
111415         function processElement(element) {
111416             if (!element) {
111417                 return;
111418             }
111419             // Ignore nodes that don't intersect the original span to classify.
111420             if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
111421                 checkForClassificationCancellation(cancellationToken, element.kind);
111422                 for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) {
111423                     var child = _a[_i];
111424                     if (!tryClassifyNode(child)) {
111425                         // Recurse into our child nodes.
111426                         processElement(child);
111427                     }
111428                 }
111429             }
111430         }
111431     }
111432     ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications;
111433 })(ts || (ts = {}));
111434 /* @internal */
111435 var ts;
111436 (function (ts) {
111437     var Completions;
111438     (function (Completions) {
111439         var StringCompletions;
111440         (function (StringCompletions) {
111441             function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) {
111442                 if (ts.isInReferenceComment(sourceFile, position)) {
111443                     var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host);
111444                     return entries && convertPathCompletions(entries);
111445                 }
111446                 if (ts.isInString(sourceFile, position, contextToken)) {
111447                     if (!contextToken || !ts.isStringLiteralLike(contextToken))
111448                         return undefined;
111449                     var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host);
111450                     return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences);
111451                 }
111452             }
111453             StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions;
111454             function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) {
111455                 if (completion === undefined) {
111456                     return undefined;
111457                 }
111458                 switch (completion.kind) {
111459                     case 0 /* Paths */:
111460                         return convertPathCompletions(completion.paths);
111461                     case 1 /* Properties */: {
111462                         var entries = [];
111463                         Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
111464                         return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
111465                     }
111466                     case 2 /* Types */: {
111467                         var entries = completion.types.map(function (type) { return ({
111468                             name: type.value,
111469                             kindModifiers: "" /* none */,
111470                             kind: "string" /* string */,
111471                             sortText: "0",
111472                             replacementSpan: ts.getReplacementSpanForContextToken(contextToken)
111473                         }); });
111474                         return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries };
111475                     }
111476                     default:
111477                         return ts.Debug.assertNever(completion);
111478                 }
111479             }
111480             function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) {
111481                 if (!contextToken || !ts.isStringLiteralLike(contextToken))
111482                     return undefined;
111483                 var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host);
111484                 return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken);
111485             }
111486             StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails;
111487             function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) {
111488                 switch (completion.kind) {
111489                     case 0 /* Paths */: {
111490                         var match = ts.find(completion.paths, function (p) { return p.name === name; });
111491                         return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]);
111492                     }
111493                     case 1 /* Properties */: {
111494                         var match = ts.find(completion.symbols, function (s) { return s.name === name; });
111495                         return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken);
111496                     }
111497                     case 2 /* Types */:
111498                         return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined;
111499                     default:
111500                         return ts.Debug.assertNever(completion);
111501                 }
111502             }
111503             function convertPathCompletions(pathCompletions) {
111504                 var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment.
111505                 var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of.
111506                 var entries = pathCompletions.map(function (_a) {
111507                     var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension;
111508                     return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: Completions.SortText.LocationPriority, replacementSpan: span });
111509                 });
111510                 return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
111511             }
111512             function kindModifiersFromExtension(extension) {
111513                 switch (extension) {
111514                     case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */;
111515                     case ".js" /* Js */: return ".js" /* jsModifier */;
111516                     case ".json" /* Json */: return ".json" /* jsonModifier */;
111517                     case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
111518                     case ".ts" /* Ts */: return ".ts" /* tsModifier */;
111519                     case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
111520                     case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
111521                     case undefined: return "" /* none */;
111522                     default:
111523                         return ts.Debug.assertNever(extension);
111524                 }
111525             }
111526             var StringLiteralCompletionKind;
111527             (function (StringLiteralCompletionKind) {
111528                 StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths";
111529                 StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties";
111530                 StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types";
111531             })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {}));
111532             function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) {
111533                 var parent = node.parent;
111534                 switch (parent.kind) {
111535                     case 187 /* LiteralType */:
111536                         switch (parent.parent.kind) {
111537                             case 169 /* TypeReference */:
111538                                 return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false };
111539                             case 185 /* IndexedAccessType */:
111540                                 // Get all apparent property names
111541                                 // i.e. interface Foo {
111542                                 //          foo: string;
111543                                 //          bar: string;
111544                                 //      }
111545                                 //      let x: Foo["/*completion position*/"]
111546                                 return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType));
111547                             case 188 /* ImportType */:
111548                                 return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
111549                             case 178 /* UnionType */: {
111550                                 if (!ts.isTypeReferenceNode(parent.parent.parent))
111551                                     return undefined;
111552                                 var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent);
111553                                 var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); });
111554                                 return { kind: 2 /* Types */, types: types, isNewIdentifier: false };
111555                             }
111556                             default:
111557                                 return undefined;
111558                         }
111559                     case 281 /* PropertyAssignment */:
111560                         if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) {
111561                             // Get quoted name of properties of the object literal expression
111562                             // i.e. interface ConfigFiles {
111563                             //          'jspm:dev': string
111564                             //      }
111565                             //      let files: ConfigFiles = {
111566                             //          '/*completion position*/'
111567                             //      }
111568                             //
111569                             //      function foo(c: ConfigFiles) {}
111570                             //      foo({
111571                             //          '/*completion position*/'
111572                             //      });
111573                             return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent));
111574                         }
111575                         return fromContextualType();
111576                     case 195 /* ElementAccessExpression */: {
111577                         var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression;
111578                         if (node === argumentExpression) {
111579                             // Get all names of properties on the expression
111580                             // i.e. interface A {
111581                             //      'prop1': string
111582                             // }
111583                             // let a: A;
111584                             // a['/*completion position*/']
111585                             return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression));
111586                         }
111587                         return undefined;
111588                     }
111589                     case 196 /* CallExpression */:
111590                     case 197 /* NewExpression */:
111591                         if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) {
111592                             var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile);
111593                             // Get string literal completions from specialized signatures of the target
111594                             // i.e. declare function f(a: 'A');
111595                             // f("/*completion position*/")
111596                             return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType();
111597                         }
111598                     // falls through (is `require("")` or `import("")`)
111599                     case 254 /* ImportDeclaration */:
111600                     case 260 /* ExportDeclaration */:
111601                     case 265 /* ExternalModuleReference */:
111602                         // Get all known external module names or complete a path to a module
111603                         // i.e. import * as ns from "/*completion position*/";
111604                         //      var y = import("/*completion position*/");
111605                         //      import x = require("/*completion position*/");
111606                         //      var y = require("/*completion position*/");
111607                         //      export * from "/*completion position*/";
111608                         return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
111609                     default:
111610                         return fromContextualType();
111611                 }
111612                 function fromContextualType() {
111613                     // Get completion for string literal from string literal type
111614                     // i.e. var x: "hi" | "hello" = "/*completion position*/"
111615                     return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false };
111616                 }
111617             }
111618             function getAlreadyUsedTypesInStringLiteralUnion(union, current) {
111619                 return ts.mapDefined(union.types, function (type) {
111620                     return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined;
111621                 });
111622             }
111623             function getStringLiteralCompletionsFromSignature(argumentInfo, checker) {
111624                 var isNewIdentifier = false;
111625                 var uniques = ts.createMap();
111626                 var candidates = [];
111627                 checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount);
111628                 var types = ts.flatMap(candidates, function (candidate) {
111629                     if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length)
111630                         return;
111631                     var type = checker.getParameterType(candidate, argumentInfo.argumentIndex);
111632                     isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */);
111633                     return getStringLiteralTypes(type, uniques);
111634                 });
111635                 return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier };
111636             }
111637             function stringLiteralCompletionsFromProperties(type) {
111638                 return type && {
111639                     kind: 1 /* Properties */,
111640                     symbols: type.getApparentProperties().filter(function (prop) {
111641                         return !ts.isPrivateIdentifierPropertyDeclaration(ts.isTransientSymbol(prop) && prop.syntheticOrigin ? prop.syntheticOrigin.valueDeclaration : prop.valueDeclaration);
111642                     }),
111643                     hasIndexSignature: ts.hasIndexSignature(type)
111644                 };
111645             }
111646             function getStringLiteralTypes(type, uniques) {
111647                 if (uniques === void 0) { uniques = ts.createMap(); }
111648                 if (!type)
111649                     return ts.emptyArray;
111650                 type = ts.skipConstraint(type);
111651                 return type.isUnion() ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) :
111652                     type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) ? [type] : ts.emptyArray;
111653             }
111654             function nameAndKind(name, kind, extension) {
111655                 return { name: name, kind: kind, extension: extension };
111656             }
111657             function directoryResult(name) {
111658                 return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined);
111659             }
111660             function addReplacementSpans(text, textStart, names) {
111661                 var span = getDirectoryFragmentTextSpan(text, textStart);
111662                 return names.map(function (_a) {
111663                     var name = _a.name, kind = _a.kind, extension = _a.extension;
111664                     return ({ name: name, kind: kind, extension: extension, span: span });
111665                 });
111666             }
111667             function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) {
111668                 return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker));
111669             }
111670             function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) {
111671                 var literalValue = ts.normalizeSlashes(node.text);
111672                 var scriptPath = sourceFile.path;
111673                 var scriptDirectory = ts.getDirectoryPath(scriptPath);
111674                 return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue))
111675                     ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath)
111676                     : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
111677             }
111678             function getExtensionOptions(compilerOptions, includeExtensions) {
111679                 if (includeExtensions === void 0) { includeExtensions = false; }
111680                 return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions };
111681             }
111682             function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) {
111683                 var extensionOptions = getExtensionOptions(compilerOptions);
111684                 if (compilerOptions.rootDirs) {
111685                     return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath);
111686                 }
111687                 else {
111688                     return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath);
111689                 }
111690             }
111691             function getSupportedExtensionsForModuleResolution(compilerOptions) {
111692                 var extensions = ts.getSupportedExtensions(compilerOptions);
111693                 return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
111694                     extensions.concat(".json" /* Json */) :
111695                     extensions;
111696             }
111697             /**
111698              * Takes a script path and returns paths for all potential folders that could be merged with its
111699              * containing folder via the "rootDirs" compiler option
111700              */
111701             function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
111702                 // Make all paths absolute/normalized if they are not already
111703                 rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
111704                 // Determine the path to the directory containing the script relative to the root directory it is contained within
111705                 var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) {
111706                     return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined;
111707                 }); // TODO: GH#18217
111708                 // Now find a path for each potential directory that is to be merged with the one containing the script
111709                 return ts.deduplicate(__spreadArrays(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), [scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
111710             }
111711             function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
111712                 var basePath = compilerOptions.project || host.getCurrentDirectory();
111713                 var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
111714                 var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
111715                 return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); });
111716             }
111717             /**
111718              * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
111719              */
111720             function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) {
111721                 var extensions = _a.extensions, includeExtensions = _a.includeExtensions;
111722                 if (result === void 0) { result = []; }
111723                 if (fragment === undefined) {
111724                     fragment = "";
111725                 }
111726                 fragment = ts.normalizeSlashes(fragment);
111727                 /**
111728                  * Remove the basename from the path. Note that we don't use the basename to filter completions;
111729                  * the client is responsible for refining completions.
111730                  */
111731                 if (!ts.hasTrailingDirectorySeparator(fragment)) {
111732                     fragment = ts.getDirectoryPath(fragment);
111733                 }
111734                 if (fragment === "") {
111735                     fragment = "." + ts.directorySeparator;
111736                 }
111737                 fragment = ts.ensureTrailingDirectorySeparator(fragment);
111738                 // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths
111739                 var absolutePath = ts.resolvePath(scriptPath, fragment);
111740                 var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath);
111741                 var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
111742                 if (!ts.tryDirectoryExists(host, baseDirectory))
111743                     return result;
111744                 // Enumerate the available files if possible
111745                 var files = ts.tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]);
111746                 if (files) {
111747                     /**
111748                      * Multiple file entries might map to the same truncated name once we remove extensions
111749                      * (happens iff includeExtensions === false)so we use a set-like data structure. Eg:
111750                      *
111751                      * both foo.ts and foo.tsx become foo
111752                      */
111753                     var foundFiles = ts.createMap(); // maps file to its extension
111754                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
111755                         var filePath = files_1[_i];
111756                         filePath = ts.normalizePath(filePath);
111757                         if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
111758                             continue;
111759                         }
111760                         var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
111761                         foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath));
111762                     }
111763                     foundFiles.forEach(function (ext, foundFile) {
111764                         result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext));
111765                     });
111766                 }
111767                 // If possible, get folder completion as well
111768                 var directories = ts.tryGetDirectories(host, baseDirectory);
111769                 if (directories) {
111770                     for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) {
111771                         var directory = directories_1[_b];
111772                         var directoryName = ts.getBaseFileName(ts.normalizePath(directory));
111773                         if (directoryName !== "@types") {
111774                             result.push(directoryResult(directoryName));
111775                         }
111776                     }
111777                 }
111778                 // check for a version redirect
111779                 var packageJsonPath = ts.findPackageJson(baseDirectory, host);
111780                 if (packageJsonPath) {
111781                     var packageJson = ts.readJson(packageJsonPath, host);
111782                     var typesVersions = packageJson.typesVersions;
111783                     if (typeof typesVersions === "object") {
111784                         var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions);
111785                         var versionPaths = versionResult && versionResult.paths;
111786                         var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length);
111787                         if (versionPaths) {
111788                             addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host);
111789                         }
111790                     }
111791                 }
111792                 return result;
111793             }
111794             function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) {
111795                 for (var path in paths) {
111796                     if (!ts.hasProperty(paths, path))
111797                         continue;
111798                     var patterns = paths[path];
111799                     if (patterns) {
111800                         var _loop_1 = function (name, kind, extension) {
111801                             // Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
111802                             if (!result.some(function (entry) { return entry.name === name; })) {
111803                                 result.push(nameAndKind(name, kind, extension));
111804                             }
111805                         };
111806                         for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
111807                             var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
111808                             _loop_1(name, kind, extension);
111809                         }
111810                     }
111811                 }
111812             }
111813             /**
111814              * Check all of the declared modules and those in node modules. Possible sources of modules:
111815              *      Modules that are found by the type checker
111816              *      Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option)
111817              *      Modules from node_modules (i.e. those listed in package.json)
111818              *          This includes all files that are found in node_modules/moduleName/ with acceptable file extensions
111819              */
111820             function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) {
111821                 var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
111822                 var result = [];
111823                 var extensionOptions = getExtensionOptions(compilerOptions);
111824                 if (baseUrl) {
111825                     var projectDir = compilerOptions.project || host.getCurrentDirectory();
111826                     var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl));
111827                     getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result);
111828                     if (paths) {
111829                         addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host);
111830                     }
111831                 }
111832                 var fragmentDirectory = getFragmentDirectory(fragment);
111833                 for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) {
111834                     var ambientName = _a[_i];
111835                     result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined));
111836                 }
111837                 getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result);
111838                 if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) {
111839                     // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies.
111840                     // (But do if we didn't find anything, e.g. 'package.json' missing.)
111841                     var foundGlobal = false;
111842                     if (fragmentDirectory === undefined) {
111843                         var _loop_2 = function (moduleName) {
111844                             if (!result.some(function (entry) { return entry.name === moduleName; })) {
111845                                 foundGlobal = true;
111846                                 result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
111847                             }
111848                         };
111849                         for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
111850                             var moduleName = _c[_b];
111851                             _loop_2(moduleName);
111852                         }
111853                     }
111854                     if (!foundGlobal) {
111855                         ts.forEachAncestorDirectory(scriptPath, function (ancestor) {
111856                             var nodeModules = ts.combinePaths(ancestor, "node_modules");
111857                             if (ts.tryDirectoryExists(host, nodeModules)) {
111858                                 getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result);
111859                             }
111860                         });
111861                     }
111862                 }
111863                 return result;
111864             }
111865             function getFragmentDirectory(fragment) {
111866                 return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
111867             }
111868             function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) {
111869                 if (!ts.endsWith(path, "*")) {
111870                     // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion.
111871                     return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray;
111872                 }
111873                 var pathPrefix = path.slice(0, path.length - 1);
111874                 var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix);
111875                 return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) {
111876                     return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host);
111877                 });
111878                 function justPathMappingName(name) {
111879                     return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray;
111880                 }
111881             }
111882             function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) {
111883                 if (!host.readDirectory) {
111884                     return undefined;
111885                 }
111886                 var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined;
111887                 if (!parsed) {
111888                     return undefined;
111889                 }
111890                 // The prefix has two effective parts: the directory path and the base component after the filepath that is not a
111891                 // full directory component. For example: directory/path/of/prefix/base*
111892                 var normalizedPrefix = ts.resolvePath(parsed.prefix);
111893                 var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix);
111894                 var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix);
111895                 var fragmentHasPath = containsSlash(fragment);
111896                 var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
111897                 // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call
111898                 var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
111899                 var normalizedSuffix = ts.normalizePath(parsed.suffix);
111900                 // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
111901                 var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory));
111902                 var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase;
111903                 // If we have a suffix, then we need to read the directory all the way down. We could create a glob
111904                 // that encodes the suffix, but we would have to escape the character "?" which readDirectory
111905                 // doesn't support. For now, this is safer but slower
111906                 var includeGlob = normalizedSuffix ? "**/*" : "./*";
111907                 var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) {
111908                     var extension = ts.tryGetExtensionFromPath(match);
111909                     var name = trimPrefixAndSuffix(match);
111910                     return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension);
111911                 });
111912                 var directories = ts.mapDefined(ts.tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) {
111913                     var name = trimPrefixAndSuffix(dir);
111914                     return name === undefined ? undefined : directoryResult(name);
111915                 });
111916                 return __spreadArrays(matches, directories);
111917                 function trimPrefixAndSuffix(path) {
111918                     var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix);
111919                     return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner);
111920                 }
111921             }
111922             function withoutStartAndEnd(s, start, end) {
111923                 return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined;
111924             }
111925             function removeLeadingDirectorySeparator(path) {
111926                 return path[0] === ts.directorySeparator ? path.slice(1) : path;
111927             }
111928             function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) {
111929                 // Get modules that the type checker picked up
111930                 var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); });
111931                 var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); });
111932                 // Nested modules of the form "module-name/sub" need to be adjusted to only return the string
111933                 // after the last '/' that appears in the fragment because that's where the replacement span
111934                 // starts
111935                 if (fragmentDirectory !== undefined) {
111936                     var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory);
111937                     return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); });
111938                 }
111939                 return nonRelativeModuleNames;
111940             }
111941             function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) {
111942                 var token = ts.getTokenAtPosition(sourceFile, position);
111943                 var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
111944                 var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; });
111945                 if (!range) {
111946                     return undefined;
111947                 }
111948                 var text = sourceFile.text.slice(range.pos, position);
111949                 var match = tripleSlashDirectiveFragmentRegex.exec(text);
111950                 if (!match) {
111951                     return undefined;
111952                 }
111953                 var prefix = match[1], kind = match[2], toComplete = match[3];
111954                 var scriptPath = ts.getDirectoryPath(sourceFile.path);
111955                 var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path)
111956                     : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions))
111957                         : ts.Debug.fail();
111958                 return addReplacementSpans(toComplete, range.pos + prefix.length, names);
111959             }
111960             function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) {
111961                 if (result === void 0) { result = []; }
111962                 // Check for typings specified in compiler options
111963                 var seen = ts.createMap();
111964                 var typeRoots = ts.tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
111965                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
111966                     var root = typeRoots_1[_i];
111967                     getCompletionEntriesFromDirectories(root);
111968                 }
111969                 // Also get all @types typings installed in visible node_modules directories
111970                 for (var _a = 0, _b = ts.findPackageJsons(scriptPath, host); _a < _b.length; _a++) {
111971                     var packageJson = _b[_a];
111972                     var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types");
111973                     getCompletionEntriesFromDirectories(typesDir);
111974                 }
111975                 return result;
111976                 function getCompletionEntriesFromDirectories(directory) {
111977                     if (!ts.tryDirectoryExists(host, directory))
111978                         return;
111979                     for (var _i = 0, _a = ts.tryGetDirectories(host, directory); _i < _a.length; _i++) {
111980                         var typeDirectoryName = _a[_i];
111981                         var packageName = ts.unmangleScopedPackageName(typeDirectoryName);
111982                         if (options.types && !ts.contains(options.types, packageName))
111983                             continue;
111984                         if (fragmentDirectory === undefined) {
111985                             if (!seen.has(packageName)) {
111986                                 result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined));
111987                                 seen.set(packageName, true);
111988                             }
111989                         }
111990                         else {
111991                             var baseDirectory = ts.combinePaths(directory, typeDirectoryName);
111992                             var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host));
111993                             if (remainingFragment !== undefined) {
111994                                 getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result);
111995                             }
111996                         }
111997                     }
111998                 }
111999             }
112000             function enumerateNodeModulesVisibleToScript(host, scriptPath) {
112001                 if (!host.readFile || !host.fileExists)
112002                     return ts.emptyArray;
112003                 var result = [];
112004                 for (var _i = 0, _a = ts.findPackageJsons(scriptPath, host); _i < _a.length; _i++) {
112005                     var packageJson = _a[_i];
112006                     var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined
112007                     // Provide completions for all non @types dependencies
112008                     for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) {
112009                         var key = nodeModulesDependencyKeys_1[_b];
112010                         var dependencies = contents[key];
112011                         if (!dependencies)
112012                             continue;
112013                         for (var dep in dependencies) {
112014                             if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) {
112015                                 result.push(dep);
112016                             }
112017                         }
112018                     }
112019                 }
112020                 return result;
112021             }
112022             // Replace everything after the last directory separator that appears
112023             function getDirectoryFragmentTextSpan(text, textStart) {
112024                 var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\"));
112025                 var offset = index !== -1 ? index + 1 : 0;
112026                 // If the range is an identifier, span is unnecessary.
112027                 var length = text.length - offset;
112028                 return length === 0 || ts.isIdentifierText(text.substr(offset, length), 99 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
112029             }
112030             // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
112031             function isPathRelativeToScript(path) {
112032                 if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) {
112033                     var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1;
112034                     var slashCharCode = path.charCodeAt(slashIndex);
112035                     return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */;
112036                 }
112037                 return false;
112038             }
112039             /**
112040              * Matches a triple slash reference directive with an incomplete string literal for its path. Used
112041              * to determine if the caret is currently within the string literal and capture the literal fragment
112042              * for completions.
112043              * For example, this matches
112044              *
112045              * /// <reference path="fragment
112046              *
112047              * but not
112048              *
112049              * /// <reference path="fragment"
112050              */
112051             var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
112052             var nodeModulesDependencyKeys = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
112053             function containsSlash(fragment) {
112054                 return ts.stringContains(fragment, ts.directorySeparator);
112055             }
112056         })(StringCompletions = Completions.StringCompletions || (Completions.StringCompletions = {}));
112057     })(Completions = ts.Completions || (ts.Completions = {}));
112058 })(ts || (ts = {}));
112059 /* @internal */
112060 var ts;
112061 (function (ts) {
112062     var Completions;
112063     (function (Completions) {
112064         var SortText;
112065         (function (SortText) {
112066             SortText["LocationPriority"] = "0";
112067             SortText["OptionalMember"] = "1";
112068             SortText["MemberDeclaredBySpreadAssignment"] = "2";
112069             SortText["SuggestedClassMembers"] = "3";
112070             SortText["GlobalsOrKeywords"] = "4";
112071             SortText["AutoImportSuggestions"] = "5";
112072             SortText["JavascriptIdentifiers"] = "6";
112073         })(SortText = Completions.SortText || (Completions.SortText = {}));
112074         /**
112075          * Special values for `CompletionInfo['source']` used to disambiguate
112076          * completion items with the same `name`. (Each completion item must
112077          * have a unique name/source combination, because those two fields
112078          * comprise `CompletionEntryIdentifier` in `getCompletionEntryDetails`.
112079          *
112080          * When the completion item is an auto-import suggestion, the source
112081          * is the module specifier of the suggestion. To avoid collisions,
112082          * the values here should not be a module specifier we would ever
112083          * generate for an auto-import.
112084          */
112085         var CompletionSource;
112086         (function (CompletionSource) {
112087             /** Completions that require `this.` insertion text */
112088             CompletionSource["ThisProperty"] = "ThisProperty/";
112089         })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {}));
112090         var SymbolOriginInfoKind;
112091         (function (SymbolOriginInfoKind) {
112092             SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 1] = "ThisType";
112093             SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMember"] = 2] = "SymbolMember";
112094             SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 4] = "Export";
112095             SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise";
112096             SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable";
112097             SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport";
112098             SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport";
112099         })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {}));
112100         function originIsThisType(origin) {
112101             return !!(origin.kind & 1 /* ThisType */);
112102         }
112103         function originIsSymbolMember(origin) {
112104             return !!(origin.kind & 2 /* SymbolMember */);
112105         }
112106         function originIsExport(origin) {
112107             return !!(origin && origin.kind & 4 /* Export */);
112108         }
112109         function originIsPromise(origin) {
112110             return !!(origin.kind & 8 /* Promise */);
112111         }
112112         function originIsNullableMember(origin) {
112113             return !!(origin.kind & 16 /* Nullable */);
112114         }
112115         var KeywordCompletionFilters;
112116         (function (KeywordCompletionFilters) {
112117             KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None";
112118             KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All";
112119             KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords";
112120             KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords";
112121             KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
112122             KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
112123             KeywordCompletionFilters[KeywordCompletionFilters["TypeAssertionKeywords"] = 6] = "TypeAssertionKeywords";
112124             KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 7] = "TypeKeywords";
112125             KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 7] = "Last";
112126         })(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
112127         var GlobalsSearch;
112128         (function (GlobalsSearch) {
112129             GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue";
112130             GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success";
112131             GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail";
112132         })(GlobalsSearch || (GlobalsSearch = {}));
112133         function createImportSuggestionsForFileCache() {
112134             var cache;
112135             var projectVersion;
112136             var fileName;
112137             return {
112138                 isEmpty: function () {
112139                     return !cache;
112140                 },
112141                 clear: function () {
112142                     cache = undefined;
112143                     fileName = undefined;
112144                     projectVersion = undefined;
112145                 },
112146                 set: function (file, suggestions, version) {
112147                     cache = suggestions;
112148                     fileName = file;
112149                     if (version) {
112150                         projectVersion = version;
112151                     }
112152                 },
112153                 get: function (file, checker, version) {
112154                     if (file !== fileName) {
112155                         return undefined;
112156                     }
112157                     if (version) {
112158                         return projectVersion === version ? cache : undefined;
112159                     }
112160                     ts.forEach(cache, function (suggestion) {
112161                         var _a, _b, _c;
112162                         // If the symbol/moduleSymbol was a merged symbol, it will have a new identity
112163                         // in the checker, even though the symbols to merge are the same (guaranteed by
112164                         // cache invalidation in synchronizeHostData).
112165                         if ((_a = suggestion.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) {
112166                             suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport
112167                                 ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol : suggestion.symbol.declarations[0].symbol);
112168                         }
112169                         if ((_c = suggestion.origin.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) {
112170                             suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol);
112171                         }
112172                     });
112173                     return cache;
112174                 },
112175             };
112176         }
112177         Completions.createImportSuggestionsForFileCache = createImportSuggestionsForFileCache;
112178         function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) {
112179             var typeChecker = program.getTypeChecker();
112180             var compilerOptions = program.getCompilerOptions();
112181             var contextToken = ts.findPrecedingToken(position, sourceFile);
112182             if (triggerCharacter && !ts.isInString(sourceFile, position, contextToken) && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) {
112183                 return undefined;
112184             }
112185             var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences);
112186             if (stringCompletions) {
112187                 return stringCompletions;
112188             }
112189             if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent)
112190                 && (contextToken.kind === 77 /* BreakKeyword */ || contextToken.kind === 82 /* ContinueKeyword */ || contextToken.kind === 75 /* Identifier */)) {
112191                 return getLabelCompletionAtPosition(contextToken.parent);
112192             }
112193             var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined, host);
112194             if (!completionData) {
112195                 return undefined;
112196             }
112197             switch (completionData.kind) {
112198                 case 0 /* Data */:
112199                     return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences);
112200                 case 1 /* JsDocTagName */:
112201                     // If the current position is a jsDoc tag name, only tag names should be provided for completion
112202                     return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions());
112203                 case 2 /* JsDocTag */:
112204                     // If the current position is a jsDoc tag, only tags should be provided for completion
112205                     return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions());
112206                 case 3 /* JsDocParameterName */:
112207                     return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag));
112208                 default:
112209                     return ts.Debug.assertNever(completionData);
112210             }
112211         }
112212         Completions.getCompletionsAtPosition = getCompletionsAtPosition;
112213         function jsdocCompletionInfo(entries) {
112214             return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
112215         }
112216         function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) {
112217             var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap;
112218             if (location && location.parent && ts.isJsxClosingElement(location.parent)) {
112219                 // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
112220                 // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element.
112221                 // For example:
112222                 //     var x = <div> </ /*1*/
112223                 // The completion list at "1" will contain "div>" with type any
112224                 // And at `<div> </ /*1*/ >` (with a closing `>`), the completion list will contain "div".
112225                 var tagName = location.parent.parent.openingElement.tagName;
112226                 var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 31 /* GreaterThanToken */, sourceFile);
112227                 var entry = {
112228                     name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"),
112229                     kind: "class" /* classElement */,
112230                     kindModifiers: undefined,
112231                     sortText: SortText.LocationPriority,
112232                 };
112233                 return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] };
112234             }
112235             var entries = [];
112236             if (isUncheckedFile(sourceFile, compilerOptions)) {
112237                 var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, 
112238                 /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap);
112239                 getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217
112240             }
112241             else {
112242                 if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) {
112243                     return undefined;
112244                 }
112245                 getCompletionEntriesFromSymbols(symbols, entries, 
112246                 /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap);
112247             }
112248             if (keywordFilters !== 0 /* None */) {
112249                 var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
112250                 for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) {
112251                     var keywordEntry = _a[_i];
112252                     if (!entryNames.has(keywordEntry.name)) {
112253                         entries.push(keywordEntry);
112254                     }
112255                 }
112256             }
112257             for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) {
112258                 var literal = literals_1[_b];
112259                 entries.push(createCompletionEntryForLiteral(literal, preferences));
112260             }
112261             return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
112262         }
112263         function isUncheckedFile(sourceFile, compilerOptions) {
112264             return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions);
112265         }
112266         function isMemberCompletionKind(kind) {
112267             switch (kind) {
112268                 case 0 /* ObjectPropertyDeclaration */:
112269                 case 3 /* MemberLike */:
112270                 case 2 /* PropertyAccess */:
112271                     return true;
112272                 default:
112273                     return false;
112274             }
112275         }
112276         function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) {
112277             ts.getNameTable(sourceFile).forEach(function (pos, name) {
112278                 // Skip identifiers produced only from the current location
112279                 if (pos === position) {
112280                     return;
112281                 }
112282                 var realName = ts.unescapeLeadingUnderscores(name);
112283                 if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) {
112284                     uniqueNames.add(realName);
112285                     entries.push({
112286                         name: realName,
112287                         kind: "warning" /* warning */,
112288                         kindModifiers: "",
112289                         sortText: SortText.JavascriptIdentifiers,
112290                         isFromUncheckedFile: true
112291                     });
112292                 }
112293             });
112294         }
112295         function completionNameForLiteral(literal, preferences) {
112296             return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" :
112297                 ts.isString(literal) ? ts.quote(literal, preferences) : JSON.stringify(literal);
112298         }
112299         function createCompletionEntryForLiteral(literal, preferences) {
112300             return { name: completionNameForLiteral(literal, preferences), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority };
112301         }
112302         function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) {
112303             var insertText;
112304             var replacementSpan = ts.getReplacementSpanForContextToken(contextToken);
112305             var insertQuestionDot = origin && originIsNullableMember(origin);
112306             var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess;
112307             if (origin && originIsThisType(origin)) {
112308                 insertText = needsConvertPropertyAccess
112309                     ? "this" + (insertQuestionDot ? "?." : "") + "[" + quotePropertyName(name, preferences) + "]"
112310                     : "this" + (insertQuestionDot ? "?." : ".") + name;
112311             }
112312             // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790.
112313             // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro.
112314             else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) {
112315                 insertText = useBraces ? needsConvertPropertyAccess ? "[" + quotePropertyName(name, preferences) + "]" : "[" + name + "]" : name;
112316                 if (insertQuestionDot || propertyAccessToConvert.questionDotToken) {
112317                     insertText = "?." + insertText;
112318                 }
112319                 var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile) ||
112320                     ts.findChildOfKind(propertyAccessToConvert, 28 /* QuestionDotToken */, sourceFile);
112321                 if (!dot) {
112322                     return undefined;
112323                 }
112324                 // If the text after the '.' starts with this name, write over it. Else, add new text.
112325                 var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end;
112326                 replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end);
112327             }
112328             if (isJsxInitializer) {
112329                 if (insertText === undefined)
112330                     insertText = name;
112331                 insertText = "{" + insertText + "}";
112332                 if (typeof isJsxInitializer !== "boolean") {
112333                     replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile);
112334                 }
112335             }
112336             if (origin && originIsPromise(origin) && propertyAccessToConvert) {
112337                 if (insertText === undefined)
112338                     insertText = name;
112339                 var precedingToken = ts.findPrecedingToken(propertyAccessToConvert.pos, sourceFile);
112340                 var awaitText = "";
112341                 if (precedingToken && ts.positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
112342                     awaitText = ";";
112343                 }
112344                 awaitText += "(await " + propertyAccessToConvert.expression.getText() + ")";
112345                 insertText = needsConvertPropertyAccess ? "" + awaitText + insertText : "" + awaitText + (insertQuestionDot ? "?." : ".") + insertText;
112346                 replacementSpan = ts.createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end);
112347             }
112348             if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) {
112349                 return undefined;
112350             }
112351             // TODO(drosen): Right now we just permit *all* semantic meanings when calling
112352             // 'getSymbolKind' which is permissible given that it is backwards compatible; but
112353             // really we should consider passing the meaning for the node so that we don't report
112354             // that a suggestion for a value is an interface.  We COULD also just do what
112355             // 'getSymbolModifiers' does, which is to use the first declaration.
112356             // Use a 'sortText' of 0' so that all symbol completion entries come before any other
112357             // entries (like JavaScript identifier entries).
112358             return {
112359                 name: name,
112360                 kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location),
112361                 kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
112362                 sortText: sortText,
112363                 source: getSourceFromOrigin(origin),
112364                 hasAction: origin && originIsExport(origin) || undefined,
112365                 isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined,
112366                 insertText: insertText,
112367                 replacementSpan: replacementSpan,
112368             };
112369         }
112370         function quotePropertyName(name, preferences) {
112371             if (/^\d+$/.test(name)) {
112372                 return name;
112373             }
112374             return ts.quote(name, preferences);
112375         }
112376         function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) {
112377             return localSymbol === recommendedCompletion ||
112378                 !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion;
112379         }
112380         function getSourceFromOrigin(origin) {
112381             if (originIsExport(origin)) {
112382                 return ts.stripQuotes(origin.moduleSymbol.name);
112383             }
112384             if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) {
112385                 return CompletionSource.ThisProperty;
112386             }
112387         }
112388         function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) {
112389             var start = ts.timestamp();
112390             // Tracks unique names.
112391             // Value is set to false for global variables or completions from external module exports, because we can have multiple of those;
112392             // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports.
112393             // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name.
112394             var uniques = ts.createMap();
112395             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
112396                 var symbol = symbols_1[_i];
112397                 var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined;
112398                 var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected);
112399                 if (!info) {
112400                     continue;
112401                 }
112402                 var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess;
112403                 if (uniques.get(name)) {
112404                     continue;
112405                 }
112406                 var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences);
112407                 if (!entry) {
112408                     continue;
112409                 }
112410                 /** True for locals; false for globals, module exports from other files, `this.` completions. */
112411                 var shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }));
112412                 uniques.set(name, shouldShadowLaterSymbols);
112413                 entries.push(entry);
112414             }
112415             log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start));
112416             // Prevent consumers of this map from having to worry about
112417             // the boolean value. Externally, it should be seen as the
112418             // set of all names.
112419             return {
112420                 has: function (name) { return uniques.has(name); },
112421                 add: function (name) { return uniques.set(name, true); },
112422             };
112423         }
112424         Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols;
112425         function getLabelCompletionAtPosition(node) {
112426             var entries = getLabelStatementCompletions(node);
112427             if (entries.length) {
112428                 return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
112429             }
112430         }
112431         function getLabelStatementCompletions(node) {
112432             var entries = [];
112433             var uniques = ts.createMap();
112434             var current = node;
112435             while (current) {
112436                 if (ts.isFunctionLike(current)) {
112437                     break;
112438                 }
112439                 if (ts.isLabeledStatement(current)) {
112440                     var name = current.label.text;
112441                     if (!uniques.has(name)) {
112442                         uniques.set(name, true);
112443                         entries.push({
112444                             name: name,
112445                             kindModifiers: "" /* none */,
112446                             kind: "label" /* label */,
112447                             sortText: SortText.LocationPriority
112448                         });
112449                     }
112450                 }
112451                 current = current.parent;
112452             }
112453             return entries;
112454         }
112455         function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) {
112456             var compilerOptions = program.getCompilerOptions();
112457             var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host);
112458             if (!completionData) {
112459                 return { type: "none" };
112460             }
112461             if (completionData.kind !== 0 /* Data */) {
112462                 return { type: "request", request: completionData };
112463             }
112464             var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation;
112465             var literal = ts.find(literals, function (l) { return completionNameForLiteral(l, preferences) === entryId.name; });
112466             if (literal !== undefined)
112467                 return { type: "literal", literal: literal };
112468             // Find the symbol with the matching entry name.
112469             // We don't need to perform character checks here because we're only comparing the
112470             // name against 'entryName' (which is known to be good), not building a new
112471             // completion entry.
112472             return ts.firstDefined(symbols, function (symbol) {
112473                 var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
112474                 var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind, completionData.isJsxIdentifierExpected);
112475                 return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source
112476                     ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation }
112477                     : undefined;
112478             }) || { type: "none" };
112479         }
112480         function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) {
112481             var typeChecker = program.getTypeChecker();
112482             var compilerOptions = program.getCompilerOptions();
112483             var name = entryId.name;
112484             var contextToken = ts.findPrecedingToken(position, sourceFile);
112485             if (ts.isInString(sourceFile, position, contextToken)) {
112486                 return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken);
112487             }
112488             // Compute all the completion symbols again.
112489             var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences);
112490             switch (symbolCompletion.type) {
112491                 case "request": {
112492                     var request = symbolCompletion.request;
112493                     switch (request.kind) {
112494                         case 1 /* JsDocTagName */:
112495                             return ts.JsDoc.getJSDocTagNameCompletionDetails(name);
112496                         case 2 /* JsDocTag */:
112497                             return ts.JsDoc.getJSDocTagCompletionDetails(name);
112498                         case 3 /* JsDocParameterName */:
112499                             return ts.JsDoc.getJSDocParameterNameCompletionDetails(name);
112500                         default:
112501                             return ts.Debug.assertNever(request);
112502                     }
112503                 }
112504                 case "symbol": {
112505                     var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken;
112506                     var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay;
112507                     return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217
112508                 }
112509                 case "literal": {
112510                     var literal = symbolCompletion.literal;
112511                     return createSimpleDetails(completionNameForLiteral(literal, preferences), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral);
112512                 }
112513                 case "none":
112514                     // Didn't find a symbol with this name.  See if we can find a keyword instead.
112515                     return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined;
112516                 default:
112517                     ts.Debug.assertNever(symbolCompletion);
112518             }
112519         }
112520         Completions.getCompletionEntryDetails = getCompletionEntryDetails;
112521         function createSimpleDetails(name, kind, kind2) {
112522             return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]);
112523         }
112524         function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) {
112525             var _a = checker.runWithCancellationToken(cancellationToken, function (checker) {
112526                 return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */);
112527             }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags;
112528             return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
112529         }
112530         Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol;
112531         function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) {
112532             return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source };
112533         }
112534         Completions.createCompletionDetails = createCompletionDetails;
112535         function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) {
112536             var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
112537             if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) {
112538                 return { codeActions: undefined, sourceDisplay: undefined };
112539             }
112540             var moduleSymbol = symbolOriginInfo.moduleSymbol;
112541             var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker));
112542             var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction;
112543             return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] };
112544         }
112545         function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host, preferences) {
112546             var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences);
112547             return completion.type === "symbol" ? completion.symbol : undefined;
112548         }
112549         Completions.getCompletionEntrySymbol = getCompletionEntrySymbol;
112550         var CompletionDataKind;
112551         (function (CompletionDataKind) {
112552             CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data";
112553             CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName";
112554             CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag";
112555             CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName";
112556         })(CompletionDataKind || (CompletionDataKind = {}));
112557         var CompletionKind;
112558         (function (CompletionKind) {
112559             CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
112560             CompletionKind[CompletionKind["Global"] = 1] = "Global";
112561             CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess";
112562             CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike";
112563             CompletionKind[CompletionKind["String"] = 4] = "String";
112564             CompletionKind[CompletionKind["None"] = 5] = "None";
112565         })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {}));
112566         function getRecommendedCompletion(previousToken, contextualType, checker) {
112567             // For a union, return the first one with a recommended completion.
112568             return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) {
112569                 var symbol = type && type.symbol;
112570                 // Don't include make a recommended completion for an abstract class
112571                 return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol))
112572                     ? getFirstSymbolInChain(symbol, previousToken, checker)
112573                     : undefined;
112574             });
112575         }
112576         function getContextualType(previousToken, position, sourceFile, checker) {
112577             var parent = previousToken.parent;
112578             switch (previousToken.kind) {
112579                 case 75 /* Identifier */:
112580                     return ts.getContextualTypeFromParent(previousToken, checker);
112581                 case 62 /* EqualsToken */:
112582                     switch (parent.kind) {
112583                         case 242 /* VariableDeclaration */:
112584                             return checker.getContextualType(parent.initializer); // TODO: GH#18217
112585                         case 209 /* BinaryExpression */:
112586                             return checker.getTypeAtLocation(parent.left);
112587                         case 273 /* JsxAttribute */:
112588                             return checker.getContextualTypeForJsxAttribute(parent);
112589                         default:
112590                             return undefined;
112591                     }
112592                 case 99 /* NewKeyword */:
112593                     return checker.getContextualType(parent);
112594                 case 78 /* CaseKeyword */:
112595                     return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker);
112596                 case 18 /* OpenBraceToken */:
112597                     return ts.isJsxExpression(parent) && parent.parent.kind !== 266 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined;
112598                 default:
112599                     var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile);
112600                     return argInfo ?
112601                         // At `,`, treat this as the next argument after the comma.
112602                         checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) :
112603                         ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) ?
112604                             // completion at `x ===/**/` should be for the right side
112605                             checker.getTypeAtLocation(parent.left) :
112606                             checker.getContextualType(previousToken);
112607             }
112608         }
112609         function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) {
112610             var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false);
112611             if (chain)
112612                 return ts.first(chain);
112613             return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
112614         }
112615         function isModuleSymbol(symbol) {
112616             return symbol.declarations.some(function (d) { return d.kind === 290 /* SourceFile */; });
112617         }
112618         function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) {
112619             var typeChecker = program.getTypeChecker();
112620             var start = ts.timestamp();
112621             var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853
112622             // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.)
112623             log("getCompletionData: Get current token: " + (ts.timestamp() - start));
112624             start = ts.timestamp();
112625             var insideComment = ts.isInComment(sourceFile, position, currentToken);
112626             log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
112627             var insideJsDocTagTypeExpression = false;
112628             var isInSnippetScope = false;
112629             if (insideComment) {
112630                 if (ts.hasDocComment(sourceFile, position)) {
112631                     if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
112632                         // The current position is next to the '@' sign, when no tag name being provided yet.
112633                         // Provide a full list of tag names
112634                         return { kind: 1 /* JsDocTagName */ };
112635                     }
112636                     else {
112637                         // When completion is requested without "@", we will have check to make sure that
112638                         // there are no comments prefix the request position. We will only allow "*" and space.
112639                         // e.g
112640                         //   /** |c| /*
112641                         //
112642                         //   /**
112643                         //     |c|
112644                         //    */
112645                         //
112646                         //   /**
112647                         //    * |c|
112648                         //    */
112649                         //
112650                         //   /**
112651                         //    *         |c|
112652                         //    */
112653                         var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
112654                         if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) {
112655                             return { kind: 2 /* JsDocTag */ };
112656                         }
112657                     }
112658                 }
112659                 // Completion should work inside certain JsDoc tags. For example:
112660                 //     /** @type {number | string} */
112661                 // Completion should work in the brackets
112662                 var tag = getJsDocTagAtPosition(currentToken, position);
112663                 if (tag) {
112664                     if (tag.tagName.pos <= position && position <= tag.tagName.end) {
112665                         return { kind: 1 /* JsDocTagName */ };
112666                     }
112667                     if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
112668                         currentToken = ts.getTokenAtPosition(sourceFile, position);
112669                         if (!currentToken ||
112670                             (!ts.isDeclarationName(currentToken) &&
112671                                 (currentToken.parent.kind !== 323 /* JSDocPropertyTag */ ||
112672                                     currentToken.parent.name !== currentToken))) {
112673                             // Use as type location if inside tag's type expression
112674                             insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
112675                         }
112676                     }
112677                     if (!insideJsDocTagTypeExpression && ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) {
112678                         return { kind: 3 /* JsDocParameterName */, tag: tag };
112679                     }
112680                 }
112681                 if (!insideJsDocTagTypeExpression) {
112682                     // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal
112683                     // comment or the plain text part of a jsDoc comment, so no completion should be available
112684                     log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment.");
112685                     return undefined;
112686                 }
112687             }
112688             start = ts.timestamp();
112689             var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217
112690             log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start));
112691             // The decision to provide completion depends on the contextToken, which is determined through the previousToken.
112692             // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file
112693             var contextToken = previousToken;
112694             // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS|
112695             // Skip this partial identifier and adjust the contextToken to the token that precedes it.
112696             if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) {
112697                 var start_1 = ts.timestamp();
112698                 contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
112699                 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
112700             }
112701             // Find the node where completion is requested on.
112702             // Also determine whether we are trying to complete with members of that node
112703             // or attributes of a JSX tag.
112704             var node = currentToken;
112705             var propertyAccessToConvert;
112706             var isRightOfDot = false;
112707             var isRightOfQuestionDot = false;
112708             var isRightOfOpenTag = false;
112709             var isStartingCloseTag = false;
112710             var isJsxInitializer = false;
112711             var isJsxIdentifierExpected = false;
112712             var location = ts.getTouchingPropertyName(sourceFile, position);
112713             if (contextToken) {
112714                 // Bail out if this is a known invalid completion location
112715                 if (isCompletionListBlocker(contextToken)) {
112716                     log("Returning an empty list because completion was requested in an invalid position.");
112717                     return undefined;
112718                 }
112719                 var parent = contextToken.parent;
112720                 if (contextToken.kind === 24 /* DotToken */ || contextToken.kind === 28 /* QuestionDotToken */) {
112721                     isRightOfDot = contextToken.kind === 24 /* DotToken */;
112722                     isRightOfQuestionDot = contextToken.kind === 28 /* QuestionDotToken */;
112723                     switch (parent.kind) {
112724                         case 194 /* PropertyAccessExpression */:
112725                             propertyAccessToConvert = parent;
112726                             node = propertyAccessToConvert.expression;
112727                             if (node.end === contextToken.pos &&
112728                                 ts.isCallExpression(node) &&
112729                                 node.getChildCount(sourceFile) &&
112730                                 ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) {
112731                                 // This is likely dot from incorrectly parsed call expression and user is starting to write spread
112732                                 // eg: Math.min(./**/)
112733                                 return undefined;
112734                             }
112735                             break;
112736                         case 153 /* QualifiedName */:
112737                             node = parent.left;
112738                             break;
112739                         case 249 /* ModuleDeclaration */:
112740                             node = parent.name;
112741                             break;
112742                         case 188 /* ImportType */:
112743                         case 219 /* MetaProperty */:
112744                             node = parent;
112745                             break;
112746                         default:
112747                             // There is nothing that precedes the dot, so this likely just a stray character
112748                             // or leading into a '...' token. Just bail out instead.
112749                             return undefined;
112750                     }
112751                 }
112752                 else if (sourceFile.languageVariant === 1 /* JSX */) {
112753                     // <UI.Test /* completion position */ />
112754                     // If the tagname is a property access expression, we will then walk up to the top most of property access expression.
112755                     // Then, try to get a JSX container and its associated attributes type.
112756                     if (parent && parent.kind === 194 /* PropertyAccessExpression */) {
112757                         contextToken = parent;
112758                         parent = parent.parent;
112759                     }
112760                     // Fix location
112761                     if (currentToken.parent === location) {
112762                         switch (currentToken.kind) {
112763                             case 31 /* GreaterThanToken */:
112764                                 if (currentToken.parent.kind === 266 /* JsxElement */ || currentToken.parent.kind === 268 /* JsxOpeningElement */) {
112765                                     location = currentToken;
112766                                 }
112767                                 break;
112768                             case 43 /* SlashToken */:
112769                                 if (currentToken.parent.kind === 267 /* JsxSelfClosingElement */) {
112770                                     location = currentToken;
112771                                 }
112772                                 break;
112773                         }
112774                     }
112775                     switch (parent.kind) {
112776                         case 269 /* JsxClosingElement */:
112777                             if (contextToken.kind === 43 /* SlashToken */) {
112778                                 isStartingCloseTag = true;
112779                                 location = contextToken;
112780                             }
112781                             break;
112782                         case 209 /* BinaryExpression */:
112783                             if (!binaryExpressionMayBeOpenTag(parent)) {
112784                                 break;
112785                             }
112786                         // falls through
112787                         case 267 /* JsxSelfClosingElement */:
112788                         case 266 /* JsxElement */:
112789                         case 268 /* JsxOpeningElement */:
112790                             isJsxIdentifierExpected = true;
112791                             if (contextToken.kind === 29 /* LessThanToken */) {
112792                                 isRightOfOpenTag = true;
112793                                 location = contextToken;
112794                             }
112795                             break;
112796                         case 273 /* JsxAttribute */:
112797                             switch (previousToken.kind) {
112798                                 case 62 /* EqualsToken */:
112799                                     isJsxInitializer = true;
112800                                     break;
112801                                 case 75 /* Identifier */:
112802                                     isJsxIdentifierExpected = true;
112803                                     // For `<div x=[|f/**/|]`, `parent` will be `x` and `previousToken.parent` will be `f` (which is its own JsxAttribute)
112804                                     // Note for `<div someBool f>` we don't want to treat this as a jsx inializer, instead it's the attribute name.
112805                                     if (parent !== previousToken.parent &&
112806                                         !parent.initializer &&
112807                                         ts.findChildOfKind(parent, 62 /* EqualsToken */, sourceFile)) {
112808                                         isJsxInitializer = previousToken;
112809                                     }
112810                             }
112811                             break;
112812                     }
112813                 }
112814             }
112815             var semanticStart = ts.timestamp();
112816             var completionKind = 5 /* None */;
112817             var isNewIdentifierLocation = false;
112818             var keywordFilters = 0 /* None */;
112819             // This also gets mutated in nested-functions after the return
112820             var symbols = [];
112821             var symbolToOriginInfoMap = [];
112822             var symbolToSortTextMap = [];
112823             var importSuggestionsCache = host.getImportSuggestionsCache && host.getImportSuggestionsCache();
112824             var isTypeOnly = isTypeOnlyCompletion();
112825             if (isRightOfDot || isRightOfQuestionDot) {
112826                 getTypeScriptMemberSymbols();
112827             }
112828             else if (isRightOfOpenTag) {
112829                 var tagSymbols = typeChecker.getJsxIntrinsicTagNamesAt(location);
112830                 ts.Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined");
112831                 tryGetGlobalSymbols();
112832                 symbols = tagSymbols.concat(symbols);
112833                 completionKind = 3 /* MemberLike */;
112834                 keywordFilters = 0 /* None */;
112835             }
112836             else if (isStartingCloseTag) {
112837                 var tagName = contextToken.parent.parent.openingElement.tagName;
112838                 var tagSymbol = typeChecker.getSymbolAtLocation(tagName);
112839                 if (tagSymbol) {
112840                     symbols = [tagSymbol];
112841                 }
112842                 completionKind = 3 /* MemberLike */;
112843                 keywordFilters = 0 /* None */;
112844             }
112845             else {
112846                 // For JavaScript or TypeScript, if we're not after a dot, then just try to get the
112847                 // global symbols in scope.  These results should be valid for either language as
112848                 // the set of symbols that can be referenced from this location.
112849                 if (!tryGetGlobalSymbols()) {
112850                     return undefined;
112851                 }
112852             }
112853             log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
112854             var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
112855             var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
112856             var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
112857             return {
112858                 kind: 0 /* Data */,
112859                 symbols: symbols,
112860                 completionKind: completionKind,
112861                 isInSnippetScope: isInSnippetScope,
112862                 propertyAccessToConvert: propertyAccessToConvert,
112863                 isNewIdentifierLocation: isNewIdentifierLocation,
112864                 location: location,
112865                 keywordFilters: keywordFilters,
112866                 literals: literals,
112867                 symbolToOriginInfoMap: symbolToOriginInfoMap,
112868                 recommendedCompletion: recommendedCompletion,
112869                 previousToken: previousToken,
112870                 isJsxInitializer: isJsxInitializer,
112871                 insideJsDocTagTypeExpression: insideJsDocTagTypeExpression,
112872                 symbolToSortTextMap: symbolToSortTextMap,
112873                 isTypeOnlyLocation: isTypeOnly,
112874                 isJsxIdentifierExpected: isJsxIdentifierExpected,
112875             };
112876             function isTagWithTypeExpression(tag) {
112877                 switch (tag.kind) {
112878                     case 317 /* JSDocParameterTag */:
112879                     case 323 /* JSDocPropertyTag */:
112880                     case 318 /* JSDocReturnTag */:
112881                     case 320 /* JSDocTypeTag */:
112882                     case 322 /* JSDocTypedefTag */:
112883                         return true;
112884                     default:
112885                         return false;
112886                 }
112887             }
112888             function getTypeScriptMemberSymbols() {
112889                 // Right of dot member completion list
112890                 completionKind = 2 /* PropertyAccess */;
112891                 // Since this is qualified name check it's a type node location
112892                 var isImportType = ts.isLiteralImportTypeNode(node);
112893                 var isTypeLocation = insideJsDocTagTypeExpression
112894                     || (isImportType && !node.isTypeOf)
112895                     || ts.isPartOfTypeNode(node.parent)
112896                     || ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
112897                 var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node);
112898                 if (ts.isEntityName(node) || isImportType) {
112899                     var isNamespaceName = ts.isModuleDeclaration(node.parent);
112900                     if (isNamespaceName)
112901                         isNewIdentifierLocation = true;
112902                     var symbol = typeChecker.getSymbolAtLocation(node);
112903                     if (symbol) {
112904                         symbol = ts.skipAlias(symbol, typeChecker);
112905                         if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) {
112906                             // Extract module or enum members
112907                             var exportedSymbols = typeChecker.getExportsOfModule(symbol);
112908                             ts.Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined");
112909                             var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); };
112910                             var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); };
112911                             var isValidAccess = isNamespaceName
112912                                 // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion.
112913                                 ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); }
112914                                 : isRhsOfImportDeclaration ?
112915                                     // Any kind is allowed when dotting off namespace in internal import equals declaration
112916                                     function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } :
112917                                     isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1;
112918                             for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) {
112919                                 var exportedSymbol = exportedSymbols_1[_i];
112920                                 if (isValidAccess(exportedSymbol)) {
112921                                     symbols.push(exportedSymbol);
112922                                 }
112923                             }
112924                             // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
112925                             if (!isTypeLocation &&
112926                                 symbol.declarations &&
112927                                 symbol.declarations.some(function (d) { return d.kind !== 290 /* SourceFile */ && d.kind !== 249 /* ModuleDeclaration */ && d.kind !== 248 /* EnumDeclaration */; })) {
112928                                 var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType();
112929                                 var insertQuestionDot = false;
112930                                 if (type.isNullableType()) {
112931                                     var canCorrectToQuestionDot = isRightOfDot &&
112932                                         !isRightOfQuestionDot &&
112933                                         preferences.includeAutomaticOptionalChainCompletions !== false;
112934                                     if (canCorrectToQuestionDot || isRightOfQuestionDot) {
112935                                         type = type.getNonNullableType();
112936                                         if (canCorrectToQuestionDot) {
112937                                             insertQuestionDot = true;
112938                                         }
112939                                     }
112940                                 }
112941                                 addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot);
112942                             }
112943                             return;
112944                         }
112945                     }
112946                 }
112947                 if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */) && contextToken === node.getChildAt(1)) {
112948                     var completion = (node.keywordToken === 99 /* NewKeyword */) ? "target" : "meta";
112949                     symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion)));
112950                     return;
112951                 }
112952                 if (!isTypeLocation) {
112953                     var type = typeChecker.getTypeAtLocation(node).getNonOptionalType();
112954                     var insertQuestionDot = false;
112955                     if (type.isNullableType()) {
112956                         var canCorrectToQuestionDot = isRightOfDot &&
112957                             !isRightOfQuestionDot &&
112958                             preferences.includeAutomaticOptionalChainCompletions !== false;
112959                         if (canCorrectToQuestionDot || isRightOfQuestionDot) {
112960                             type = type.getNonNullableType();
112961                             if (canCorrectToQuestionDot) {
112962                                 insertQuestionDot = true;
112963                             }
112964                         }
112965                     }
112966                     addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot);
112967                 }
112968             }
112969             function addTypeProperties(type, insertAwait, insertQuestionDot) {
112970                 isNewIdentifierLocation = !!type.getStringIndexType();
112971                 if (isRightOfQuestionDot && ts.some(type.getCallSignatures())) {
112972                     isNewIdentifierLocation = true;
112973                 }
112974                 var propertyAccess = node.kind === 188 /* ImportType */ ? node : node.parent;
112975                 if (isUncheckedFile) {
112976                     // In javascript files, for union types, we don't just get the members that
112977                     // the individual types have in common, we also include all the members that
112978                     // each individual type has. This is because we're going to add all identifiers
112979                     // anyways. So we might as well elevate the members that were at least part
112980                     // of the individual types to a higher status since we know what they are.
112981                     symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker));
112982                 }
112983                 else {
112984                     for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) {
112985                         var symbol = _a[_i];
112986                         if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) {
112987                             addPropertySymbol(symbol, /*insertAwait*/ false, insertQuestionDot);
112988                         }
112989                     }
112990                 }
112991                 if (insertAwait && preferences.includeCompletionsWithInsertText) {
112992                     var promiseType = typeChecker.getPromisedTypeOfPromise(type);
112993                     if (promiseType) {
112994                         for (var _b = 0, _c = promiseType.getApparentProperties(); _b < _c.length; _b++) {
112995                             var symbol = _c[_b];
112996                             if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, promiseType, symbol)) {
112997                                 addPropertySymbol(symbol, /* insertAwait */ true, insertQuestionDot);
112998                             }
112999                         }
113000                     }
113001                 }
113002             }
113003             function addPropertySymbol(symbol, insertAwait, insertQuestionDot) {
113004                 // For a computed property with an accessible name like `Symbol.iterator`,
113005                 // we'll add a completion for the *name* `Symbol` instead of for the property.
113006                 // If this is e.g. [Symbol.iterator], add a completion for `Symbol`.
113007                 var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); });
113008                 if (computedPropertyName) {
113009                     var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`.
113010                     var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName);
113011                     // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`.
113012                     var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker);
113013                     if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) {
113014                         symbols.push(firstAccessibleSymbol);
113015                         var moduleSymbol = firstAccessibleSymbol.parent;
113016                         symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] =
113017                             !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)
113018                                 ? { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }
113019                                 : { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), moduleSymbol: moduleSymbol, isDefaultExport: false };
113020                     }
113021                     else if (preferences.includeCompletionsWithInsertText) {
113022                         addSymbolOriginInfo(symbol);
113023                         symbols.push(symbol);
113024                     }
113025                 }
113026                 else {
113027                     addSymbolOriginInfo(symbol);
113028                     symbols.push(symbol);
113029                 }
113030                 function addSymbolOriginInfo(symbol) {
113031                     if (preferences.includeCompletionsWithInsertText) {
113032                         if (insertAwait && !symbolToOriginInfoMap[ts.getSymbolId(symbol)]) {
113033                             symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) };
113034                         }
113035                         else if (insertQuestionDot) {
113036                             symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 16 /* Nullable */ };
113037                         }
113038                     }
113039                 }
113040                 function getNullableSymbolOriginInfoKind(kind) {
113041                     return insertQuestionDot ? kind | 16 /* Nullable */ : kind;
113042                 }
113043             }
113044             /** Given 'a.b.c', returns 'a'. */
113045             function getLeftMostName(e) {
113046                 return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined;
113047             }
113048             function tryGetGlobalSymbols() {
113049                 var result = tryGetObjectLikeCompletionSymbols()
113050                     || tryGetImportOrExportClauseCompletionSymbols()
113051                     || tryGetLocalNamedExportCompletionSymbols()
113052                     || tryGetConstructorCompletion()
113053                     || tryGetClassLikeCompletionSymbols()
113054                     || tryGetJsxCompletionSymbols()
113055                     || (getGlobalCompletions(), 1 /* Success */);
113056                 return result === 1 /* Success */;
113057             }
113058             function tryGetConstructorCompletion() {
113059                 if (!tryGetConstructorLikeCompletionContainer(contextToken))
113060                     return 0 /* Continue */;
113061                 // no members, only keywords
113062                 completionKind = 5 /* None */;
113063                 // Declaring new property/method/accessor
113064                 isNewIdentifierLocation = true;
113065                 // Has keywords for constructor parameter
113066                 keywordFilters = 4 /* ConstructorParameterKeywords */;
113067                 return 1 /* Success */;
113068             }
113069             function tryGetJsxCompletionSymbols() {
113070                 var jsxContainer = tryGetContainingJsxElement(contextToken);
113071                 // Cursor is inside a JSX self-closing element or opening element
113072                 var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes);
113073                 if (!attrsType)
113074                     return 0 /* Continue */;
113075                 var completionsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes, 4 /* Completions */);
113076                 symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, completionsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties);
113077                 setSortTextToOptionalMember();
113078                 completionKind = 3 /* MemberLike */;
113079                 isNewIdentifierLocation = false;
113080                 return 1 /* Success */;
113081             }
113082             function getGlobalCompletions() {
113083                 keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */;
113084                 // Get all entities in the current scope.
113085                 completionKind = 1 /* Global */;
113086                 isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
113087                 if (previousToken !== contextToken) {
113088                     ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
113089                 }
113090                 // We need to find the node that will give us an appropriate scope to begin
113091                 // aggregating completion candidates. This is achieved in 'getScopeNode'
113092                 // by finding the first node that encompasses a position, accounting for whether a node
113093                 // is "complete" to decide whether a position belongs to the node.
113094                 //
113095                 // However, at the end of an identifier, we are interested in the scope of the identifier
113096                 // itself, but fall outside of the identifier. For instance:
113097                 //
113098                 //      xyz => x$
113099                 //
113100                 // the cursor is outside of both the 'x' and the arrow function 'xyz => x',
113101                 // so 'xyz' is not returned in our results.
113102                 //
113103                 // We define 'adjustedPosition' so that we may appropriately account for
113104                 // being at the end of an identifier. The intention is that if requesting completion
113105                 // at the end of an identifier, it should be effectively equivalent to requesting completion
113106                 // anywhere inside/at the beginning of the identifier. So in the previous case, the
113107                 // 'adjustedPosition' will work as if requesting completion in the following:
113108                 //
113109                 //      xyz => $x
113110                 //
113111                 // If previousToken !== contextToken, then
113112                 //   - 'contextToken' was adjusted to the token prior to 'previousToken'
113113                 //      because we were at the end of an identifier.
113114                 //   - 'previousToken' is defined.
113115                 var adjustedPosition = previousToken !== contextToken ?
113116                     previousToken.getStart() :
113117                     position;
113118                 var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
113119                 isInSnippetScope = isSnippetScope(scopeNode);
113120                 var symbolMeanings = (isTypeOnly ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
113121                 symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings);
113122                 ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined");
113123                 for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
113124                     var symbol = symbols_2[_i];
113125                     if (!typeChecker.isArgumentsSymbol(symbol) &&
113126                         !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) {
113127                         symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.GlobalsOrKeywords;
113128                     }
113129                 }
113130                 // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
113131                 if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 290 /* SourceFile */) {
113132                     var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
113133                     if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) {
113134                         for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) {
113135                             var symbol = _b[_a];
113136                             symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ };
113137                             symbols.push(symbol);
113138                             symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.SuggestedClassMembers;
113139                         }
113140                     }
113141                 }
113142                 if (shouldOfferImportCompletions()) {
113143                     var lowerCaseTokenText_1 = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : "";
113144                     var autoImportSuggestions = getSymbolsFromOtherSourceFileExports(program.getCompilerOptions().target, host);
113145                     if (!detailsEntryId && importSuggestionsCache) {
113146                         importSuggestionsCache.set(sourceFile.fileName, autoImportSuggestions, host.getProjectVersion && host.getProjectVersion());
113147                     }
113148                     autoImportSuggestions.forEach(function (_a) {
113149                         var symbol = _a.symbol, symbolName = _a.symbolName, skipFilter = _a.skipFilter, origin = _a.origin;
113150                         if (detailsEntryId) {
113151                             if (detailsEntryId.source && ts.stripQuotes(origin.moduleSymbol.name) !== detailsEntryId.source) {
113152                                 return;
113153                             }
113154                         }
113155                         else if (!skipFilter && !stringContainsCharactersInOrder(symbolName.toLowerCase(), lowerCaseTokenText_1)) {
113156                             return;
113157                         }
113158                         var symbolId = ts.getSymbolId(symbol);
113159                         symbols.push(symbol);
113160                         symbolToOriginInfoMap[symbolId] = origin;
113161                         symbolToSortTextMap[symbolId] = SortText.AutoImportSuggestions;
113162                     });
113163                 }
113164                 filterGlobalCompletion(symbols);
113165             }
113166             function shouldOfferImportCompletions() {
113167                 // If not already a module, must have modules enabled.
113168                 if (!preferences.includeCompletionsForModuleExports)
113169                     return false;
113170                 // If already using ES6 modules, OK to continue using them.
113171                 if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator)
113172                     return true;
113173                 // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK.
113174                 if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))
113175                     return true;
113176                 // If some file is using ES6 modules, assume that it's OK to add more.
113177                 return ts.programContainsModules(program);
113178             }
113179             function isSnippetScope(scopeNode) {
113180                 switch (scopeNode.kind) {
113181                     case 290 /* SourceFile */:
113182                     case 211 /* TemplateExpression */:
113183                     case 276 /* JsxExpression */:
113184                     case 223 /* Block */:
113185                         return true;
113186                     default:
113187                         return ts.isStatement(scopeNode);
113188                 }
113189             }
113190             function filterGlobalCompletion(symbols) {
113191                 var isTypeOnly = isTypeOnlyCompletion();
113192                 if (isTypeOnly) {
113193                     keywordFilters = isTypeAssertion()
113194                         ? 6 /* TypeAssertionKeywords */
113195                         : 7 /* TypeKeywords */;
113196                 }
113197                 ts.filterMutate(symbols, function (symbol) {
113198                     if (!ts.isSourceFile(location)) {
113199                         // export = /**/ here we want to get all meanings, so any symbol is ok
113200                         if (ts.isExportAssignment(location.parent)) {
113201                             return true;
113202                         }
113203                         symbol = ts.skipAlias(symbol, typeChecker);
113204                         // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace)
113205                         if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) {
113206                             return !!(symbol.flags & 1920 /* Namespace */);
113207                         }
113208                         if (isTypeOnly) {
113209                             // It's a type, but you can reach it by namespace.type as well
113210                             return symbolCanBeReferencedAtTypeLocation(symbol);
113211                         }
113212                     }
113213                     // expressions are value space (which includes the value namespaces)
113214                     return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */);
113215                 });
113216             }
113217             function isTypeAssertion() {
113218                 return ts.isAssertionExpression(contextToken.parent);
113219             }
113220             function isTypeOnlyCompletion() {
113221                 return insideJsDocTagTypeExpression
113222                     || !isContextTokenValueLocation(contextToken) &&
113223                         (ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)
113224                             || ts.isPartOfTypeNode(location)
113225                             || isContextTokenTypeLocation(contextToken));
113226             }
113227             function isContextTokenValueLocation(contextToken) {
113228                 return contextToken &&
113229                     contextToken.kind === 108 /* TypeOfKeyword */ &&
113230                     (contextToken.parent.kind === 172 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent));
113231             }
113232             function isContextTokenTypeLocation(contextToken) {
113233                 if (contextToken) {
113234                     var parentKind = contextToken.parent.kind;
113235                     switch (contextToken.kind) {
113236                         case 58 /* ColonToken */:
113237                             return parentKind === 159 /* PropertyDeclaration */ ||
113238                                 parentKind === 158 /* PropertySignature */ ||
113239                                 parentKind === 156 /* Parameter */ ||
113240                                 parentKind === 242 /* VariableDeclaration */ ||
113241                                 ts.isFunctionLikeKind(parentKind);
113242                         case 62 /* EqualsToken */:
113243                             return parentKind === 247 /* TypeAliasDeclaration */;
113244                         case 123 /* AsKeyword */:
113245                             return parentKind === 217 /* AsExpression */;
113246                         case 29 /* LessThanToken */:
113247                             return parentKind === 169 /* TypeReference */ ||
113248                                 parentKind === 199 /* TypeAssertionExpression */;
113249                         case 90 /* ExtendsKeyword */:
113250                             return parentKind === 155 /* TypeParameter */;
113251                     }
113252                 }
113253                 return false;
113254             }
113255             /** True if symbol is a type or a module containing at least one type. */
113256             function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) {
113257                 if (seenModules === void 0) { seenModules = ts.createMap(); }
113258                 var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker);
113259                 return !!(sym.flags & 788968 /* Type */) ||
113260                     !!(sym.flags & 1536 /* Module */) &&
113261                         ts.addToSeen(seenModules, ts.getSymbolId(sym)) &&
113262                         typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); });
113263             }
113264             /**
113265              * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates"
113266              * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but
113267              * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out,
113268              * if and only if the the first can be imported (it may be excluded due to package.json filtering in
113269              * `codefix.forEachExternalModuleToImportFrom`).
113270              *
113271              * Example. Imagine a chain of node_modules re-exporting one original symbol:
113272              *
113273              * ```js
113274              *  node_modules/x/index.js         node_modules/y/index.js           node_modules/z/index.js
113275              * +-----------------------+      +--------------------------+      +--------------------------+
113276              * |                       |      |                          |      |                          |
113277              * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; |
113278              * |                       |      |                          |      |                          |
113279              * +-----------------------+      +--------------------------+      +--------------------------+
113280              * ```
113281              *
113282              * Also imagine three buckets, which we’ll reference soon:
113283              *
113284              * ```md
113285              * |                  |      |                      |      |                   |
113286              * |   **Bucket A**   |      |    **Bucket B**      |      |    **Bucket C**   |
113287              * |    Symbols to    |      | Aliases to symbols   |      | Symbols to return |
113288              * |    definitely    |      | in Buckets A or C    |      | if nothing better |
113289              * |      return      |      | (don’t return these) |      |    comes along    |
113290              * |__________________|      |______________________|      |___________________|
113291              * ```
113292              *
113293              * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it
113294              * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not
113295              * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we
113296              * may not be sure whether or not it should go in the list. So, we’ll take the following steps:
113297              *
113298              * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is
113299              *    already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B
113300              *    (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C.
113301              * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'.
113302              *    At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z'
113303              *    should never be returned in the final list, so put it in Bucket B.
113304              * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so
113305              *    we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out.
113306              *    Put this symbol in Bucket A.
113307              * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t
113308              *    occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move
113309              *    everything from Bucket C to Bucket A.
113310              */
113311             function getSymbolsFromOtherSourceFileExports(target, host) {
113312                 var cached = importSuggestionsCache && importSuggestionsCache.get(sourceFile.fileName, typeChecker, detailsEntryId && host.getProjectVersion ? host.getProjectVersion() : undefined);
113313                 if (cached) {
113314                     log("getSymbolsFromOtherSourceFileExports: Using cached list");
113315                     return cached;
113316                 }
113317                 var startTime = ts.timestamp();
113318                 log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : ""));
113319                 var seenResolvedModules = ts.createMap();
113320                 var seenExports = ts.createMap();
113321                 /** Bucket B */
113322                 var aliasesToAlreadyIncludedSymbols = ts.createMap();
113323                 /** Bucket C */
113324                 var aliasesToReturnIfOriginalsAreMissing = ts.createMap();
113325                 /** Bucket A */
113326                 var results = [];
113327                 /** Ids present in `results` for faster lookup */
113328                 var resultSymbolIds = ts.createMap();
113329                 ts.codefix.forEachExternalModuleToImportFrom(program, host, sourceFile, !detailsEntryId, function (moduleSymbol) {
113330                     // Perf -- ignore other modules if this is a request for details
113331                     if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) {
113332                         return;
113333                     }
113334                     var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol);
113335                     // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one.
113336                     if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) {
113337                         return;
113338                     }
113339                     // Don't add another completion for `export =` of a symbol that's already global.
113340                     // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`.
113341                     if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) {
113342                         pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true);
113343                     }
113344                     for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) {
113345                         var symbol = _a[_i];
113346                         var symbolId = ts.getSymbolId(symbol).toString();
113347                         // `getExportsAndPropertiesOfModule` can include duplicates
113348                         if (!ts.addToSeen(seenExports, symbolId)) {
113349                             continue;
113350                         }
113351                         // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion.
113352                         if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) {
113353                             continue;
113354                         }
113355                         // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols.
113356                         var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol;
113357                         // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check).
113358                         if (isExportStarFromReExport || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier; })) {
113359                             // Walk the export chain back one module (step 1 or 2 in diagrammed example).
113360                             // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that.
113361                             var nearestExportSymbol = isExportStarFromReExport ? symbol : getNearestExportSymbol(symbol);
113362                             if (!nearestExportSymbol)
113363                                 continue;
113364                             var nearestExportSymbolId = ts.getSymbolId(nearestExportSymbol).toString();
113365                             var symbolHasBeenSeen = resultSymbolIds.has(nearestExportSymbolId) || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId);
113366                             if (!symbolHasBeenSeen) {
113367                                 aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId, { alias: symbol, moduleSymbol: moduleSymbol });
113368                                 aliasesToAlreadyIncludedSymbols.set(symbolId, true);
113369                             }
113370                             else {
113371                                 // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here
113372                                 // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id.
113373                                 ts.addToSeen(aliasesToAlreadyIncludedSymbols, symbolId);
113374                             }
113375                         }
113376                         else {
113377                             // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example)
113378                             aliasesToReturnIfOriginalsAreMissing.delete(symbolId);
113379                             pushSymbol(symbol, moduleSymbol);
113380                         }
113381                     }
113382                 });
113383                 // By this point, any potential duplicates that were actually duplicates have been
113384                 // removed, so the rest need to be added. (Step 4 in diagrammed example)
113385                 aliasesToReturnIfOriginalsAreMissing.forEach(function (_a) {
113386                     var alias = _a.alias, moduleSymbol = _a.moduleSymbol;
113387                     return pushSymbol(alias, moduleSymbol);
113388                 });
113389                 log("getSymbolsFromOtherSourceFileExports: " + (ts.timestamp() - startTime));
113390                 return results;
113391                 function pushSymbol(symbol, moduleSymbol, skipFilter) {
113392                     if (skipFilter === void 0) { skipFilter = false; }
113393                     var isDefaultExport = symbol.escapedName === "default" /* Default */;
113394                     if (isDefaultExport) {
113395                         symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol;
113396                     }
113397                     if (typeChecker.isUndefinedSymbol(symbol)) {
113398                         return;
113399                     }
113400                     ts.addToSeen(resultSymbolIds, ts.getSymbolId(symbol));
113401                     var origin = { kind: 4 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport };
113402                     results.push({
113403                         symbol: symbol,
113404                         symbolName: ts.getNameForExportedSymbol(symbol, target),
113405                         origin: origin,
113406                         skipFilter: skipFilter,
113407                     });
113408                 }
113409             }
113410             function getNearestExportSymbol(fromSymbol) {
113411                 return findAlias(typeChecker, fromSymbol, function (alias) {
113412                     return ts.some(alias.declarations, function (d) { return ts.isExportSpecifier(d) || !!d.localSymbol; });
113413                 });
113414             }
113415             /**
113416              * True if you could remove some characters in `a` to get `b`.
113417              * E.g., true for "abcdef" and "bdf".
113418              * But not true for "abcdef" and "dbf".
113419              */
113420             function stringContainsCharactersInOrder(str, characters) {
113421                 if (characters.length === 0) {
113422                     return true;
113423                 }
113424                 var characterIndex = 0;
113425                 for (var strIndex = 0; strIndex < str.length; strIndex++) {
113426                     if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) {
113427                         characterIndex++;
113428                         if (characterIndex === characters.length) {
113429                             return true;
113430                         }
113431                     }
113432                 }
113433                 // Did not find all characters
113434                 return false;
113435             }
113436             /**
113437              * Finds the first node that "embraces" the position, so that one may
113438              * accurately aggregate locals from the closest containing scope.
113439              */
113440             function getScopeNode(initialToken, position, sourceFile) {
113441                 var scope = initialToken;
113442                 while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) {
113443                     scope = scope.parent;
113444                 }
113445                 return scope;
113446             }
113447             function isCompletionListBlocker(contextToken) {
113448                 var start = ts.timestamp();
113449                 var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
113450                     isSolelyIdentifierDefinitionLocation(contextToken) ||
113451                     isDotOfNumericLiteral(contextToken) ||
113452                     isInJsxText(contextToken);
113453                 log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start));
113454                 return result;
113455             }
113456             function isInJsxText(contextToken) {
113457                 if (contextToken.kind === 11 /* JsxText */) {
113458                     return true;
113459                 }
113460                 if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) {
113461                     if (contextToken.parent.kind === 268 /* JsxOpeningElement */) {
113462                         // Two possibilities:
113463                         //   1. <div>/**/
113464                         //      - contextToken: GreaterThanToken (before cursor)
113465                         //      - location: JSXElement
113466                         //      - different parents (JSXOpeningElement, JSXElement)
113467                         //   2. <Component<string> /**/>
113468                         //      - contextToken: GreaterThanToken (before cursor)
113469                         //      - location: GreaterThanToken (after cursor)
113470                         //      - same parent (JSXOpeningElement)
113471                         return location.parent.kind !== 268 /* JsxOpeningElement */;
113472                     }
113473                     if (contextToken.parent.kind === 269 /* JsxClosingElement */ || contextToken.parent.kind === 267 /* JsxSelfClosingElement */) {
113474                         return !!contextToken.parent.parent && contextToken.parent.parent.kind === 266 /* JsxElement */;
113475                     }
113476                 }
113477                 return false;
113478             }
113479             function isNewIdentifierDefinitionLocation(previousToken) {
113480                 if (previousToken) {
113481                     var containingNodeKind = previousToken.parent.kind;
113482                     // Previous token may have been a keyword that was converted to an identifier.
113483                     switch (keywordForNode(previousToken)) {
113484                         case 27 /* CommaToken */:
113485                             return containingNodeKind === 196 /* CallExpression */ // func( a, |
113486                                 || containingNodeKind === 162 /* Constructor */ // constructor( a, |   /* public, protected, private keywords are allowed here, so show completion */
113487                                 || containingNodeKind === 197 /* NewExpression */ // new C(a, |
113488                                 || containingNodeKind === 192 /* ArrayLiteralExpression */ // [a, |
113489                                 || containingNodeKind === 209 /* BinaryExpression */ // const x = (a, |
113490                                 || containingNodeKind === 170 /* FunctionType */; // var x: (s: string, list|
113491                         case 20 /* OpenParenToken */:
113492                             return containingNodeKind === 196 /* CallExpression */ // func( |
113493                                 || containingNodeKind === 162 /* Constructor */ // constructor( |
113494                                 || containingNodeKind === 197 /* NewExpression */ // new C(a|
113495                                 || containingNodeKind === 200 /* ParenthesizedExpression */ // const x = (a|
113496                                 || containingNodeKind === 182 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
113497                         case 22 /* OpenBracketToken */:
113498                             return containingNodeKind === 192 /* ArrayLiteralExpression */ // [ |
113499                                 || containingNodeKind === 167 /* IndexSignature */ // [ | : string ]
113500                                 || containingNodeKind === 154 /* ComputedPropertyName */; // [ |    /* this can become an index signature */
113501                         case 135 /* ModuleKeyword */: // module |
113502                         case 136 /* NamespaceKeyword */: // namespace |
113503                             return true;
113504                         case 24 /* DotToken */:
113505                             return containingNodeKind === 249 /* ModuleDeclaration */; // module A.|
113506                         case 18 /* OpenBraceToken */:
113507                             return containingNodeKind === 245 /* ClassDeclaration */; // class A{ |
113508                         case 62 /* EqualsToken */:
113509                             return containingNodeKind === 242 /* VariableDeclaration */ // const x = a|
113510                                 || containingNodeKind === 209 /* BinaryExpression */; // x = a|
113511                         case 15 /* TemplateHead */:
113512                             return containingNodeKind === 211 /* TemplateExpression */; // `aa ${|
113513                         case 16 /* TemplateMiddle */:
113514                             return containingNodeKind === 221 /* TemplateSpan */; // `aa ${10} dd ${|
113515                         case 119 /* PublicKeyword */:
113516                         case 117 /* PrivateKeyword */:
113517                         case 118 /* ProtectedKeyword */:
113518                             return containingNodeKind === 159 /* PropertyDeclaration */; // class A{ public |
113519                     }
113520                 }
113521                 return false;
113522             }
113523             function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) {
113524                 // To be "in" one of these literals, the position has to be:
113525                 //   1. entirely within the token text.
113526                 //   2. at the end position of an unterminated token.
113527                 //   3. at the end of a regular expression (due to trailing flags like '/foo/g').
113528                 return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) ||
113529                     position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken)));
113530             }
113531             /**
113532              * Aggregates relevant symbols for completion in object literals and object binding patterns.
113533              * Relevant symbols are stored in the captured 'symbols' variable.
113534              *
113535              * @returns true if 'symbols' was successfully populated; false otherwise.
113536              */
113537             function tryGetObjectLikeCompletionSymbols() {
113538                 var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken);
113539                 if (!objectLikeContainer)
113540                     return 0 /* Continue */;
113541                 // We're looking up possible property names from contextual/inferred/declared type.
113542                 completionKind = 0 /* ObjectPropertyDeclaration */;
113543                 var typeMembers;
113544                 var existingMembers;
113545                 if (objectLikeContainer.kind === 193 /* ObjectLiteralExpression */) {
113546                     var instantiatedType = typeChecker.getContextualType(objectLikeContainer);
113547                     var completionsType = instantiatedType && typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */);
113548                     if (!instantiatedType || !completionsType)
113549                         return 2 /* Fail */;
113550                     isNewIdentifierLocation = ts.hasIndexSignature(instantiatedType || completionsType);
113551                     typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker);
113552                     existingMembers = objectLikeContainer.properties;
113553                 }
113554                 else {
113555                     ts.Debug.assert(objectLikeContainer.kind === 189 /* ObjectBindingPattern */);
113556                     // We are *only* completing on properties from the type being destructured.
113557                     isNewIdentifierLocation = false;
113558                     var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
113559                     if (!ts.isVariableLike(rootDeclaration))
113560                         return ts.Debug.fail("Root declaration is not variable-like.");
113561                     // We don't want to complete using the type acquired by the shape
113562                     // of the binding pattern; we are only interested in types acquired
113563                     // through type declaration or inference.
113564                     // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed -
113565                     // type of parameter will flow in from the contextual type of the function
113566                     var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 232 /* ForOfStatement */;
113567                     if (!canGetType && rootDeclaration.kind === 156 /* Parameter */) {
113568                         if (ts.isExpression(rootDeclaration.parent)) {
113569                             canGetType = !!typeChecker.getContextualType(rootDeclaration.parent);
113570                         }
113571                         else if (rootDeclaration.parent.kind === 161 /* MethodDeclaration */ || rootDeclaration.parent.kind === 164 /* SetAccessor */) {
113572                             canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent);
113573                         }
113574                     }
113575                     if (canGetType) {
113576                         var typeForObject_1 = typeChecker.getTypeAtLocation(objectLikeContainer);
113577                         if (!typeForObject_1)
113578                             return 2 /* Fail */;
113579                         // In a binding pattern, get only known properties (unless in the same scope).
113580                         // Everywhere else we will get all possible properties.
113581                         var containerClass_1 = ts.getContainingClass(objectLikeContainer);
113582                         typeMembers = typeChecker.getPropertiesOfType(typeForObject_1).filter(function (symbol) {
113583                             // either public
113584                             return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */)
113585                                 // or we're in it
113586                                 || containerClass_1 && ts.contains(typeForObject_1.symbol.declarations, containerClass_1);
113587                         });
113588                         existingMembers = objectLikeContainer.elements;
113589                     }
113590                 }
113591                 if (typeMembers && typeMembers.length > 0) {
113592                     // Add filtered items to the completion list
113593                     symbols = filterObjectMembersList(typeMembers, ts.Debug.checkDefined(existingMembers));
113594                 }
113595                 setSortTextToOptionalMember();
113596                 return 1 /* Success */;
113597             }
113598             /**
113599              * Aggregates relevant symbols for completion in import clauses and export clauses
113600              * whose declarations have a module specifier; for instance, symbols will be aggregated for
113601              *
113602              *      import { | } from "moduleName";
113603              *      export { a as foo, | } from "moduleName";
113604              *
113605              * but not for
113606              *
113607              *      export { | };
113608              *
113609              * Relevant symbols are stored in the captured 'symbols' variable.
113610              */
113611             function tryGetImportOrExportClauseCompletionSymbols() {
113612                 // `import { |` or `import { a as 0, | }`
113613                 var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */)
113614                     ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined;
113615                 if (!namedImportsOrExports)
113616                     return 0 /* Continue */;
113617                 // try to show exported member for imported/re-exported module
113618                 var moduleSpecifier = (namedImportsOrExports.kind === 257 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier;
113619                 if (!moduleSpecifier)
113620                     return namedImportsOrExports.kind === 257 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */;
113621                 var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217
113622                 if (!moduleSpecifierSymbol)
113623                     return 2 /* Fail */;
113624                 completionKind = 3 /* MemberLike */;
113625                 isNewIdentifierLocation = false;
113626                 var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
113627                 var existing = ts.arrayToSet(namedImportsOrExports.elements, function (n) { return isCurrentlyEditingNode(n) ? undefined : (n.propertyName || n.name).escapedText; });
113628                 symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); });
113629                 return 1 /* Success */;
113630             }
113631             /**
113632              * Adds local declarations for completions in named exports:
113633              *
113634              *   export { | };
113635              *
113636              * Does not check for the absence of a module specifier (`export {} from "./other"`)
113637              * because `tryGetImportOrExportClauseCompletionSymbols` runs first and handles that,
113638              * preventing this function from running.
113639              */
113640             function tryGetLocalNamedExportCompletionSymbols() {
113641                 var _a;
113642                 var namedExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */)
113643                     ? ts.tryCast(contextToken.parent, ts.isNamedExports)
113644                     : undefined;
113645                 if (!namedExports) {
113646                     return 0 /* Continue */;
113647                 }
113648                 var localsContainer = ts.findAncestor(namedExports, ts.or(ts.isSourceFile, ts.isModuleDeclaration));
113649                 completionKind = 5 /* None */;
113650                 isNewIdentifierLocation = false;
113651                 (_a = localsContainer.locals) === null || _a === void 0 ? void 0 : _a.forEach(function (symbol, name) {
113652                     var _a, _b;
113653                     symbols.push(symbol);
113654                     if ((_b = (_a = localsContainer.symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has(name)) {
113655                         symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.OptionalMember;
113656                     }
113657                 });
113658                 return 1 /* Success */;
113659             }
113660             /**
113661              * Aggregates relevant symbols for completion in class declaration
113662              * Relevant symbols are stored in the captured 'symbols' variable.
113663              */
113664             function tryGetClassLikeCompletionSymbols() {
113665                 var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position);
113666                 if (!decl)
113667                     return 0 /* Continue */;
113668                 // We're looking up possible property names from parent type.
113669                 completionKind = 3 /* MemberLike */;
113670                 // Declaring new property/method/accessor
113671                 isNewIdentifierLocation = true;
113672                 keywordFilters = contextToken.kind === 41 /* AsteriskToken */ ? 0 /* None */ :
113673                     ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */;
113674                 // If you're in an interface you don't want to repeat things from super-interface. So just stop here.
113675                 if (!ts.isClassLike(decl))
113676                     return 1 /* Success */;
113677                 var classElement = contextToken.kind === 26 /* SemicolonToken */ ? contextToken.parent.parent : contextToken.parent;
113678                 var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */;
113679                 // If this is context token is not something we are editing now, consider if this would lead to be modifier
113680                 if (contextToken.kind === 75 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) {
113681                     switch (contextToken.getText()) {
113682                         case "private":
113683                             classElementModifierFlags = classElementModifierFlags | 8 /* Private */;
113684                             break;
113685                         case "static":
113686                             classElementModifierFlags = classElementModifierFlags | 32 /* Static */;
113687                             break;
113688                     }
113689                 }
113690                 // No member list for private methods
113691                 if (!(classElementModifierFlags & 8 /* Private */)) {
113692                     // List of property symbols of base type that are not private and already implemented
113693                     var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) {
113694                         var type = typeChecker.getTypeAtLocation(baseTypeNode);
113695                         return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type);
113696                     });
113697                     symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags);
113698                 }
113699                 return 1 /* Success */;
113700             }
113701             /**
113702              * Returns the immediate owning object literal or binding pattern of a context token,
113703              * on the condition that one exists and that the context implies completion should be given.
113704              */
113705             function tryGetObjectLikeCompletionContainer(contextToken) {
113706                 if (contextToken) {
113707                     var parent = contextToken.parent;
113708                     switch (contextToken.kind) {
113709                         case 18 /* OpenBraceToken */: // const x = { |
113710                         case 27 /* CommaToken */: // const x = { a: 0, |
113711                             if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) {
113712                                 return parent;
113713                             }
113714                             break;
113715                         case 41 /* AsteriskToken */:
113716                             return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined;
113717                         case 75 /* Identifier */:
113718                             return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent)
113719                                 ? contextToken.parent.parent : undefined;
113720                     }
113721                 }
113722                 return undefined;
113723             }
113724             function isConstructorParameterCompletion(node) {
113725                 return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent)
113726                     && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node));
113727             }
113728             /**
113729              * Returns the immediate owning class declaration of a context token,
113730              * on the condition that one exists and that the context implies completion should be given.
113731              */
113732             function tryGetConstructorLikeCompletionContainer(contextToken) {
113733                 if (contextToken) {
113734                     var parent = contextToken.parent;
113735                     switch (contextToken.kind) {
113736                         case 20 /* OpenParenToken */:
113737                         case 27 /* CommaToken */:
113738                             return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined;
113739                         default:
113740                             if (isConstructorParameterCompletion(contextToken)) {
113741                                 return parent.parent;
113742                             }
113743                     }
113744                 }
113745                 return undefined;
113746             }
113747             function tryGetFunctionLikeBodyCompletionContainer(contextToken) {
113748                 if (contextToken) {
113749                     var prev_1;
113750                     var container = ts.findAncestor(contextToken.parent, function (node) {
113751                         if (ts.isClassLike(node)) {
113752                             return "quit";
113753                         }
113754                         if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) {
113755                             return true;
113756                         }
113757                         prev_1 = node;
113758                         return false;
113759                     });
113760                     return container && container;
113761                 }
113762             }
113763             function tryGetContainingJsxElement(contextToken) {
113764                 if (contextToken) {
113765                     var parent = contextToken.parent;
113766                     switch (contextToken.kind) {
113767                         case 31 /* GreaterThanToken */: // End of a type argument list
113768                         case 30 /* LessThanSlashToken */:
113769                         case 43 /* SlashToken */:
113770                         case 75 /* Identifier */:
113771                         case 194 /* PropertyAccessExpression */:
113772                         case 274 /* JsxAttributes */:
113773                         case 273 /* JsxAttribute */:
113774                         case 275 /* JsxSpreadAttribute */:
113775                             if (parent && (parent.kind === 267 /* JsxSelfClosingElement */ || parent.kind === 268 /* JsxOpeningElement */)) {
113776                                 if (contextToken.kind === 31 /* GreaterThanToken */) {
113777                                     var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined);
113778                                     if (!parent.typeArguments || (precedingToken && precedingToken.kind === 43 /* SlashToken */))
113779                                         break;
113780                                 }
113781                                 return parent;
113782                             }
113783                             else if (parent.kind === 273 /* JsxAttribute */) {
113784                                 // Currently we parse JsxOpeningLikeElement as:
113785                                 //      JsxOpeningLikeElement
113786                                 //          attributes: JsxAttributes
113787                                 //             properties: NodeArray<JsxAttributeLike>
113788                                 return parent.parent.parent;
113789                             }
113790                             break;
113791                         // The context token is the closing } or " of an attribute, which means
113792                         // its parent is a JsxExpression, whose parent is a JsxAttribute,
113793                         // whose parent is a JsxOpeningLikeElement
113794                         case 10 /* StringLiteral */:
113795                             if (parent && ((parent.kind === 273 /* JsxAttribute */) || (parent.kind === 275 /* JsxSpreadAttribute */))) {
113796                                 // Currently we parse JsxOpeningLikeElement as:
113797                                 //      JsxOpeningLikeElement
113798                                 //          attributes: JsxAttributes
113799                                 //             properties: NodeArray<JsxAttributeLike>
113800                                 return parent.parent.parent;
113801                             }
113802                             break;
113803                         case 19 /* CloseBraceToken */:
113804                             if (parent &&
113805                                 parent.kind === 276 /* JsxExpression */ &&
113806                                 parent.parent && parent.parent.kind === 273 /* JsxAttribute */) {
113807                                 // Currently we parse JsxOpeningLikeElement as:
113808                                 //      JsxOpeningLikeElement
113809                                 //          attributes: JsxAttributes
113810                                 //             properties: NodeArray<JsxAttributeLike>
113811                                 //                  each JsxAttribute can have initializer as JsxExpression
113812                                 return parent.parent.parent.parent;
113813                             }
113814                             if (parent && parent.kind === 275 /* JsxSpreadAttribute */) {
113815                                 // Currently we parse JsxOpeningLikeElement as:
113816                                 //      JsxOpeningLikeElement
113817                                 //          attributes: JsxAttributes
113818                                 //             properties: NodeArray<JsxAttributeLike>
113819                                 return parent.parent.parent;
113820                             }
113821                             break;
113822                     }
113823                 }
113824                 return undefined;
113825             }
113826             /**
113827              * @returns true if we are certain that the currently edited location must define a new location; false otherwise.
113828              */
113829             function isSolelyIdentifierDefinitionLocation(contextToken) {
113830                 var parent = contextToken.parent;
113831                 var containingNodeKind = parent.kind;
113832                 switch (contextToken.kind) {
113833                     case 27 /* CommaToken */:
113834                         return containingNodeKind === 242 /* VariableDeclaration */ ||
113835                             isVariableDeclarationListButNotTypeArgument(contextToken) ||
113836                             containingNodeKind === 225 /* VariableStatement */ ||
113837                             containingNodeKind === 248 /* EnumDeclaration */ || // enum a { foo, |
113838                             isFunctionLikeButNotConstructor(containingNodeKind) ||
113839                             containingNodeKind === 246 /* InterfaceDeclaration */ || // interface A<T, |
113840                             containingNodeKind === 190 /* ArrayBindingPattern */ || // var [x, y|
113841                             containingNodeKind === 247 /* TypeAliasDeclaration */ || // type Map, K, |
113842                             // class A<T, |
113843                             // var C = class D<T, |
113844                             (ts.isClassLike(parent) &&
113845                                 !!parent.typeParameters &&
113846                                 parent.typeParameters.end >= contextToken.pos);
113847                     case 24 /* DotToken */:
113848                         return containingNodeKind === 190 /* ArrayBindingPattern */; // var [.|
113849                     case 58 /* ColonToken */:
113850                         return containingNodeKind === 191 /* BindingElement */; // var {x :html|
113851                     case 22 /* OpenBracketToken */:
113852                         return containingNodeKind === 190 /* ArrayBindingPattern */; // var [x|
113853                     case 20 /* OpenParenToken */:
113854                         return containingNodeKind === 280 /* CatchClause */ ||
113855                             isFunctionLikeButNotConstructor(containingNodeKind);
113856                     case 18 /* OpenBraceToken */:
113857                         return containingNodeKind === 248 /* EnumDeclaration */; // enum a { |
113858                     case 29 /* LessThanToken */:
113859                         return containingNodeKind === 245 /* ClassDeclaration */ || // class A< |
113860                             containingNodeKind === 214 /* ClassExpression */ || // var C = class D< |
113861                             containingNodeKind === 246 /* InterfaceDeclaration */ || // interface A< |
113862                             containingNodeKind === 247 /* TypeAliasDeclaration */ || // type List< |
113863                             ts.isFunctionLikeKind(containingNodeKind);
113864                     case 120 /* StaticKeyword */:
113865                         return containingNodeKind === 159 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent);
113866                     case 25 /* DotDotDotToken */:
113867                         return containingNodeKind === 156 /* Parameter */ ||
113868                             (!!parent.parent && parent.parent.kind === 190 /* ArrayBindingPattern */); // var [...z|
113869                     case 119 /* PublicKeyword */:
113870                     case 117 /* PrivateKeyword */:
113871                     case 118 /* ProtectedKeyword */:
113872                         return containingNodeKind === 156 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent);
113873                     case 123 /* AsKeyword */:
113874                         return containingNodeKind === 258 /* ImportSpecifier */ ||
113875                             containingNodeKind === 263 /* ExportSpecifier */ ||
113876                             containingNodeKind === 256 /* NamespaceImport */;
113877                     case 131 /* GetKeyword */:
113878                     case 142 /* SetKeyword */:
113879                         return !isFromObjectTypeDeclaration(contextToken);
113880                     case 80 /* ClassKeyword */:
113881                     case 88 /* EnumKeyword */:
113882                     case 114 /* InterfaceKeyword */:
113883                     case 94 /* FunctionKeyword */:
113884                     case 109 /* VarKeyword */:
113885                     case 96 /* ImportKeyword */:
113886                     case 115 /* LetKeyword */:
113887                     case 81 /* ConstKeyword */:
113888                     case 145 /* TypeKeyword */: // type htm|
113889                         return true;
113890                     case 41 /* AsteriskToken */:
113891                         return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent);
113892                 }
113893                 // If the previous token is keyword correspoding to class member completion keyword
113894                 // there will be completion available here
113895                 if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) {
113896                     return false;
113897                 }
113898                 if (isConstructorParameterCompletion(contextToken)) {
113899                     // constructor parameter completion is available only if
113900                     // - its modifier of the constructor parameter or
113901                     // - its name of the parameter and not being edited
113902                     // eg. constructor(a |<- this shouldnt show completion
113903                     if (!ts.isIdentifier(contextToken) ||
113904                         ts.isParameterPropertyModifier(keywordForNode(contextToken)) ||
113905                         isCurrentlyEditingNode(contextToken)) {
113906                         return false;
113907                     }
113908                 }
113909                 // Previous token may have been a keyword that was converted to an identifier.
113910                 switch (keywordForNode(contextToken)) {
113911                     case 122 /* AbstractKeyword */:
113912                     case 80 /* ClassKeyword */:
113913                     case 81 /* ConstKeyword */:
113914                     case 130 /* DeclareKeyword */:
113915                     case 88 /* EnumKeyword */:
113916                     case 94 /* FunctionKeyword */:
113917                     case 114 /* InterfaceKeyword */:
113918                     case 115 /* LetKeyword */:
113919                     case 117 /* PrivateKeyword */:
113920                     case 118 /* ProtectedKeyword */:
113921                     case 119 /* PublicKeyword */:
113922                     case 120 /* StaticKeyword */:
113923                     case 109 /* VarKeyword */:
113924                         return true;
113925                     case 126 /* AsyncKeyword */:
113926                         return ts.isPropertyDeclaration(contextToken.parent);
113927                 }
113928                 return ts.isDeclarationName(contextToken)
113929                     && !ts.isJsxAttribute(contextToken.parent)
113930                     // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`.
113931                     // If `contextToken !== previousToken`, this is `class C ex/**/`.
113932                     && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end));
113933             }
113934             function isFunctionLikeButNotConstructor(kind) {
113935                 return ts.isFunctionLikeKind(kind) && kind !== 162 /* Constructor */;
113936             }
113937             function isDotOfNumericLiteral(contextToken) {
113938                 if (contextToken.kind === 8 /* NumericLiteral */) {
113939                     var text = contextToken.getFullText();
113940                     return text.charAt(text.length - 1) === ".";
113941                 }
113942                 return false;
113943             }
113944             function isVariableDeclarationListButNotTypeArgument(node) {
113945                 return node.parent.kind === 243 /* VariableDeclarationList */
113946                     && !ts.isPossiblyTypeArgumentPosition(node, sourceFile, typeChecker);
113947             }
113948             /**
113949              * Filters out completion suggestions for named imports or exports.
113950              *
113951              * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations
113952              *          do not occur at the current position and have not otherwise been typed.
113953              */
113954             function filterObjectMembersList(contextualMemberSymbols, existingMembers) {
113955                 if (existingMembers.length === 0) {
113956                     return contextualMemberSymbols;
113957                 }
113958                 var membersDeclaredBySpreadAssignment = ts.createMap();
113959                 var existingMemberNames = ts.createUnderscoreEscapedMap();
113960                 for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) {
113961                     var m = existingMembers_1[_i];
113962                     // Ignore omitted expressions for missing members
113963                     if (m.kind !== 281 /* PropertyAssignment */ &&
113964                         m.kind !== 282 /* ShorthandPropertyAssignment */ &&
113965                         m.kind !== 191 /* BindingElement */ &&
113966                         m.kind !== 161 /* MethodDeclaration */ &&
113967                         m.kind !== 163 /* GetAccessor */ &&
113968                         m.kind !== 164 /* SetAccessor */ &&
113969                         m.kind !== 283 /* SpreadAssignment */) {
113970                         continue;
113971                     }
113972                     // If this is the current item we are editing right now, do not filter it out
113973                     if (isCurrentlyEditingNode(m)) {
113974                         continue;
113975                     }
113976                     var existingName = void 0;
113977                     if (ts.isSpreadAssignment(m)) {
113978                         setMembersDeclaredBySpreadAssignment(m, membersDeclaredBySpreadAssignment);
113979                     }
113980                     else if (ts.isBindingElement(m) && m.propertyName) {
113981                         // include only identifiers in completion list
113982                         if (m.propertyName.kind === 75 /* Identifier */) {
113983                             existingName = m.propertyName.escapedText;
113984                         }
113985                     }
113986                     else {
113987                         // TODO: Account for computed property name
113988                         // NOTE: if one only performs this step when m.name is an identifier,
113989                         // things like '__proto__' are not filtered out.
113990                         var name = ts.getNameOfDeclaration(m);
113991                         existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
113992                     }
113993                     existingMemberNames.set(existingName, true); // TODO: GH#18217
113994                 }
113995                 var filteredSymbols = contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); });
113996                 setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
113997                 return filteredSymbols;
113998             }
113999             function setMembersDeclaredBySpreadAssignment(declaration, membersDeclaredBySpreadAssignment) {
114000                 var expression = declaration.expression;
114001                 var symbol = typeChecker.getSymbolAtLocation(expression);
114002                 var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression);
114003                 var properties = type && type.properties;
114004                 if (properties) {
114005                     properties.forEach(function (property) {
114006                         membersDeclaredBySpreadAssignment.set(property.name, true);
114007                     });
114008                 }
114009             }
114010             // Set SortText to OptionalMember if it is an optional member
114011             function setSortTextToOptionalMember() {
114012                 symbols.forEach(function (m) {
114013                     if (m.flags & 16777216 /* Optional */) {
114014                         symbolToSortTextMap[ts.getSymbolId(m)] = symbolToSortTextMap[ts.getSymbolId(m)] || SortText.OptionalMember;
114015                     }
114016                 });
114017             }
114018             // Set SortText to MemberDeclaredBySpreadAssignment if it is fulfilled by spread assignment
114019             function setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, contextualMemberSymbols) {
114020                 if (membersDeclaredBySpreadAssignment.size === 0) {
114021                     return;
114022                 }
114023                 for (var _i = 0, contextualMemberSymbols_1 = contextualMemberSymbols; _i < contextualMemberSymbols_1.length; _i++) {
114024                     var contextualMemberSymbol = contextualMemberSymbols_1[_i];
114025                     if (membersDeclaredBySpreadAssignment.has(contextualMemberSymbol.name)) {
114026                         symbolToSortTextMap[ts.getSymbolId(contextualMemberSymbol)] = SortText.MemberDeclaredBySpreadAssignment;
114027                     }
114028                 }
114029             }
114030             /**
114031              * Filters out completion suggestions for class elements.
114032              *
114033              * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags
114034              */
114035             function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) {
114036                 var existingMemberNames = ts.createUnderscoreEscapedMap();
114037                 for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) {
114038                     var m = existingMembers_2[_i];
114039                     // Ignore omitted expressions for missing members
114040                     if (m.kind !== 159 /* PropertyDeclaration */ &&
114041                         m.kind !== 161 /* MethodDeclaration */ &&
114042                         m.kind !== 163 /* GetAccessor */ &&
114043                         m.kind !== 164 /* SetAccessor */) {
114044                         continue;
114045                     }
114046                     // If this is the current item we are editing right now, do not filter it out
114047                     if (isCurrentlyEditingNode(m)) {
114048                         continue;
114049                     }
114050                     // Dont filter member even if the name matches if it is declared private in the list
114051                     if (ts.hasModifier(m, 8 /* Private */)) {
114052                         continue;
114053                     }
114054                     // do not filter it out if the static presence doesnt match
114055                     if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) {
114056                         continue;
114057                     }
114058                     var existingName = ts.getPropertyNameForPropertyNameNode(m.name);
114059                     if (existingName) {
114060                         existingMemberNames.set(existingName, true);
114061                     }
114062                 }
114063                 return baseSymbols.filter(function (propertySymbol) {
114064                     return !existingMemberNames.has(propertySymbol.escapedName) &&
114065                         !!propertySymbol.declarations &&
114066                         !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) &&
114067                         !ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration);
114068                 });
114069             }
114070             /**
114071              * Filters out completion suggestions from 'symbols' according to existing JSX attributes.
114072              *
114073              * @returns Symbols to be suggested in a JSX element, barring those whose attributes
114074              *          do not occur at the current position and have not otherwise been typed.
114075              */
114076             function filterJsxAttributes(symbols, attributes) {
114077                 var seenNames = ts.createUnderscoreEscapedMap();
114078                 var membersDeclaredBySpreadAssignment = ts.createMap();
114079                 for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {
114080                     var attr = attributes_1[_i];
114081                     // If this is the current item we are editing right now, do not filter it out
114082                     if (isCurrentlyEditingNode(attr)) {
114083                         continue;
114084                     }
114085                     if (attr.kind === 273 /* JsxAttribute */) {
114086                         seenNames.set(attr.name.escapedText, true);
114087                     }
114088                     else if (ts.isJsxSpreadAttribute(attr)) {
114089                         setMembersDeclaredBySpreadAssignment(attr, membersDeclaredBySpreadAssignment);
114090                     }
114091                 }
114092                 var filteredSymbols = symbols.filter(function (a) { return !seenNames.get(a.escapedName); });
114093                 setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
114094                 return filteredSymbols;
114095             }
114096             function isCurrentlyEditingNode(node) {
114097                 return node.getStart(sourceFile) <= position && position <= node.getEnd();
114098             }
114099         }
114100         function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) {
114101             var name = originIsExport(origin) ? ts.getNameForExportedSymbol(symbol, target) : symbol.name;
114102             if (name === undefined
114103                 // If the symbol is external module, don't show it in the completion list
114104                 // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there)
114105                 || symbol.flags & 1536 /* Module */ && ts.isSingleOrDoubleQuote(name.charCodeAt(0))
114106                 // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@"
114107                 || ts.isKnownSymbol(symbol)) {
114108                 return undefined;
114109             }
114110             var validNameResult = { name: name, needsConvertPropertyAccess: false };
114111             if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
114112                 return validNameResult;
114113             }
114114             switch (kind) {
114115                 case 3 /* MemberLike */:
114116                     return undefined;
114117                 case 0 /* ObjectPropertyDeclaration */:
114118                     // TODO: GH#18169
114119                     return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
114120                 case 2 /* PropertyAccess */:
114121                 case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name.
114122                     // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547
114123                     return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true };
114124                 case 5 /* None */:
114125                 case 4 /* String */:
114126                     return validNameResult;
114127                 default:
114128                     ts.Debug.assertNever(kind);
114129             }
114130         }
114131         // A cache of completion entries for keywords, these do not change between sessions
114132         var _keywordCompletions = [];
114133         var allKeywordsCompletions = ts.memoize(function () {
114134             var res = [];
114135             for (var i = 77 /* FirstKeyword */; i <= 152 /* LastKeyword */; i++) {
114136                 res.push({
114137                     name: ts.tokenToString(i),
114138                     kind: "keyword" /* keyword */,
114139                     kindModifiers: "" /* none */,
114140                     sortText: SortText.GlobalsOrKeywords
114141                 });
114142             }
114143             return res;
114144         });
114145         function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
114146             if (!filterOutTsOnlyKeywords)
114147                 return getTypescriptKeywordCompletions(keywordFilter);
114148             var index = keywordFilter + 7 /* Last */ + 1;
114149             return _keywordCompletions[index] ||
114150                 (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
114151                     .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); }));
114152         }
114153         function getTypescriptKeywordCompletions(keywordFilter) {
114154             return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
114155                 var kind = ts.stringToToken(entry.name);
114156                 switch (keywordFilter) {
114157                     case 0 /* None */:
114158                         return false;
114159                     case 1 /* All */:
114160                         return isFunctionLikeBodyKeyword(kind)
114161                             || kind === 130 /* DeclareKeyword */
114162                             || kind === 135 /* ModuleKeyword */
114163                             || kind === 145 /* TypeKeyword */
114164                             || kind === 136 /* NamespaceKeyword */
114165                             || kind === 123 /* AsKeyword */
114166                             || ts.isTypeKeyword(kind) && kind !== 146 /* UndefinedKeyword */;
114167                     case 5 /* FunctionLikeBodyKeywords */:
114168                         return isFunctionLikeBodyKeyword(kind);
114169                     case 2 /* ClassElementKeywords */:
114170                         return isClassMemberCompletionKeyword(kind);
114171                     case 3 /* InterfaceElementKeywords */:
114172                         return isInterfaceOrTypeLiteralCompletionKeyword(kind);
114173                     case 4 /* ConstructorParameterKeywords */:
114174                         return ts.isParameterPropertyModifier(kind);
114175                     case 6 /* TypeAssertionKeywords */:
114176                         return ts.isTypeKeyword(kind) || kind === 81 /* ConstKeyword */;
114177                     case 7 /* TypeKeywords */:
114178                         return ts.isTypeKeyword(kind);
114179                     default:
114180                         return ts.Debug.assertNever(keywordFilter);
114181                 }
114182             }));
114183         }
114184         function isTypeScriptOnlyKeyword(kind) {
114185             switch (kind) {
114186                 case 122 /* AbstractKeyword */:
114187                 case 125 /* AnyKeyword */:
114188                 case 151 /* BigIntKeyword */:
114189                 case 128 /* BooleanKeyword */:
114190                 case 130 /* DeclareKeyword */:
114191                 case 88 /* EnumKeyword */:
114192                 case 150 /* GlobalKeyword */:
114193                 case 113 /* ImplementsKeyword */:
114194                 case 132 /* InferKeyword */:
114195                 case 114 /* InterfaceKeyword */:
114196                 case 133 /* IsKeyword */:
114197                 case 134 /* KeyOfKeyword */:
114198                 case 135 /* ModuleKeyword */:
114199                 case 136 /* NamespaceKeyword */:
114200                 case 137 /* NeverKeyword */:
114201                 case 140 /* NumberKeyword */:
114202                 case 141 /* ObjectKeyword */:
114203                 case 117 /* PrivateKeyword */:
114204                 case 118 /* ProtectedKeyword */:
114205                 case 119 /* PublicKeyword */:
114206                 case 138 /* ReadonlyKeyword */:
114207                 case 143 /* StringKeyword */:
114208                 case 144 /* SymbolKeyword */:
114209                 case 145 /* TypeKeyword */:
114210                 case 147 /* UniqueKeyword */:
114211                 case 148 /* UnknownKeyword */:
114212                     return true;
114213                 default:
114214                     return false;
114215             }
114216         }
114217         function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
114218             return kind === 138 /* ReadonlyKeyword */;
114219         }
114220         function isClassMemberCompletionKeyword(kind) {
114221             switch (kind) {
114222                 case 122 /* AbstractKeyword */:
114223                 case 129 /* ConstructorKeyword */:
114224                 case 131 /* GetKeyword */:
114225                 case 142 /* SetKeyword */:
114226                 case 126 /* AsyncKeyword */:
114227                 case 130 /* DeclareKeyword */:
114228                     return true;
114229                 default:
114230                     return ts.isClassMemberModifier(kind);
114231             }
114232         }
114233         function isFunctionLikeBodyKeyword(kind) {
114234             return kind === 126 /* AsyncKeyword */
114235                 || kind === 127 /* AwaitKeyword */
114236                 || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind);
114237         }
114238         function keywordForNode(node) {
114239             return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind;
114240         }
114241         /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */
114242         function getJsDocTagAtPosition(node, position) {
114243             var jsdoc = ts.findAncestor(node, ts.isJSDoc);
114244             return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined);
114245         }
114246         function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) {
114247             var hasCompletionsType = completionsType && completionsType !== contextualType;
114248             var type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */)
114249                 ? checker.getUnionType([contextualType, completionsType])
114250                 : contextualType;
114251             var properties = type.isUnion()
114252                 ? checker.getAllPossiblePropertiesOfTypes(type.types.filter(function (memberType) {
114253                     // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals.
114254                     return !(memberType.flags & 131068 /* Primitive */ ||
114255                         checker.isArrayLikeType(memberType) ||
114256                         ts.typeHasCallOrConstructSignatures(memberType, checker) ||
114257                         checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj));
114258                 }))
114259                 : type.getApparentProperties();
114260             return hasCompletionsType ? properties.filter(hasDeclarationOtherThanSelf) : properties;
114261             // Filter out members whose only declaration is the object literal itself to avoid
114262             // self-fulfilling completions like:
114263             //
114264             // function f<T>(x: T) {}
114265             // f({ abc/**/: "" }) // `abc` is a member of `T` but only because it declares itself
114266             function hasDeclarationOtherThanSelf(member) {
114267                 return ts.some(member.declarations, function (decl) { return decl.parent !== obj; });
114268             }
114269         }
114270         /**
114271          * Gets all properties on a type, but if that type is a union of several types,
114272          * excludes array-like types or callable/constructable types.
114273          */
114274         function getPropertiesForCompletion(type, checker) {
114275             return type.isUnion()
114276                 ? ts.Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined")
114277                 : ts.Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
114278         }
114279         /**
114280          * Returns the immediate owning class declaration of a context token,
114281          * on the condition that one exists and that the context implies completion should be given.
114282          */
114283         function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) {
114284             // class c { method() { } | method2() { } }
114285             switch (location.kind) {
114286                 case 324 /* SyntaxList */:
114287                     return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
114288                 case 1 /* EndOfFileToken */:
114289                     var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
114290                     if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) {
114291                         return cls;
114292                     }
114293                     break;
114294                 case 75 /* Identifier */: {
114295                     // class c { public prop = c| }
114296                     if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) {
114297                         return undefined;
114298                     }
114299                     // class c extends React.Component { a: () => 1\n compon| }
114300                     if (isFromObjectTypeDeclaration(location)) {
114301                         return ts.findAncestor(location, ts.isObjectTypeDeclaration);
114302                     }
114303                 }
114304             }
114305             if (!contextToken)
114306                 return undefined;
114307             switch (contextToken.kind) {
114308                 case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ }
114309                     return undefined;
114310                 case 26 /* SemicolonToken */: // class c {getValue(): number; | }
114311                 case 19 /* CloseBraceToken */: // class c { method() { } | }
114312                     // class c { method() { } b| }
114313                     return isFromObjectTypeDeclaration(location) && location.parent.name === location
114314                         ? location.parent.parent
114315                         : ts.tryCast(location, ts.isObjectTypeDeclaration);
114316                 case 18 /* OpenBraceToken */: // class c { |
114317                 case 27 /* CommaToken */: // class c {getValue(): number, | }
114318                     return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration);
114319                 default:
114320                     if (!isFromObjectTypeDeclaration(contextToken)) {
114321                         // class c extends React.Component { a: () => 1\n| }
114322                         if (ts.getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== ts.getLineAndCharacterOfPosition(sourceFile, position).line && ts.isObjectTypeDeclaration(location)) {
114323                             return location;
114324                         }
114325                         return undefined;
114326                     }
114327                     var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword;
114328                     return (isValidKeyword(contextToken.kind) || contextToken.kind === 41 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217
114329                         ? contextToken.parent.parent : undefined;
114330             }
114331         }
114332         // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes
114333         function isFromObjectTypeDeclaration(node) {
114334             return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent);
114335         }
114336         function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
114337             switch (triggerCharacter) {
114338                 case ".":
114339                 case "@":
114340                     return true;
114341                 case '"':
114342                 case "'":
114343                 case "`":
114344                     // Only automatically bring up completions if this is an opening quote.
114345                     return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1;
114346                 case "#":
114347                     return !!contextToken && ts.isPrivateIdentifier(contextToken) && !!ts.getContainingClass(contextToken);
114348                 case "<":
114349                     // Opening JSX tag
114350                     return !!contextToken && contextToken.kind === 29 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent));
114351                 case "/":
114352                     return !!contextToken && (ts.isStringLiteralLike(contextToken)
114353                         ? !!ts.tryGetImportFromModuleSpecifier(contextToken)
114354                         : contextToken.kind === 43 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent));
114355                 default:
114356                     return ts.Debug.assertNever(triggerCharacter);
114357             }
114358         }
114359         function binaryExpressionMayBeOpenTag(_a) {
114360             var left = _a.left;
114361             return ts.nodeIsMissing(left);
114362         }
114363         function findAlias(typeChecker, symbol, predicate) {
114364             var currentAlias = symbol;
114365             while (currentAlias.flags & 2097152 /* Alias */ && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) {
114366                 if (predicate(currentAlias)) {
114367                     return currentAlias;
114368                 }
114369             }
114370         }
114371         /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */
114372         function isProbablyGlobalType(type, sourceFile, checker) {
114373             // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in
114374             // lib.webworker.d.ts, so checking against `self` is also a check against `window` when it exists.
114375             var selfSymbol = checker.resolveName("self", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false);
114376             if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) {
114377                 return true;
114378             }
114379             var globalSymbol = checker.resolveName("global", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false);
114380             if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) {
114381                 return true;
114382             }
114383             var globalThisSymbol = checker.resolveName("globalThis", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false);
114384             if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) {
114385                 return true;
114386             }
114387             return false;
114388         }
114389     })(Completions = ts.Completions || (ts.Completions = {}));
114390 })(ts || (ts = {}));
114391 var ts;
114392 (function (ts) {
114393     /* @internal */
114394     var DocumentHighlights;
114395     (function (DocumentHighlights) {
114396         function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) {
114397             var node = ts.getTouchingPropertyName(sourceFile, position);
114398             if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) {
114399                 // For a JSX element, just highlight the matching tag, not all references.
114400                 var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
114401                 var highlightSpans = [openingElement, closingElement].map(function (_a) {
114402                     var tagName = _a.tagName;
114403                     return getHighlightSpanForNode(tagName, sourceFile);
114404                 });
114405                 return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
114406             }
114407             return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile);
114408         }
114409         DocumentHighlights.getDocumentHighlights = getDocumentHighlights;
114410         function getHighlightSpanForNode(node, sourceFile) {
114411             return {
114412                 fileName: sourceFile.fileName,
114413                 textSpan: ts.createTextSpanFromNode(node, sourceFile),
114414                 kind: "none" /* none */
114415             };
114416         }
114417         function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
114418             var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; });
114419             var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet);
114420             if (!referenceEntries)
114421                 return undefined;
114422             var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; });
114423             return ts.arrayFrom(map.entries(), function (_a) {
114424                 var fileName = _a[0], highlightSpans = _a[1];
114425                 if (!sourceFilesSet.has(fileName)) {
114426                     ts.Debug.assert(program.redirectTargetsMap.has(fileName));
114427                     var redirectTarget_1 = program.getSourceFile(fileName);
114428                     var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; });
114429                     fileName = redirect.fileName;
114430                     ts.Debug.assert(sourceFilesSet.has(fileName));
114431                 }
114432                 return { fileName: fileName, highlightSpans: highlightSpans };
114433             });
114434         }
114435         function getSyntacticDocumentHighlights(node, sourceFile) {
114436             var highlightSpans = getHighlightSpans(node, sourceFile);
114437             return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
114438         }
114439         function getHighlightSpans(node, sourceFile) {
114440             switch (node.kind) {
114441                 case 95 /* IfKeyword */:
114442                 case 87 /* ElseKeyword */:
114443                     return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined;
114444                 case 101 /* ReturnKeyword */:
114445                     return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences);
114446                 case 105 /* ThrowKeyword */:
114447                     return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences);
114448                 case 107 /* TryKeyword */:
114449                 case 79 /* CatchKeyword */:
114450                 case 92 /* FinallyKeyword */:
114451                     var tryStatement = node.kind === 79 /* CatchKeyword */ ? node.parent.parent : node.parent;
114452                     return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences);
114453                 case 103 /* SwitchKeyword */:
114454                     return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences);
114455                 case 78 /* CaseKeyword */:
114456                 case 84 /* DefaultKeyword */: {
114457                     if (ts.isDefaultClause(node.parent) || ts.isCaseClause(node.parent)) {
114458                         return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences);
114459                     }
114460                     return undefined;
114461                 }
114462                 case 77 /* BreakKeyword */:
114463                 case 82 /* ContinueKeyword */:
114464                     return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences);
114465                 case 93 /* ForKeyword */:
114466                 case 111 /* WhileKeyword */:
114467                 case 86 /* DoKeyword */:
114468                     return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences);
114469                 case 129 /* ConstructorKeyword */:
114470                     return getFromAllDeclarations(ts.isConstructorDeclaration, [129 /* ConstructorKeyword */]);
114471                 case 131 /* GetKeyword */:
114472                 case 142 /* SetKeyword */:
114473                     return getFromAllDeclarations(ts.isAccessor, [131 /* GetKeyword */, 142 /* SetKeyword */]);
114474                 case 127 /* AwaitKeyword */:
114475                     return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
114476                 case 126 /* AsyncKeyword */:
114477                     return highlightSpans(getAsyncAndAwaitOccurrences(node));
114478                 case 121 /* YieldKeyword */:
114479                     return highlightSpans(getYieldOccurrences(node));
114480                 default:
114481                     return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
114482                         ? highlightSpans(getModifierOccurrences(node.kind, node.parent))
114483                         : undefined;
114484             }
114485             function getFromAllDeclarations(nodeTest, keywords) {
114486                 return useParent(node.parent, nodeTest, function (decl) { return ts.mapDefined(decl.symbol.declarations, function (d) {
114487                     return nodeTest(d) ? ts.find(d.getChildren(sourceFile), function (c) { return ts.contains(keywords, c.kind); }) : undefined;
114488                 }); });
114489             }
114490             function useParent(node, nodeTest, getNodes) {
114491                 return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined;
114492             }
114493             function highlightSpans(nodes) {
114494                 return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); });
114495             }
114496         }
114497         /**
114498          * Aggregates all throw-statements within this node *without* crossing
114499          * into function boundaries and try-blocks with catch-clauses.
114500          */
114501         function aggregateOwnedThrowStatements(node) {
114502             if (ts.isThrowStatement(node)) {
114503                 return [node];
114504             }
114505             else if (ts.isTryStatement(node)) {
114506                 // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context.
114507                 return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock));
114508             }
114509             // Do not cross function boundaries.
114510             return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements);
114511         }
114512         /**
114513          * For lack of a better name, this function takes a throw statement and returns the
114514          * nearest ancestor that is a try-block (whose try statement has a catch clause),
114515          * function-block, or source file.
114516          */
114517         function getThrowStatementOwner(throwStatement) {
114518             var child = throwStatement;
114519             while (child.parent) {
114520                 var parent = child.parent;
114521                 if (ts.isFunctionBlock(parent) || parent.kind === 290 /* SourceFile */) {
114522                     return parent;
114523                 }
114524                 // A throw-statement is only owned by a try-statement if the try-statement has
114525                 // a catch clause, and if the throw-statement occurs within the try block.
114526                 if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) {
114527                     return child;
114528                 }
114529                 child = parent;
114530             }
114531             return undefined;
114532         }
114533         function aggregateAllBreakAndContinueStatements(node) {
114534             return ts.isBreakOrContinueStatement(node) ? [node] : ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements);
114535         }
114536         function flatMapChildren(node, cb) {
114537             var result = [];
114538             node.forEachChild(function (child) {
114539                 var value = cb(child);
114540                 if (value !== undefined) {
114541                     result.push.apply(result, ts.toArray(value));
114542                 }
114543             });
114544             return result;
114545         }
114546         function ownsBreakOrContinueStatement(owner, statement) {
114547             var actualOwner = getBreakOrContinueOwner(statement);
114548             return !!actualOwner && actualOwner === owner;
114549         }
114550         function getBreakOrContinueOwner(statement) {
114551             return ts.findAncestor(statement, function (node) {
114552                 switch (node.kind) {
114553                     case 237 /* SwitchStatement */:
114554                         if (statement.kind === 233 /* ContinueStatement */) {
114555                             return false;
114556                         }
114557                     // falls through
114558                     case 230 /* ForStatement */:
114559                     case 231 /* ForInStatement */:
114560                     case 232 /* ForOfStatement */:
114561                     case 229 /* WhileStatement */:
114562                     case 228 /* DoStatement */:
114563                         return !statement.label || isLabeledBy(node, statement.label.escapedText);
114564                     default:
114565                         // Don't cross function boundaries.
114566                         // TODO: GH#20090
114567                         return ts.isFunctionLike(node) && "quit";
114568                 }
114569             });
114570         }
114571         function getModifierOccurrences(modifier, declaration) {
114572             return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); });
114573         }
114574         function getNodesToSearchForModifier(declaration, modifierFlag) {
114575             // Types of node whose children might have modifiers.
114576             var container = declaration.parent;
114577             switch (container.kind) {
114578                 case 250 /* ModuleBlock */:
114579                 case 290 /* SourceFile */:
114580                 case 223 /* Block */:
114581                 case 277 /* CaseClause */:
114582                 case 278 /* DefaultClause */:
114583                     // Container is either a class declaration or the declaration is a classDeclaration
114584                     if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) {
114585                         return __spreadArrays(declaration.members, [declaration]);
114586                     }
114587                     else {
114588                         return container.statements;
114589                     }
114590                 case 162 /* Constructor */:
114591                 case 161 /* MethodDeclaration */:
114592                 case 244 /* FunctionDeclaration */:
114593                     return __spreadArrays(container.parameters, (ts.isClassLike(container.parent) ? container.parent.members : []));
114594                 case 245 /* ClassDeclaration */:
114595                 case 214 /* ClassExpression */:
114596                 case 246 /* InterfaceDeclaration */:
114597                 case 173 /* TypeLiteral */:
114598                     var nodes = container.members;
114599                     // If we're an accessibility modifier, we're in an instance member and should search
114600                     // the constructor's parameter list for instance members as well.
114601                     if (modifierFlag & (28 /* AccessibilityModifier */ | 64 /* Readonly */)) {
114602                         var constructor = ts.find(container.members, ts.isConstructorDeclaration);
114603                         if (constructor) {
114604                             return __spreadArrays(nodes, constructor.parameters);
114605                         }
114606                     }
114607                     else if (modifierFlag & 128 /* Abstract */) {
114608                         return __spreadArrays(nodes, [container]);
114609                     }
114610                     return nodes;
114611                 default:
114612                     ts.Debug.assertNever(container, "Invalid container kind.");
114613             }
114614         }
114615         function pushKeywordIf(keywordList, token) {
114616             var expected = [];
114617             for (var _i = 2; _i < arguments.length; _i++) {
114618                 expected[_i - 2] = arguments[_i];
114619             }
114620             if (token && ts.contains(expected, token.kind)) {
114621                 keywordList.push(token);
114622                 return true;
114623             }
114624             return false;
114625         }
114626         function getLoopBreakContinueOccurrences(loopNode) {
114627             var keywords = [];
114628             if (pushKeywordIf(keywords, loopNode.getFirstToken(), 93 /* ForKeyword */, 111 /* WhileKeyword */, 86 /* DoKeyword */)) {
114629                 // If we succeeded and got a do-while loop, then start looking for a 'while' keyword.
114630                 if (loopNode.kind === 228 /* DoStatement */) {
114631                     var loopTokens = loopNode.getChildren();
114632                     for (var i = loopTokens.length - 1; i >= 0; i--) {
114633                         if (pushKeywordIf(keywords, loopTokens[i], 111 /* WhileKeyword */)) {
114634                             break;
114635                         }
114636                     }
114637                 }
114638             }
114639             ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) {
114640                 if (ownsBreakOrContinueStatement(loopNode, statement)) {
114641                     pushKeywordIf(keywords, statement.getFirstToken(), 77 /* BreakKeyword */, 82 /* ContinueKeyword */);
114642                 }
114643             });
114644             return keywords;
114645         }
114646         function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) {
114647             var owner = getBreakOrContinueOwner(breakOrContinueStatement);
114648             if (owner) {
114649                 switch (owner.kind) {
114650                     case 230 /* ForStatement */:
114651                     case 231 /* ForInStatement */:
114652                     case 232 /* ForOfStatement */:
114653                     case 228 /* DoStatement */:
114654                     case 229 /* WhileStatement */:
114655                         return getLoopBreakContinueOccurrences(owner);
114656                     case 237 /* SwitchStatement */:
114657                         return getSwitchCaseDefaultOccurrences(owner);
114658                 }
114659             }
114660             return undefined;
114661         }
114662         function getSwitchCaseDefaultOccurrences(switchStatement) {
114663             var keywords = [];
114664             pushKeywordIf(keywords, switchStatement.getFirstToken(), 103 /* SwitchKeyword */);
114665             // Go through each clause in the switch statement, collecting the 'case'/'default' keywords.
114666             ts.forEach(switchStatement.caseBlock.clauses, function (clause) {
114667                 pushKeywordIf(keywords, clause.getFirstToken(), 78 /* CaseKeyword */, 84 /* DefaultKeyword */);
114668                 ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) {
114669                     if (ownsBreakOrContinueStatement(switchStatement, statement)) {
114670                         pushKeywordIf(keywords, statement.getFirstToken(), 77 /* BreakKeyword */);
114671                     }
114672                 });
114673             });
114674             return keywords;
114675         }
114676         function getTryCatchFinallyOccurrences(tryStatement, sourceFile) {
114677             var keywords = [];
114678             pushKeywordIf(keywords, tryStatement.getFirstToken(), 107 /* TryKeyword */);
114679             if (tryStatement.catchClause) {
114680                 pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 79 /* CatchKeyword */);
114681             }
114682             if (tryStatement.finallyBlock) {
114683                 var finallyKeyword = ts.findChildOfKind(tryStatement, 92 /* FinallyKeyword */, sourceFile);
114684                 pushKeywordIf(keywords, finallyKeyword, 92 /* FinallyKeyword */);
114685             }
114686             return keywords;
114687         }
114688         function getThrowOccurrences(throwStatement, sourceFile) {
114689             var owner = getThrowStatementOwner(throwStatement);
114690             if (!owner) {
114691                 return undefined;
114692             }
114693             var keywords = [];
114694             ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) {
114695                 keywords.push(ts.findChildOfKind(throwStatement, 105 /* ThrowKeyword */, sourceFile));
114696             });
114697             // If the "owner" is a function, then we equate 'return' and 'throw' statements in their
114698             // ability to "jump out" of the function, and include occurrences for both.
114699             if (ts.isFunctionBlock(owner)) {
114700                 ts.forEachReturnStatement(owner, function (returnStatement) {
114701                     keywords.push(ts.findChildOfKind(returnStatement, 101 /* ReturnKeyword */, sourceFile));
114702                 });
114703             }
114704             return keywords;
114705         }
114706         function getReturnOccurrences(returnStatement, sourceFile) {
114707             var func = ts.getContainingFunction(returnStatement);
114708             if (!func) {
114709                 return undefined;
114710             }
114711             var keywords = [];
114712             ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) {
114713                 keywords.push(ts.findChildOfKind(returnStatement, 101 /* ReturnKeyword */, sourceFile));
114714             });
114715             // Include 'throw' statements that do not occur within a try block.
114716             ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) {
114717                 keywords.push(ts.findChildOfKind(throwStatement, 105 /* ThrowKeyword */, sourceFile));
114718             });
114719             return keywords;
114720         }
114721         function getAsyncAndAwaitOccurrences(node) {
114722             var func = ts.getContainingFunction(node);
114723             if (!func) {
114724                 return undefined;
114725             }
114726             var keywords = [];
114727             if (func.modifiers) {
114728                 func.modifiers.forEach(function (modifier) {
114729                     pushKeywordIf(keywords, modifier, 126 /* AsyncKeyword */);
114730                 });
114731             }
114732             ts.forEachChild(func, function (child) {
114733                 traverseWithoutCrossingFunction(child, function (node) {
114734                     if (ts.isAwaitExpression(node)) {
114735                         pushKeywordIf(keywords, node.getFirstToken(), 127 /* AwaitKeyword */);
114736                     }
114737                 });
114738             });
114739             return keywords;
114740         }
114741         function getYieldOccurrences(node) {
114742             var func = ts.getContainingFunction(node);
114743             if (!func) {
114744                 return undefined;
114745             }
114746             var keywords = [];
114747             ts.forEachChild(func, function (child) {
114748                 traverseWithoutCrossingFunction(child, function (node) {
114749                     if (ts.isYieldExpression(node)) {
114750                         pushKeywordIf(keywords, node.getFirstToken(), 121 /* YieldKeyword */);
114751                     }
114752                 });
114753             });
114754             return keywords;
114755         }
114756         // Do not cross function/class/interface/module/type boundaries.
114757         function traverseWithoutCrossingFunction(node, cb) {
114758             cb(node);
114759             if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
114760                 ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); });
114761             }
114762         }
114763         function getIfElseOccurrences(ifStatement, sourceFile) {
114764             var keywords = getIfElseKeywords(ifStatement, sourceFile);
114765             var result = [];
114766             // We'd like to highlight else/ifs together if they are only separated by whitespace
114767             // (i.e. the keywords are separated by no comments, no newlines).
114768             for (var i = 0; i < keywords.length; i++) {
114769                 if (keywords[i].kind === 87 /* ElseKeyword */ && i < keywords.length - 1) {
114770                     var elseKeyword = keywords[i];
114771                     var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword.
114772                     var shouldCombineElseAndIf = true;
114773                     // Avoid recalculating getStart() by iterating backwards.
114774                     for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) {
114775                         if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
114776                             shouldCombineElseAndIf = false;
114777                             break;
114778                         }
114779                     }
114780                     if (shouldCombineElseAndIf) {
114781                         result.push({
114782                             fileName: sourceFile.fileName,
114783                             textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
114784                             kind: "reference" /* reference */
114785                         });
114786                         i++; // skip the next keyword
114787                         continue;
114788                     }
114789                 }
114790                 // Ordinary case: just highlight the keyword.
114791                 result.push(getHighlightSpanForNode(keywords[i], sourceFile));
114792             }
114793             return result;
114794         }
114795         function getIfElseKeywords(ifStatement, sourceFile) {
114796             var keywords = [];
114797             // Traverse upwards through all parent if-statements linked by their else-branches.
114798             while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) {
114799                 ifStatement = ifStatement.parent;
114800             }
114801             // Now traverse back down through the else branches, aggregating if/else keywords of if-statements.
114802             while (true) {
114803                 var children = ifStatement.getChildren(sourceFile);
114804                 pushKeywordIf(keywords, children[0], 95 /* IfKeyword */);
114805                 // Generally the 'else' keyword is second-to-last, so we traverse backwards.
114806                 for (var i = children.length - 1; i >= 0; i--) {
114807                     if (pushKeywordIf(keywords, children[i], 87 /* ElseKeyword */)) {
114808                         break;
114809                     }
114810                 }
114811                 if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) {
114812                     break;
114813                 }
114814                 ifStatement = ifStatement.elseStatement;
114815             }
114816             return keywords;
114817         }
114818         /**
114819          * Whether or not a 'node' is preceded by a label of the given string.
114820          * Note: 'node' cannot be a SourceFile.
114821          */
114822         function isLabeledBy(node, labelName) {
114823             return !!ts.findAncestor(node.parent, function (owner) { return !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName; });
114824         }
114825     })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {}));
114826 })(ts || (ts = {}));
114827 var ts;
114828 (function (ts) {
114829     function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) {
114830         return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory);
114831     }
114832     ts.createDocumentRegistry = createDocumentRegistry;
114833     /*@internal*/
114834     function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) {
114835         if (currentDirectory === void 0) { currentDirectory = ""; }
114836         // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have
114837         // for those settings.
114838         var buckets = ts.createMap();
114839         var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames);
114840         function reportStats() {
114841             var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) {
114842                 var entries = buckets.get(name);
114843                 var sourceFiles = [];
114844                 entries.forEach(function (entry, name) {
114845                     sourceFiles.push({
114846                         name: name,
114847                         refCount: entry.languageServiceRefCount
114848                     });
114849                 });
114850                 sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; });
114851                 return {
114852                     bucket: name,
114853                     sourceFiles: sourceFiles
114854                 };
114855             });
114856             return JSON.stringify(bucketInfoArray, undefined, 2);
114857         }
114858         function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
114859             var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
114860             var key = getKeyForCompilationSettings(compilationSettings);
114861             return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
114862         }
114863         function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
114864             return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind);
114865         }
114866         function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
114867             var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
114868             var key = getKeyForCompilationSettings(compilationSettings);
114869             return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
114870         }
114871         function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
114872             return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind);
114873         }
114874         function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
114875             var bucket = ts.getOrUpdate(buckets, key, ts.createMap);
114876             var entry = bucket.get(path);
114877             var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */;
114878             if (!entry && externalCache) {
114879                 var sourceFile = externalCache.getDocument(key, path);
114880                 if (sourceFile) {
114881                     ts.Debug.assert(acquiring);
114882                     entry = {
114883                         sourceFile: sourceFile,
114884                         languageServiceRefCount: 0
114885                     };
114886                     bucket.set(path, entry);
114887                 }
114888             }
114889             if (!entry) {
114890                 // Have never seen this file with these settings.  Create a new source file for it.
114891                 var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
114892                 if (externalCache) {
114893                     externalCache.setDocument(key, path, sourceFile);
114894                 }
114895                 entry = {
114896                     sourceFile: sourceFile,
114897                     languageServiceRefCount: 1,
114898                 };
114899                 bucket.set(path, entry);
114900             }
114901             else {
114902                 // We have an entry for this file.  However, it may be for a different version of
114903                 // the script snapshot.  If so, update it appropriately.  Otherwise, we can just
114904                 // return it as is.
114905                 if (entry.sourceFile.version !== version) {
114906                     entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217
114907                     if (externalCache) {
114908                         externalCache.setDocument(key, path, entry.sourceFile);
114909                     }
114910                 }
114911                 // If we're acquiring, then this is the first time this LS is asking for this document.
114912                 // Increase our ref count so we know there's another LS using the document.  If we're
114913                 // not acquiring, then that means the LS is 'updating' the file instead, and that means
114914                 // it has already acquired the document previously.  As such, we do not need to increase
114915                 // the ref count.
114916                 if (acquiring) {
114917                     entry.languageServiceRefCount++;
114918                 }
114919             }
114920             ts.Debug.assert(entry.languageServiceRefCount !== 0);
114921             return entry.sourceFile;
114922         }
114923         function releaseDocument(fileName, compilationSettings) {
114924             var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
114925             var key = getKeyForCompilationSettings(compilationSettings);
114926             return releaseDocumentWithKey(path, key);
114927         }
114928         function releaseDocumentWithKey(path, key) {
114929             var bucket = ts.Debug.checkDefined(buckets.get(key));
114930             var entry = bucket.get(path);
114931             entry.languageServiceRefCount--;
114932             ts.Debug.assert(entry.languageServiceRefCount >= 0);
114933             if (entry.languageServiceRefCount === 0) {
114934                 bucket.delete(path);
114935             }
114936         }
114937         function getLanguageServiceRefCounts(path) {
114938             return ts.arrayFrom(buckets.entries(), function (_a) {
114939                 var key = _a[0], bucket = _a[1];
114940                 var entry = bucket.get(path);
114941                 return [key, entry && entry.languageServiceRefCount];
114942             });
114943         }
114944         return {
114945             acquireDocument: acquireDocument,
114946             acquireDocumentWithKey: acquireDocumentWithKey,
114947             updateDocument: updateDocument,
114948             updateDocumentWithKey: updateDocumentWithKey,
114949             releaseDocument: releaseDocument,
114950             releaseDocumentWithKey: releaseDocumentWithKey,
114951             getLanguageServiceRefCounts: getLanguageServiceRefCounts,
114952             reportStats: reportStats,
114953             getKeyForCompilationSettings: getKeyForCompilationSettings
114954         };
114955     }
114956     ts.createDocumentRegistryInternal = createDocumentRegistryInternal;
114957     function getKeyForCompilationSettings(settings) {
114958         return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|");
114959     }
114960 })(ts || (ts = {}));
114961 /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */
114962 /* @internal */
114963 var ts;
114964 (function (ts) {
114965     var FindAllReferences;
114966     (function (FindAllReferences) {
114967         /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily.  */
114968         function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) {
114969             var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken);
114970             return function (exportSymbol, exportInfo, isForRename) {
114971                 var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers;
114972                 return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename));
114973             };
114974         }
114975         FindAllReferences.createImportTracker = createImportTracker;
114976         var ExportKind;
114977         (function (ExportKind) {
114978             ExportKind[ExportKind["Named"] = 0] = "Named";
114979             ExportKind[ExportKind["Default"] = 1] = "Default";
114980             ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals";
114981         })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {}));
114982         var ImportExport;
114983         (function (ImportExport) {
114984             ImportExport[ImportExport["Import"] = 0] = "Import";
114985             ImportExport[ImportExport["Export"] = 1] = "Export";
114986         })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {}));
114987         /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */
114988         function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) {
114989             var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind;
114990             var markSeenDirectImport = ts.nodeSeenTracker();
114991             var markSeenIndirectUser = ts.nodeSeenTracker();
114992             var directImports = [];
114993             var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports;
114994             var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : [];
114995             handleDirectImports(exportingModuleSymbol);
114996             return { directImports: directImports, indirectUsers: getIndirectUsers() };
114997             function getIndirectUsers() {
114998                 if (isAvailableThroughGlobal) {
114999                     // It has `export as namespace`, so anything could potentially use it.
115000                     return sourceFiles;
115001                 }
115002                 // Module augmentations may use this module's exports without importing it.
115003                 for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) {
115004                     var decl = _a[_i];
115005                     if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
115006                         addIndirectUser(decl);
115007                     }
115008                 }
115009                 // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that.
115010                 return indirectUserDeclarations.map(ts.getSourceFileOfNode);
115011             }
115012             function handleDirectImports(exportingModuleSymbol) {
115013                 var theseDirectImports = getDirectImports(exportingModuleSymbol);
115014                 if (theseDirectImports) {
115015                     for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) {
115016                         var direct = theseDirectImports_1[_i];
115017                         if (!markSeenDirectImport(direct)) {
115018                             continue;
115019                         }
115020                         if (cancellationToken)
115021                             cancellationToken.throwIfCancellationRequested();
115022                         switch (direct.kind) {
115023                             case 196 /* CallExpression */:
115024                                 if (!isAvailableThroughGlobal) {
115025                                     var parent = direct.parent;
115026                                     if (exportKind === 2 /* ExportEquals */ && parent.kind === 242 /* VariableDeclaration */) {
115027                                         var name = parent.name;
115028                                         if (name.kind === 75 /* Identifier */) {
115029                                             directImports.push(name);
115030                                             break;
115031                                         }
115032                                     }
115033                                     // Don't support re-exporting 'require()' calls, so just add a single indirect user.
115034                                     addIndirectUser(direct.getSourceFile());
115035                                 }
115036                                 break;
115037                             case 75 /* Identifier */: // for 'const x = require("y");
115038                                 break; // TODO: GH#23879
115039                             case 253 /* ImportEqualsDeclaration */:
115040                                 handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false);
115041                                 break;
115042                             case 254 /* ImportDeclaration */:
115043                                 directImports.push(direct);
115044                                 var namedBindings = direct.importClause && direct.importClause.namedBindings;
115045                                 if (namedBindings && namedBindings.kind === 256 /* NamespaceImport */) {
115046                                     handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true);
115047                                 }
115048                                 else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) {
115049                                     addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports
115050                                 }
115051                                 break;
115052                             case 260 /* ExportDeclaration */:
115053                                 if (!direct.exportClause) {
115054                                     // This is `export * from "foo"`, so imports of this module may import the export too.
115055                                     handleDirectImports(getContainingModuleSymbol(direct, checker));
115056                                 }
115057                                 else {
115058                                     // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports.
115059                                     directImports.push(direct);
115060                                 }
115061                                 break;
115062                             case 188 /* ImportType */:
115063                                 directImports.push(direct);
115064                                 break;
115065                             default:
115066                                 ts.Debug.failBadSyntaxKind(direct, "Unexpected import kind.");
115067                         }
115068                     }
115069                 }
115070             }
115071             function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) {
115072                 if (exportKind === 2 /* ExportEquals */) {
115073                     // This is a direct import, not import-as-namespace.
115074                     if (!alreadyAddedDirect)
115075                         directImports.push(importDeclaration);
115076                 }
115077                 else if (!isAvailableThroughGlobal) {
115078                     var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
115079                     ts.Debug.assert(sourceFileLike.kind === 290 /* SourceFile */ || sourceFileLike.kind === 249 /* ModuleDeclaration */);
115080                     if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
115081                         addIndirectUsers(sourceFileLike);
115082                     }
115083                     else {
115084                         addIndirectUser(sourceFileLike);
115085                     }
115086                 }
115087             }
115088             function addIndirectUser(sourceFileLike) {
115089                 ts.Debug.assert(!isAvailableThroughGlobal);
115090                 var isNew = markSeenIndirectUser(sourceFileLike);
115091                 if (isNew) {
115092                     indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217
115093                 }
115094                 return isNew;
115095             }
115096             /** Adds a module and all of its transitive dependencies as possible indirect users. */
115097             function addIndirectUsers(sourceFileLike) {
115098                 if (!addIndirectUser(sourceFileLike)) {
115099                     return;
115100                 }
115101                 var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol);
115102                 ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
115103                 var directImports = getDirectImports(moduleSymbol);
115104                 if (directImports) {
115105                     for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) {
115106                         var directImport = directImports_1[_i];
115107                         if (!ts.isImportTypeNode(directImport)) {
115108                             addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport));
115109                         }
115110                     }
115111                 }
115112             }
115113             function getDirectImports(moduleSymbol) {
115114                 return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString());
115115             }
115116         }
115117         /**
115118          * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol.
115119          * The returned `importSearches` will result in the entire source file being searched.
115120          * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced.
115121          */
115122         function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) {
115123             var importSearches = [];
115124             var singleReferences = [];
115125             function addSearch(location, symbol) {
115126                 importSearches.push([location, symbol]);
115127             }
115128             if (directImports) {
115129                 for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) {
115130                     var decl = directImports_2[_i];
115131                     handleImport(decl);
115132                 }
115133             }
115134             return { importSearches: importSearches, singleReferences: singleReferences };
115135             function handleImport(decl) {
115136                 if (decl.kind === 253 /* ImportEqualsDeclaration */) {
115137                     if (isExternalModuleImportEquals(decl)) {
115138                         handleNamespaceImportLike(decl.name);
115139                     }
115140                     return;
115141                 }
115142                 if (decl.kind === 75 /* Identifier */) {
115143                     handleNamespaceImportLike(decl);
115144                     return;
115145                 }
115146                 if (decl.kind === 188 /* ImportType */) {
115147                     if (decl.qualifier) {
115148                         var firstIdentifier = ts.getFirstIdentifier(decl.qualifier);
115149                         if (firstIdentifier.escapedText === ts.symbolName(exportSymbol)) {
115150                             singleReferences.push(firstIdentifier);
115151                         }
115152                     }
115153                     else if (exportKind === 2 /* ExportEquals */) {
115154                         singleReferences.push(decl.argument.literal);
115155                     }
115156                     return;
115157                 }
115158                 // Ignore if there's a grammar error
115159                 if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) {
115160                     return;
115161                 }
115162                 if (decl.kind === 260 /* ExportDeclaration */) {
115163                     if (decl.exportClause && ts.isNamedExports(decl.exportClause)) {
115164                         searchForNamedImport(decl.exportClause);
115165                     }
115166                     return;
115167                 }
115168                 var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings;
115169                 if (namedBindings) {
115170                     switch (namedBindings.kind) {
115171                         case 256 /* NamespaceImport */:
115172                             handleNamespaceImportLike(namedBindings.name);
115173                             break;
115174                         case 257 /* NamedImports */:
115175                             // 'default' might be accessed as a named import `{ default as foo }`.
115176                             if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) {
115177                                 searchForNamedImport(namedBindings);
115178                             }
115179                             break;
115180                         default:
115181                             ts.Debug.assertNever(namedBindings);
115182                     }
115183                 }
115184                 // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals.
115185                 // If a default import has the same name as the default export, allow to rename it.
115186                 // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
115187                 if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
115188                     var defaultImportAlias = checker.getSymbolAtLocation(name);
115189                     addSearch(name, defaultImportAlias);
115190                 }
115191             }
115192             /**
115193              * `import x = require("./x")` or `import * as x from "./x"`.
115194              * An `export =` may be imported by this syntax, so it may be a direct import.
115195              * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
115196              */
115197             function handleNamespaceImportLike(importName) {
115198                 // Don't rename an import that already has a different name than the export.
115199                 if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) {
115200                     addSearch(importName, checker.getSymbolAtLocation(importName));
115201                 }
115202             }
115203             function searchForNamedImport(namedBindings) {
115204                 if (!namedBindings) {
115205                     return;
115206                 }
115207                 for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
115208                     var element = _a[_i];
115209                     var name = element.name, propertyName = element.propertyName;
115210                     if (!isNameMatch((propertyName || name).escapedText)) {
115211                         continue;
115212                     }
115213                     if (propertyName) {
115214                         // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference.
115215                         singleReferences.push(propertyName);
115216                         // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`.
115217                         // But do rename `foo` in ` { default as foo }` if that's the original export name.
115218                         if (!isForRename || name.escapedText === exportSymbol.escapedName) {
115219                             // Search locally for `bar`.
115220                             addSearch(name, checker.getSymbolAtLocation(name));
115221                         }
115222                     }
115223                     else {
115224                         var localSymbol = element.kind === 263 /* ExportSpecifier */ && element.propertyName
115225                             ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol.
115226                             : checker.getSymbolAtLocation(name);
115227                         addSearch(name, localSymbol);
115228                     }
115229                 }
115230             }
115231             function isNameMatch(name) {
115232                 // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports
115233                 return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */;
115234             }
115235         }
115236         /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */
115237         function findNamespaceReExports(sourceFileLike, name, checker) {
115238             var namespaceImportSymbol = checker.getSymbolAtLocation(name);
115239             return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
115240                 if (!ts.isExportDeclaration(statement))
115241                     return;
115242                 var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
115243                 return !moduleSpecifier && exportClause && ts.isNamedExports(exportClause) &&
115244                     exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
115245             });
115246         }
115247         function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
115248             var refs = [];
115249             var checker = program.getTypeChecker();
115250             for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
115251                 var referencingFile = sourceFiles_1[_i];
115252                 var searchSourceFile = searchModuleSymbol.valueDeclaration;
115253                 if (searchSourceFile.kind === 290 /* SourceFile */) {
115254                     for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
115255                         var ref = _b[_a];
115256                         if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
115257                             refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
115258                         }
115259                     }
115260                     for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) {
115261                         var ref = _d[_c];
115262                         var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName);
115263                         if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) {
115264                             refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
115265                         }
115266                     }
115267                 }
115268                 forEachImport(referencingFile, function (_importDecl, moduleSpecifier) {
115269                     var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
115270                     if (moduleSymbol === searchModuleSymbol) {
115271                         refs.push({ kind: "import", literal: moduleSpecifier });
115272                     }
115273                 });
115274             }
115275             return refs;
115276         }
115277         FindAllReferences.findModuleReferences = findModuleReferences;
115278         /** Returns a map from a module symbol Id to all import statements that directly reference the module. */
115279         function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
115280             var map = ts.createMap();
115281             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
115282                 var sourceFile = sourceFiles_2[_i];
115283                 if (cancellationToken)
115284                     cancellationToken.throwIfCancellationRequested();
115285                 forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
115286                     var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
115287                     if (moduleSymbol) {
115288                         var id = ts.getSymbolId(moduleSymbol).toString();
115289                         var imports = map.get(id);
115290                         if (!imports) {
115291                             map.set(id, imports = []);
115292                         }
115293                         imports.push(importDecl);
115294                     }
115295                 });
115296             }
115297             return map;
115298         }
115299         /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
115300         function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
115301             return ts.forEach(sourceFileLike.kind === 290 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
115302                 return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
115303             });
115304         }
115305         /** Calls `action` for each import, re-export, or require() in a file. */
115306         function forEachImport(sourceFile, action) {
115307             if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) {
115308                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
115309                     var i = _a[_i];
115310                     action(ts.importFromModuleSpecifier(i), i);
115311                 }
115312             }
115313             else {
115314                 forEachPossibleImportOrExportStatement(sourceFile, function (statement) {
115315                     switch (statement.kind) {
115316                         case 260 /* ExportDeclaration */:
115317                         case 254 /* ImportDeclaration */: {
115318                             var decl = statement;
115319                             if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) {
115320                                 action(decl, decl.moduleSpecifier);
115321                             }
115322                             break;
115323                         }
115324                         case 253 /* ImportEqualsDeclaration */: {
115325                             var decl = statement;
115326                             if (isExternalModuleImportEquals(decl)) {
115327                                 action(decl, decl.moduleReference.expression);
115328                             }
115329                             break;
115330                         }
115331                     }
115332                 });
115333             }
115334         }
115335         /**
115336          * Given a local reference, we might notice that it's an import/export and recursively search for references of that.
115337          * If at an import, look locally for the symbol it imports.
115338          * If at an export, look for all imports of it.
115339          * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`.
115340          * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here.
115341          */
115342         function getImportOrExportSymbol(node, symbol, checker, comingFromExport) {
115343             return comingFromExport ? getExport() : getExport() || getImport();
115344             function getExport() {
115345                 var parent = node.parent;
115346                 var grandParent = parent.parent;
115347                 if (symbol.exportSymbol) {
115348                     if (parent.kind === 194 /* PropertyAccessExpression */) {
115349                         // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use.
115350                         // So check that we are at the declaration.
115351                         return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent)
115352                             ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false)
115353                             : undefined;
115354                     }
115355                     else {
115356                         return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent));
115357                     }
115358                 }
115359                 else {
115360                     var exportNode = getExportNode(parent, node);
115361                     if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) {
115362                         if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) {
115363                             // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement.
115364                             if (comingFromExport) {
115365                                 return undefined;
115366                             }
115367                             var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
115368                             return { kind: 0 /* Import */, symbol: lhsSymbol };
115369                         }
115370                         else {
115371                             return exportInfo(symbol, getExportKindForDeclaration(exportNode));
115372                         }
115373                     }
115374                     // If we are in `export = a;` or `export default a;`, `parent` is the export assignment.
115375                     else if (ts.isExportAssignment(parent)) {
115376                         return getExportAssignmentExport(parent);
115377                     }
115378                     // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment.
115379                     else if (ts.isExportAssignment(grandParent)) {
115380                         return getExportAssignmentExport(grandParent);
115381                     }
115382                     // Similar for `module.exports =` and `exports.A =`.
115383                     else if (ts.isBinaryExpression(parent)) {
115384                         return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true);
115385                     }
115386                     else if (ts.isBinaryExpression(grandParent)) {
115387                         return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true);
115388                     }
115389                     else if (ts.isJSDocTypedefTag(parent)) {
115390                         return exportInfo(symbol, 0 /* Named */);
115391                     }
115392                 }
115393                 function getExportAssignmentExport(ex) {
115394                     // Get the symbol for the `export =` node; its parent is the module it's the export of.
115395                     var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent");
115396                     var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */;
115397                     return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } };
115398                 }
115399                 function getSpecialPropertyExport(node, useLhsSymbol) {
115400                     var kind;
115401                     switch (ts.getAssignmentDeclarationKind(node)) {
115402                         case 1 /* ExportsProperty */:
115403                             kind = 0 /* Named */;
115404                             break;
115405                         case 2 /* ModuleExports */:
115406                             kind = 2 /* ExportEquals */;
115407                             break;
115408                         default:
115409                             return undefined;
115410                     }
115411                     var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.getNameOfAccessExpression(ts.cast(node.left, ts.isAccessExpression))) : symbol;
115412                     return sym && exportInfo(sym, kind);
115413                 }
115414             }
115415             function getImport() {
115416                 var isImport = isNodeImport(node);
115417                 if (!isImport)
115418                     return undefined;
115419                 // A symbol being imported is always an alias. So get what that aliases to find the local symbol.
115420                 var importedSymbol = checker.getImmediateAliasedSymbol(symbol);
115421                 if (!importedSymbol)
115422                     return undefined;
115423                 // Search on the local symbol in the exporting module, not the exported symbol.
115424                 importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker);
115425                 // Similarly, skip past the symbol for 'export ='
115426                 if (importedSymbol.escapedName === "export=") {
115427                     importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker);
115428                 }
115429                 // If the import has a different name than the export, do not continue searching.
115430                 // If `importedName` is undefined, do continue searching as the export is anonymous.
115431                 // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
115432                 var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
115433                 if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
115434                     return { kind: 0 /* Import */, symbol: importedSymbol };
115435                 }
115436             }
115437             function exportInfo(symbol, kind) {
115438                 var exportInfo = getExportInfo(symbol, kind, checker);
115439                 return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo };
115440             }
115441             // Not meant for use with export specifiers or export assignment.
115442             function getExportKindForDeclaration(node) {
115443                 return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */;
115444             }
115445         }
115446         FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol;
115447         function getExportEqualsLocalSymbol(importedSymbol, checker) {
115448             if (importedSymbol.flags & 2097152 /* Alias */) {
115449                 return ts.Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol));
115450             }
115451             var decl = importedSymbol.valueDeclaration;
115452             if (ts.isExportAssignment(decl)) { // `export = class {}`
115453                 return ts.Debug.checkDefined(decl.expression.symbol);
115454             }
115455             else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}`
115456                 return ts.Debug.checkDefined(decl.right.symbol);
115457             }
115458             else if (ts.isSourceFile(decl)) { // json module
115459                 return ts.Debug.checkDefined(decl.symbol);
115460             }
115461             return ts.Debug.fail();
115462         }
115463         // If a reference is a class expression, the exported node would be its parent.
115464         // If a reference is a variable declaration, the exported node would be the variable statement.
115465         function getExportNode(parent, node) {
115466             var declaration = ts.isVariableDeclaration(parent) ? parent : ts.isBindingElement(parent) ? ts.walkUpBindingElementsAndPatterns(parent) : undefined;
115467             if (declaration) {
115468                 return parent.name !== node ? undefined :
115469                     ts.isCatchClause(declaration.parent) ? undefined : ts.isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : undefined;
115470             }
115471             else {
115472                 return parent;
115473             }
115474         }
115475         function isNodeImport(node) {
115476             var parent = node.parent;
115477             switch (parent.kind) {
115478                 case 253 /* ImportEqualsDeclaration */:
115479                     return parent.name === node && isExternalModuleImportEquals(parent);
115480                 case 258 /* ImportSpecifier */:
115481                     // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
115482                     return !parent.propertyName;
115483                 case 255 /* ImportClause */:
115484                 case 256 /* NamespaceImport */:
115485                     ts.Debug.assert(parent.name === node);
115486                     return true;
115487                 default:
115488                     return false;
115489             }
115490         }
115491         function getExportInfo(exportSymbol, exportKind, checker) {
115492             var moduleSymbol = exportSymbol.parent;
115493             if (!moduleSymbol)
115494                 return undefined; // This can happen if an `export` is not at the top-level (which is a compile error).
115495             var exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); // Need to get merged symbol in case there's an augmentation.
115496             // `export` may appear in a namespace. In that case, just rely on global search.
115497             return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
115498         }
115499         FindAllReferences.getExportInfo = getExportInfo;
115500         /** If at an export specifier, go to the symbol it refers to. */
115501         function skipExportSpecifierSymbol(symbol, checker) {
115502             // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
115503             if (symbol.declarations) {
115504                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
115505                     var declaration = _a[_i];
115506                     if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) {
115507                         return checker.getExportSpecifierLocalTargetSymbol(declaration);
115508                     }
115509                 }
115510             }
115511             return symbol;
115512         }
115513         function getContainingModuleSymbol(importer, checker) {
115514             return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol);
115515         }
115516         function getSourceFileLikeForImportDeclaration(node) {
115517             if (node.kind === 196 /* CallExpression */) {
115518                 return node.getSourceFile();
115519             }
115520             var parent = node.parent;
115521             if (parent.kind === 290 /* SourceFile */) {
115522                 return parent;
115523             }
115524             ts.Debug.assert(parent.kind === 250 /* ModuleBlock */);
115525             return ts.cast(parent.parent, isAmbientModuleDeclaration);
115526         }
115527         function isAmbientModuleDeclaration(node) {
115528             return node.kind === 249 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */;
115529         }
115530         function isExternalModuleImportEquals(eq) {
115531             return eq.moduleReference.kind === 265 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */;
115532         }
115533     })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
115534 })(ts || (ts = {}));
115535 /* @internal */
115536 var ts;
115537 (function (ts) {
115538     var FindAllReferences;
115539     (function (FindAllReferences) {
115540         var DefinitionKind;
115541         (function (DefinitionKind) {
115542             DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol";
115543             DefinitionKind[DefinitionKind["Label"] = 1] = "Label";
115544             DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword";
115545             DefinitionKind[DefinitionKind["This"] = 3] = "This";
115546             DefinitionKind[DefinitionKind["String"] = 4] = "String";
115547         })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {}));
115548         var EntryKind;
115549         (function (EntryKind) {
115550             EntryKind[EntryKind["Span"] = 0] = "Span";
115551             EntryKind[EntryKind["Node"] = 1] = "Node";
115552             EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral";
115553             EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty";
115554             EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal";
115555         })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {}));
115556         function nodeEntry(node, kind) {
115557             if (kind === void 0) { kind = 1 /* Node */; }
115558             return {
115559                 kind: kind,
115560                 node: node.name || node,
115561                 context: getContextNodeForNodeEntry(node)
115562             };
115563         }
115564         FindAllReferences.nodeEntry = nodeEntry;
115565         function isContextWithStartAndEndNode(node) {
115566             return node && node.kind === undefined;
115567         }
115568         FindAllReferences.isContextWithStartAndEndNode = isContextWithStartAndEndNode;
115569         function getContextNodeForNodeEntry(node) {
115570             if (ts.isDeclaration(node)) {
115571                 return getContextNode(node);
115572             }
115573             if (!node.parent)
115574                 return undefined;
115575             if (!ts.isDeclaration(node.parent) && !ts.isExportAssignment(node.parent)) {
115576                 // Special property assignment in javascript
115577                 if (ts.isInJSFile(node)) {
115578                     var binaryExpression = ts.isBinaryExpression(node.parent) ?
115579                         node.parent :
115580                         ts.isAccessExpression(node.parent) &&
115581                             ts.isBinaryExpression(node.parent.parent) &&
115582                             node.parent.parent.left === node.parent ?
115583                             node.parent.parent :
115584                             undefined;
115585                     if (binaryExpression && ts.getAssignmentDeclarationKind(binaryExpression) !== 0 /* None */) {
115586                         return getContextNode(binaryExpression);
115587                     }
115588                 }
115589                 // Jsx Tags
115590                 if (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) {
115591                     return node.parent.parent;
115592                 }
115593                 else if (ts.isJsxSelfClosingElement(node.parent) ||
115594                     ts.isLabeledStatement(node.parent) ||
115595                     ts.isBreakOrContinueStatement(node.parent)) {
115596                     return node.parent;
115597                 }
115598                 else if (ts.isStringLiteralLike(node)) {
115599                     var validImport = ts.tryGetImportFromModuleSpecifier(node);
115600                     if (validImport) {
115601                         var declOrStatement = ts.findAncestor(validImport, function (node) {
115602                             return ts.isDeclaration(node) ||
115603                                 ts.isStatement(node) ||
115604                                 ts.isJSDocTag(node);
115605                         });
115606                         return ts.isDeclaration(declOrStatement) ?
115607                             getContextNode(declOrStatement) :
115608                             declOrStatement;
115609                     }
115610                 }
115611                 // Handle computed property name
115612                 var propertyName = ts.findAncestor(node, ts.isComputedPropertyName);
115613                 return propertyName ?
115614                     getContextNode(propertyName.parent) :
115615                     undefined;
115616             }
115617             if (node.parent.name === node || // node is name of declaration, use parent
115618                 ts.isConstructorDeclaration(node.parent) ||
115619                 ts.isExportAssignment(node.parent) ||
115620                 // Property name of the import export specifier or binding pattern, use parent
115621                 ((ts.isImportOrExportSpecifier(node.parent) || ts.isBindingElement(node.parent))
115622                     && node.parent.propertyName === node) ||
115623                 // Is default export
115624                 (node.kind === 84 /* DefaultKeyword */ && ts.hasModifier(node.parent, 513 /* ExportDefault */))) {
115625                 return getContextNode(node.parent);
115626             }
115627             return undefined;
115628         }
115629         function getContextNode(node) {
115630             if (!node)
115631                 return undefined;
115632             switch (node.kind) {
115633                 case 242 /* VariableDeclaration */:
115634                     return !ts.isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ?
115635                         node :
115636                         ts.isVariableStatement(node.parent.parent) ?
115637                             node.parent.parent :
115638                             ts.isForInOrOfStatement(node.parent.parent) ?
115639                                 getContextNode(node.parent.parent) :
115640                                 node.parent;
115641                 case 191 /* BindingElement */:
115642                     return getContextNode(node.parent.parent);
115643                 case 258 /* ImportSpecifier */:
115644                     return node.parent.parent.parent;
115645                 case 263 /* ExportSpecifier */:
115646                 case 256 /* NamespaceImport */:
115647                     return node.parent.parent;
115648                 case 255 /* ImportClause */:
115649                     return node.parent;
115650                 case 209 /* BinaryExpression */:
115651                     return ts.isExpressionStatement(node.parent) ?
115652                         node.parent :
115653                         node;
115654                 case 232 /* ForOfStatement */:
115655                 case 231 /* ForInStatement */:
115656                     return {
115657                         start: node.initializer,
115658                         end: node.expression
115659                     };
115660                 case 281 /* PropertyAssignment */:
115661                 case 282 /* ShorthandPropertyAssignment */:
115662                     return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ?
115663                         getContextNode(ts.findAncestor(node.parent, function (node) {
115664                             return ts.isBinaryExpression(node) || ts.isForInOrOfStatement(node);
115665                         })) :
115666                         node;
115667                 default:
115668                     return node;
115669             }
115670         }
115671         FindAllReferences.getContextNode = getContextNode;
115672         function toContextSpan(textSpan, sourceFile, context) {
115673             if (!context)
115674                 return undefined;
115675             var contextSpan = isContextWithStartAndEndNode(context) ?
115676                 getTextSpan(context.start, sourceFile, context.end) :
115677                 getTextSpan(context, sourceFile);
115678             return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ?
115679                 { contextSpan: contextSpan } :
115680                 undefined;
115681         }
115682         FindAllReferences.toContextSpan = toContextSpan;
115683         var FindReferencesUse;
115684         (function (FindReferencesUse) {
115685             /**
115686              * When searching for references to a symbol, the location will not be adjusted (this is the default behavior when not specified).
115687              */
115688             FindReferencesUse[FindReferencesUse["Other"] = 0] = "Other";
115689             /**
115690              * When searching for references to a symbol, the location will be adjusted if the cursor was on a keyword.
115691              */
115692             FindReferencesUse[FindReferencesUse["References"] = 1] = "References";
115693             /**
115694              * When searching for references to a symbol, the location will be adjusted if the cursor was on a keyword.
115695              * Unlike `References`, the location will only be adjusted keyword belonged to a declaration with a valid name.
115696              * If set, we will find fewer references -- if it is referenced by several different names, we still only find references for the original name.
115697              */
115698             FindReferencesUse[FindReferencesUse["Rename"] = 2] = "Rename";
115699         })(FindReferencesUse = FindAllReferences.FindReferencesUse || (FindAllReferences.FindReferencesUse = {}));
115700         function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
115701             var node = ts.getTouchingPropertyName(sourceFile, position);
115702             var referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, { use: 1 /* References */ });
115703             var checker = program.getTypeChecker();
115704             return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) {
115705                 var definition = _a.definition, references = _a.references;
115706                 // Only include referenced symbols that have a valid definition.
115707                 return definition && {
115708                     definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }),
115709                     references: references.map(toReferenceEntry)
115710                 };
115711             });
115712         }
115713         FindAllReferences.findReferencedSymbols = findReferencedSymbols;
115714         function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) {
115715             var node = ts.getTouchingPropertyName(sourceFile, position);
115716             var referenceEntries;
115717             var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position);
115718             if (node.parent.kind === 194 /* PropertyAccessExpression */
115719                 || node.parent.kind === 191 /* BindingElement */
115720                 || node.parent.kind === 195 /* ElementAccessExpression */
115721                 || node.kind === 102 /* SuperKeyword */) {
115722                 referenceEntries = entries && __spreadArrays(entries);
115723             }
115724             else {
115725                 var queue = entries && __spreadArrays(entries);
115726                 var seenNodes = ts.createMap();
115727                 while (queue && queue.length) {
115728                     var entry = queue.shift();
115729                     if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) {
115730                         continue;
115731                     }
115732                     referenceEntries = ts.append(referenceEntries, entry);
115733                     var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos);
115734                     if (entries_1) {
115735                         queue.push.apply(queue, entries_1);
115736                     }
115737                 }
115738             }
115739             var checker = program.getTypeChecker();
115740             return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); });
115741         }
115742         FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
115743         function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
115744             if (node.kind === 290 /* SourceFile */) {
115745                 return undefined;
115746             }
115747             var checker = program.getTypeChecker();
115748             // If invoked directly on a shorthand property assignment, then return
115749             // the declaration of the symbol being assigned (not the symbol being assigned to).
115750             if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
115751                 var result_1 = [];
115752                 Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
115753                 return result_1;
115754             }
115755             else if (node.kind === 102 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
115756                 // References to and accesses on the super keyword only have one possible implementation, so no
115757                 // need to "Find all References"
115758                 var symbol = checker.getSymbolAtLocation(node);
115759                 return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
115760             }
115761             else {
115762                 // Perform "Find all References" and retrieve only those that are implementations
115763                 return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true, use: 1 /* References */ });
115764             }
115765         }
115766         function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
115767             return ts.map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); });
115768         }
115769         FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries;
115770         function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
115771             if (options === void 0) { options = {}; }
115772             if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
115773             return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
115774         }
115775         FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
115776         function flattenEntries(referenceSymbols) {
115777             return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
115778         }
115779         function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
115780             var info = (function () {
115781                 switch (def.type) {
115782                     case 0 /* Symbol */: {
115783                         var symbol = def.symbol;
115784                         var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
115785                         var name_1 = displayParts_1.map(function (p) { return p.text; }).join("");
115786                         var declaration = symbol.declarations ? ts.first(symbol.declarations) : undefined;
115787                         return {
115788                             node: declaration ?
115789                                 ts.getNameOfDeclaration(declaration) || declaration :
115790                                 originalNode,
115791                             name: name_1,
115792                             kind: kind_1,
115793                             displayParts: displayParts_1,
115794                             context: getContextNode(declaration)
115795                         };
115796                     }
115797                     case 1 /* Label */: {
115798                         var node_1 = def.node;
115799                         return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] };
115800                     }
115801                     case 2 /* Keyword */: {
115802                         var node_2 = def.node;
115803                         var name_2 = ts.tokenToString(node_2.kind);
115804                         return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] };
115805                     }
115806                     case 3 /* This */: {
115807                         var node_3 = def.node;
115808                         var symbol = checker.getSymbolAtLocation(node_3);
115809                         var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")];
115810                         return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
115811                     }
115812                     case 4 /* String */: {
115813                         var node_4 = def.node;
115814                         return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] };
115815                     }
115816                     default:
115817                         return ts.Debug.assertNever(def);
115818                 }
115819             })();
115820             var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts, context = info.context;
115821             var sourceFile = node.getSourceFile();
115822             var textSpan = getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile);
115823             return __assign({ containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind,
115824                 name: name,
115825                 textSpan: textSpan,
115826                 displayParts: displayParts }, toContextSpan(textSpan, sourceFile, context));
115827         }
115828         function getDefinitionKindAndDisplayParts(symbol, checker, node) {
115829             var meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol);
115830             var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node;
115831             var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
115832             return { displayParts: displayParts, kind: symbolKind };
115833         }
115834         function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) {
115835             return __assign(__assign({}, entryToDocumentSpan(entry)), (providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker)));
115836         }
115837         FindAllReferences.toRenameLocation = toRenameLocation;
115838         function toReferenceEntry(entry) {
115839             var documentSpan = entryToDocumentSpan(entry);
115840             if (entry.kind === 0 /* Span */) {
115841                 return __assign(__assign({}, documentSpan), { isWriteAccess: false, isDefinition: false });
115842             }
115843             var kind = entry.kind, node = entry.node;
115844             return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: isDefinitionForReference(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined });
115845         }
115846         FindAllReferences.toReferenceEntry = toReferenceEntry;
115847         function entryToDocumentSpan(entry) {
115848             if (entry.kind === 0 /* Span */) {
115849                 return { textSpan: entry.textSpan, fileName: entry.fileName };
115850             }
115851             else {
115852                 var sourceFile = entry.node.getSourceFile();
115853                 var textSpan = getTextSpan(entry.node, sourceFile);
115854                 return __assign({ textSpan: textSpan, fileName: sourceFile.fileName }, toContextSpan(textSpan, sourceFile, entry.context));
115855             }
115856         }
115857         function getPrefixAndSuffixText(entry, originalNode, checker) {
115858             if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) {
115859                 var node = entry.node, kind = entry.kind;
115860                 var name = originalNode.text;
115861                 var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent);
115862                 if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent) && node.parent.name === node) {
115863                     var prefixColon = { prefixText: name + ": " };
115864                     var suffixColon = { suffixText: ": " + name };
115865                     return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon
115866                         : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon
115867                             // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol.
115868                             // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol.
115869                             : isShorthandAssignment ? suffixColon : prefixColon;
115870                 }
115871                 else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
115872                     // If the original symbol was using this alias, just rename the alias.
115873                     var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
115874                     return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions;
115875                 }
115876                 else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
115877                     // If the symbol for the node is same as declared node symbol use prefix text
115878                     return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ?
115879                         { prefixText: name + " as " } :
115880                         { suffixText: " as " + name };
115881                 }
115882             }
115883             return ts.emptyOptions;
115884         }
115885         function toImplementationLocation(entry, checker) {
115886             var documentSpan = entryToDocumentSpan(entry);
115887             if (entry.kind !== 0 /* Span */) {
115888                 var node = entry.node;
115889                 return __assign(__assign({}, documentSpan), implementationKindDisplayParts(node, checker));
115890             }
115891             else {
115892                 return __assign(__assign({}, documentSpan), { kind: "" /* unknown */, displayParts: [] });
115893             }
115894         }
115895         function implementationKindDisplayParts(node, checker) {
115896             var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
115897             if (symbol) {
115898                 return getDefinitionKindAndDisplayParts(symbol, checker, node);
115899             }
115900             else if (node.kind === 193 /* ObjectLiteralExpression */) {
115901                 return {
115902                     kind: "interface" /* interfaceElement */,
115903                     displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)]
115904                 };
115905             }
115906             else if (node.kind === 214 /* ClassExpression */) {
115907                 return {
115908                     kind: "local class" /* localClassElement */,
115909                     displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)]
115910                 };
115911             }
115912             else {
115913                 return { kind: ts.getNodeKind(node), displayParts: [] };
115914             }
115915         }
115916         function toHighlightSpan(entry) {
115917             var documentSpan = entryToDocumentSpan(entry);
115918             if (entry.kind === 0 /* Span */) {
115919                 return {
115920                     fileName: documentSpan.fileName,
115921                     span: {
115922                         textSpan: documentSpan.textSpan,
115923                         kind: "reference" /* reference */
115924                     }
115925                 };
115926             }
115927             var writeAccess = isWriteAccessForReference(entry.node);
115928             var span = __assign({ textSpan: documentSpan.textSpan, kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: entry.kind === 2 /* StringLiteral */ ? true : undefined }, documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan });
115929             return { fileName: documentSpan.fileName, span: span };
115930         }
115931         FindAllReferences.toHighlightSpan = toHighlightSpan;
115932         function getTextSpan(node, sourceFile, endNode) {
115933             var start = node.getStart(sourceFile);
115934             var end = (endNode || node).getEnd();
115935             if (ts.isStringLiteralLike(node)) {
115936                 ts.Debug.assert(endNode === undefined);
115937                 start += 1;
115938                 end -= 1;
115939             }
115940             return ts.createTextSpanFromBounds(start, end);
115941         }
115942         function getTextSpanOfEntry(entry) {
115943             return entry.kind === 0 /* Span */ ? entry.textSpan :
115944                 getTextSpan(entry.node, entry.node.getSourceFile());
115945         }
115946         FindAllReferences.getTextSpanOfEntry = getTextSpanOfEntry;
115947         /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
115948         function isWriteAccessForReference(node) {
115949             var decl = ts.getDeclarationFromName(node);
115950             return !!decl && declarationIsWriteAccess(decl) || node.kind === 84 /* DefaultKeyword */ || ts.isWriteAccess(node);
115951         }
115952         function isDefinitionForReference(node) {
115953             return node.kind === 84 /* DefaultKeyword */
115954                 || !!ts.getDeclarationFromName(node)
115955                 || ts.isLiteralComputedPropertyDeclarationName(node)
115956                 || (node.kind === 129 /* ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent));
115957         }
115958         /**
115959          * True if 'decl' provides a value, as in `function f() {}`;
115960          * false if 'decl' is just a location for a future write, as in 'let x;'
115961          */
115962         function declarationIsWriteAccess(decl) {
115963             // Consider anything in an ambient declaration to be a write access since it may be coming from JS.
115964             if (!!(decl.flags & 8388608 /* Ambient */))
115965                 return true;
115966             switch (decl.kind) {
115967                 case 209 /* BinaryExpression */:
115968                 case 191 /* BindingElement */:
115969                 case 245 /* ClassDeclaration */:
115970                 case 214 /* ClassExpression */:
115971                 case 84 /* DefaultKeyword */:
115972                 case 248 /* EnumDeclaration */:
115973                 case 284 /* EnumMember */:
115974                 case 263 /* ExportSpecifier */:
115975                 case 255 /* ImportClause */: // default import
115976                 case 253 /* ImportEqualsDeclaration */:
115977                 case 258 /* ImportSpecifier */:
115978                 case 246 /* InterfaceDeclaration */:
115979                 case 315 /* JSDocCallbackTag */:
115980                 case 322 /* JSDocTypedefTag */:
115981                 case 273 /* JsxAttribute */:
115982                 case 249 /* ModuleDeclaration */:
115983                 case 252 /* NamespaceExportDeclaration */:
115984                 case 256 /* NamespaceImport */:
115985                 case 262 /* NamespaceExport */:
115986                 case 156 /* Parameter */:
115987                 case 282 /* ShorthandPropertyAssignment */:
115988                 case 247 /* TypeAliasDeclaration */:
115989                 case 155 /* TypeParameter */:
115990                     return true;
115991                 case 281 /* PropertyAssignment */:
115992                     // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.)
115993                     return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent);
115994                 case 244 /* FunctionDeclaration */:
115995                 case 201 /* FunctionExpression */:
115996                 case 162 /* Constructor */:
115997                 case 161 /* MethodDeclaration */:
115998                 case 163 /* GetAccessor */:
115999                 case 164 /* SetAccessor */:
116000                     return !!decl.body;
116001                 case 242 /* VariableDeclaration */:
116002                 case 159 /* PropertyDeclaration */:
116003                     return !!decl.initializer || ts.isCatchClause(decl.parent);
116004                 case 160 /* MethodSignature */:
116005                 case 158 /* PropertySignature */:
116006                 case 323 /* JSDocPropertyTag */:
116007                 case 317 /* JSDocParameterTag */:
116008                     return false;
116009                 default:
116010                     return ts.Debug.failBadSyntaxKind(decl);
116011             }
116012         }
116013         /** Encapsulates the core find-all-references algorithm. */
116014         var Core;
116015         (function (Core) {
116016             /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
116017             function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
116018                 if (options === void 0) { options = {}; }
116019                 if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
116020                 if (options.use === 1 /* References */) {
116021                     node = ts.getAdjustedReferenceLocation(node);
116022                 }
116023                 else if (options.use === 2 /* Rename */) {
116024                     node = ts.getAdjustedRenameLocation(node);
116025                 }
116026                 if (ts.isSourceFile(node)) {
116027                     var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
116028                     var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol);
116029                     return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
116030                 }
116031                 if (!options.implementations) {
116032                     var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
116033                     if (special) {
116034                         return special;
116035                     }
116036                 }
116037                 var checker = program.getTypeChecker();
116038                 var symbol = checker.getSymbolAtLocation(node);
116039                 // Could not find a symbol e.g. unknown identifier
116040                 if (!symbol) {
116041                     // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
116042                     return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined;
116043                 }
116044                 if (symbol.escapedName === "export=" /* ExportEquals */) {
116045                     return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
116046                 }
116047                 var moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
116048                 if (moduleReferences && !(symbol.flags & 33554432 /* Transient */)) {
116049                     return moduleReferences;
116050                 }
116051                 var aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker);
116052                 var moduleReferencesOfExportTarget = aliasedSymbol &&
116053                     getReferencedSymbolsForModuleIfDeclaredBySourceFile(aliasedSymbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
116054                 var references = getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
116055                 return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget);
116056             }
116057             Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
116058             function getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker) {
116059                 if (node.parent && ts.isNamespaceExportDeclaration(node.parent)) {
116060                     var aliasedSymbol = checker.getAliasedSymbol(symbol);
116061                     var targetSymbol = checker.getMergedSymbol(aliasedSymbol);
116062                     if (aliasedSymbol !== targetSymbol) {
116063                         return targetSymbol;
116064                     }
116065                 }
116066                 return undefined;
116067             }
116068             function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
116069                 var moduleSourceFile = (symbol.flags & 1536 /* Module */) && symbol.declarations && ts.find(symbol.declarations, ts.isSourceFile);
116070                 if (!moduleSourceFile)
116071                     return undefined;
116072                 var exportEquals = symbol.exports.get("export=" /* ExportEquals */);
116073                 // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
116074                 var moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
116075                 if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName))
116076                     return moduleReferences;
116077                 // Continue to get references to 'export ='.
116078                 var checker = program.getTypeChecker();
116079                 symbol = ts.skipAlias(exportEquals, checker);
116080                 return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(symbol, /*node*/ undefined, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
116081             }
116082             /**
116083              * Merges the references by sorting them (by file index in sourceFiles and their location in it) that point to same definition symbol
116084              */
116085             function mergeReferences(program) {
116086                 var referencesToMerge = [];
116087                 for (var _i = 1; _i < arguments.length; _i++) {
116088                     referencesToMerge[_i - 1] = arguments[_i];
116089                 }
116090                 var result;
116091                 for (var _a = 0, referencesToMerge_1 = referencesToMerge; _a < referencesToMerge_1.length; _a++) {
116092                     var references = referencesToMerge_1[_a];
116093                     if (!references || !references.length)
116094                         continue;
116095                     if (!result) {
116096                         result = references;
116097                         continue;
116098                     }
116099                     var _loop_3 = function (entry) {
116100                         if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
116101                             result.push(entry);
116102                             return "continue";
116103                         }
116104                         var symbol = entry.definition.symbol;
116105                         var refIndex = ts.findIndex(result, function (ref) { return !!ref.definition &&
116106                             ref.definition.type === 0 /* Symbol */ &&
116107                             ref.definition.symbol === symbol; });
116108                         if (refIndex === -1) {
116109                             result.push(entry);
116110                             return "continue";
116111                         }
116112                         var reference = result[refIndex];
116113                         result[refIndex] = {
116114                             definition: reference.definition,
116115                             references: reference.references.concat(entry.references).sort(function (entry1, entry2) {
116116                                 var entry1File = getSourceFileIndexOfEntry(program, entry1);
116117                                 var entry2File = getSourceFileIndexOfEntry(program, entry2);
116118                                 if (entry1File !== entry2File) {
116119                                     return ts.compareValues(entry1File, entry2File);
116120                                 }
116121                                 var entry1Span = getTextSpanOfEntry(entry1);
116122                                 var entry2Span = getTextSpanOfEntry(entry2);
116123                                 return entry1Span.start !== entry2Span.start ?
116124                                     ts.compareValues(entry1Span.start, entry2Span.start) :
116125                                     ts.compareValues(entry1Span.length, entry2Span.length);
116126                             })
116127                         };
116128                     };
116129                     for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
116130                         var entry = references_1[_b];
116131                         _loop_3(entry);
116132                     }
116133                 }
116134                 return result;
116135             }
116136             function getSourceFileIndexOfEntry(program, entry) {
116137                 var sourceFile = entry.kind === 0 /* Span */ ?
116138                     program.getSourceFile(entry.fileName) :
116139                     entry.node.getSourceFile();
116140                 return program.getSourceFiles().indexOf(sourceFile);
116141             }
116142             function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
116143                 ts.Debug.assert(!!symbol.valueDeclaration);
116144                 var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) {
116145                     if (reference.kind === "import") {
116146                         var parent = reference.literal.parent;
116147                         if (ts.isLiteralTypeNode(parent)) {
116148                             var importType = ts.cast(parent.parent, ts.isImportTypeNode);
116149                             if (excludeImportTypeOfExportEquals && !importType.qualifier) {
116150                                 return undefined;
116151                             }
116152                         }
116153                         // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway.
116154                         return nodeEntry(reference.literal);
116155                     }
116156                     else {
116157                         return {
116158                             kind: 0 /* Span */,
116159                             fileName: reference.referencingFile.fileName,
116160                             textSpan: ts.createTextSpanFromRange(reference.ref),
116161                         };
116162                     }
116163                 });
116164                 if (symbol.declarations) {
116165                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
116166                         var decl = _a[_i];
116167                         switch (decl.kind) {
116168                             case 290 /* SourceFile */:
116169                                 // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
116170                                 break;
116171                             case 249 /* ModuleDeclaration */:
116172                                 if (sourceFilesSet.has(decl.getSourceFile().fileName)) {
116173                                     references.push(nodeEntry(decl.name));
116174                                 }
116175                                 break;
116176                             default:
116177                                 // This may be merged with something.
116178                                 ts.Debug.assert(!!(symbol.flags & 33554432 /* Transient */), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
116179                         }
116180                     }
116181                 }
116182                 var exported = symbol.exports.get("export=" /* ExportEquals */);
116183                 if (exported) {
116184                     for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) {
116185                         var decl = _c[_b];
116186                         var sourceFile = decl.getSourceFile();
116187                         if (sourceFilesSet.has(sourceFile.fileName)) {
116188                             // At `module.exports = ...`, reference node is `module`
116189                             var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) ? decl.left.expression :
116190                                 ts.isExportAssignment(decl) ? ts.Debug.checkDefined(ts.findChildOfKind(decl, 89 /* ExportKeyword */, sourceFile)) :
116191                                     ts.getNameOfDeclaration(decl) || decl;
116192                             references.push(nodeEntry(node));
116193                         }
116194                     }
116195                 }
116196                 return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray;
116197             }
116198             /** As in a `readonly prop: any` or `constructor(readonly prop: any)`, not a `readonly any[]`. */
116199             function isReadonlyTypeOperator(node) {
116200                 return node.kind === 138 /* ReadonlyKeyword */
116201                     && ts.isTypeOperatorNode(node.parent)
116202                     && node.parent.operator === 138 /* ReadonlyKeyword */;
116203             }
116204             /** getReferencedSymbols for special node kinds. */
116205             function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
116206                 if (ts.isTypeKeyword(node.kind)) {
116207                     // A void expression (i.e., `void foo()`) is not special, but the `void` type is.
116208                     if (node.kind === 110 /* VoidKeyword */ && ts.isVoidExpression(node.parent)) {
116209                         return undefined;
116210                     }
116211                     // A modifier readonly (like on a property declaration) is not special;
116212                     // a readonly type keyword (like `readonly string[]`) is.
116213                     if (node.kind === 138 /* ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) {
116214                         return undefined;
116215                     }
116216                     // Likewise, when we *are* looking for a special keyword, make sure we
116217                     // *don’t* include readonly member modifiers.
116218                     return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken, node.kind === 138 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : undefined);
116219                 }
116220                 // Labels
116221                 if (ts.isJumpStatementTarget(node)) {
116222                     var labelDefinition = ts.getTargetLabel(node.parent, node.text);
116223                     // if we have a label definition, look within its statement for references, if not, then
116224                     // the label is undefined and we have no results..
116225                     return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
116226                 }
116227                 else if (ts.isLabelOfLabeledStatement(node)) {
116228                     // it is a label definition and not a target, search within the parent labeledStatement
116229                     return getLabelReferencesInNode(node.parent, node);
116230                 }
116231                 if (ts.isThis(node)) {
116232                     return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
116233                 }
116234                 if (node.kind === 102 /* SuperKeyword */) {
116235                     return getReferencesForSuperKeyword(node);
116236                 }
116237                 return undefined;
116238             }
116239             /** Core find-all-references algorithm for a normal symbol. */
116240             function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
116241                 var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol;
116242                 // Compute the meaning from the location and the symbol it references
116243                 var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
116244                 var result = [];
116245                 var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
116246                 var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier);
116247                 if (exportSpecifier) {
116248                     // When renaming at an export specifier, rename the export and not the thing being exported.
116249                     getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);
116250                 }
116251                 else if (node && node.kind === 84 /* DefaultKeyword */) {
116252                     addReference(node, symbol, state);
116253                     searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
116254                 }
116255                 else {
116256                     var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
116257                     getReferencesInContainerOrFiles(symbol, state, search);
116258                 }
116259                 return result;
116260             }
116261             function getReferencesInContainerOrFiles(symbol, state, search) {
116262                 // Try to get the smallest valid scope that we can limit our search to;
116263                 // otherwise we'll need to search globally (i.e. include each file).
116264                 var scope = getSymbolScope(symbol);
116265                 if (scope) {
116266                     getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope)));
116267                 }
116268                 else {
116269                     // Global search
116270                     for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) {
116271                         var sourceFile = _a[_i];
116272                         state.cancellationToken.throwIfCancellationRequested();
116273                         searchForName(sourceFile, search, state);
116274                     }
116275                 }
116276             }
116277             function getSpecialSearchKind(node) {
116278                 switch (node.kind) {
116279                     case 129 /* ConstructorKeyword */:
116280                         return 1 /* Constructor */;
116281                     case 75 /* Identifier */:
116282                         if (ts.isClassLike(node.parent)) {
116283                             ts.Debug.assert(node.parent.name === node);
116284                             return 2 /* Class */;
116285                         }
116286                     // falls through
116287                     default:
116288                         return 0 /* None */;
116289                 }
116290             }
116291             /** Handle a few special cases relating to export/import specifiers. */
116292             function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) {
116293                 var parent = node.parent;
116294                 if (ts.isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) {
116295                     return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
116296                 }
116297                 // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references.
116298                 return ts.firstDefined(symbol.declarations, function (decl) {
116299                     if (!decl.parent) {
116300                         // Ignore UMD module and global merge
116301                         if (symbol.flags & 33554432 /* Transient */)
116302                             return undefined;
116303                         // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
116304                         ts.Debug.fail("Unexpected symbol at " + ts.Debug.formatSyntaxKind(node.kind) + ": " + ts.Debug.formatSymbol(symbol));
116305                     }
116306                     return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
116307                         ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name)
116308                         : undefined;
116309                 });
116310             }
116311             var SpecialSearchKind;
116312             (function (SpecialSearchKind) {
116313                 SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None";
116314                 SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor";
116315                 SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class";
116316             })(SpecialSearchKind || (SpecialSearchKind = {}));
116317             function getNonModuleSymbolOfMergedModuleSymbol(symbol) {
116318                 if (!(symbol.flags & (1536 /* Module */ | 33554432 /* Transient */)))
116319                     return undefined;
116320                 var decl = symbol.declarations && ts.find(symbol.declarations, function (d) { return !ts.isSourceFile(d) && !ts.isModuleDeclaration(d); });
116321                 return decl && decl.symbol;
116322             }
116323             /**
116324              * Holds all state needed for the finding references.
116325              * Unlike `Search`, there is only one `State`.
116326              */
116327             var State = /** @class */ (function () {
116328                 function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
116329                     this.sourceFiles = sourceFiles;
116330                     this.sourceFilesSet = sourceFilesSet;
116331                     this.specialSearchKind = specialSearchKind;
116332                     this.checker = checker;
116333                     this.cancellationToken = cancellationToken;
116334                     this.searchMeaning = searchMeaning;
116335                     this.options = options;
116336                     this.result = result;
116337                     /** Cache for `explicitlyinheritsFrom`. */
116338                     this.inheritsFromCache = ts.createMap();
116339                     /**
116340                      * Type nodes can contain multiple references to the same type. For example:
116341                      *      let x: Foo & (Foo & Bar) = ...
116342                      * Because we are returning the implementation locations and not the identifier locations,
116343                      * duplicate entries would be returned here as each of the type references is part of
116344                      * the same implementation. For that reason, check before we add a new entry.
116345                      */
116346                     this.markSeenContainingTypeReference = ts.nodeSeenTracker();
116347                     /**
116348                      * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once.
116349                      * For example:
116350                      *     // b.ts
116351                      *     export { foo as bar } from "./a";
116352                      *     import { bar } from "./b";
116353                      *
116354                      * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local).
116355                      * But another reference to it may appear in the same source file.
116356                      * See `tests/cases/fourslash/transitiveExportImports3.ts`.
116357                      */
116358                     this.markSeenReExportRHS = ts.nodeSeenTracker();
116359                     this.symbolIdToReferences = [];
116360                     // Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
116361                     this.sourceFileToSeenSymbols = [];
116362                 }
116363                 State.prototype.includesSourceFile = function (sourceFile) {
116364                     return this.sourceFilesSet.has(sourceFile.fileName);
116365                 };
116366                 /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
116367                 State.prototype.getImportSearches = function (exportSymbol, exportInfo) {
116368                     if (!this.importTracker)
116369                         this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken);
116370                     return this.importTracker(exportSymbol, exportInfo, this.options.use === 2 /* Rename */);
116371                 };
116372                 /** @param allSearchSymbols set of additional symbols for use by `includes`. */
116373                 State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) {
116374                     if (searchOptions === void 0) { searchOptions = {}; }
116375                     // Note: if this is an external module symbol, the name doesn't include quotes.
116376                     // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`.
116377                     // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form
116378                     // here appears to be intentional).
116379                     var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.symbolName(ts.getLocalSymbolForExportDefault(symbol) || getNonModuleSymbolOfMergedModuleSymbol(symbol) || symbol)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b;
116380                     var escapedText = ts.escapeLeadingUnderscores(text);
116381                     var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined;
116382                     return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } };
116383                 };
116384                 /**
116385                  * Callback to add references for a particular searched symbol.
116386                  * This initializes a reference group, so only call this if you will add at least one reference.
116387                  */
116388                 State.prototype.referenceAdder = function (searchSymbol) {
116389                     var symbolId = ts.getSymbolId(searchSymbol);
116390                     var references = this.symbolIdToReferences[symbolId];
116391                     if (!references) {
116392                         references = this.symbolIdToReferences[symbolId] = [];
116393                         this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references });
116394                     }
116395                     return function (node, kind) { return references.push(nodeEntry(node, kind)); };
116396                 };
116397                 /** Add a reference with no associated definition. */
116398                 State.prototype.addStringOrCommentReference = function (fileName, textSpan) {
116399                     this.result.push({
116400                         definition: undefined,
116401                         references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }]
116402                     });
116403                 };
116404                 /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
116405                 State.prototype.markSearchedSymbols = function (sourceFile, symbols) {
116406                     var sourceId = ts.getNodeId(sourceFile);
116407                     var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
116408                     var anyNewSymbols = false;
116409                     for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
116410                         var sym = symbols_3[_i];
116411                         anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
116412                     }
116413                     return anyNewSymbols;
116414                 };
116415                 return State;
116416             }());
116417             /** Search for all imports of a given exported symbol using `State.getImportSearches`. */
116418             function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) {
116419                 var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
116420                 // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
116421                 if (singleReferences.length) {
116422                     var addRef = state.referenceAdder(exportSymbol);
116423                     for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
116424                         var singleRef = singleReferences_1[_i];
116425                         if (shouldAddSingleReference(singleRef, state))
116426                             addRef(singleRef);
116427                     }
116428                 }
116429                 // For each import, find all references to that import in its source file.
116430                 for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) {
116431                     var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1];
116432                     getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state);
116433                 }
116434                 if (indirectUsers.length) {
116435                     var indirectSearch = void 0;
116436                     switch (exportInfo.exportKind) {
116437                         case 0 /* Named */:
116438                             indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */);
116439                             break;
116440                         case 1 /* Default */:
116441                             // Search for a property access to '.default'. This can't be renamed.
116442                             indirectSearch = state.options.use === 2 /* Rename */ ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" });
116443                             break;
116444                         case 2 /* ExportEquals */:
116445                             break;
116446                     }
116447                     if (indirectSearch) {
116448                         for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) {
116449                             var indirectUser = indirectUsers_1[_d];
116450                             searchForName(indirectUser, indirectSearch, state);
116451                         }
116452                     }
116453                 }
116454             }
116455             function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) {
116456                 var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken);
116457                 var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers;
116458                 for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) {
116459                     var importLocation = importSearches_2[_i][0];
116460                     cb(importLocation);
116461                 }
116462                 for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) {
116463                     var indirectUser = indirectUsers_2[_b];
116464                     for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
116465                         var node = _d[_c];
116466                         // Import specifiers should be handled by importSearches
116467                         if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) {
116468                             cb(node);
116469                         }
116470                     }
116471                 }
116472             }
116473             Core.eachExportReference = eachExportReference;
116474             function shouldAddSingleReference(singleRef, state) {
116475                 if (!hasMatchingMeaning(singleRef, state))
116476                     return false;
116477                 if (state.options.use !== 2 /* Rename */)
116478                     return true;
116479                 // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;`
116480                 if (!ts.isIdentifier(singleRef))
116481                     return false;
116482                 // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
116483                 return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */);
116484             }
116485             // Go to the symbol we imported from and find references for it.
116486             function searchForImportedSymbol(symbol, state) {
116487                 if (!symbol.declarations)
116488                     return;
116489                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
116490                     var declaration = _a[_i];
116491                     var exportingFile = declaration.getSourceFile();
116492                     // Need to search in the file even if it's not in the search-file set, because it might export the symbol.
116493                     getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile));
116494                 }
116495             }
116496             /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
116497             function searchForName(sourceFile, search, state) {
116498                 if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) {
116499                     getReferencesInSourceFile(sourceFile, search, state);
116500                 }
116501             }
116502             function getPropertySymbolOfDestructuringAssignment(location, checker) {
116503                 return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent)
116504                     ? checker.getPropertySymbolOfDestructuringAssignment(location)
116505                     : undefined;
116506             }
116507             /**
116508              * Determines the smallest scope in which a symbol may have named references.
116509              * Note that not every construct has been accounted for. This function can
116510              * probably be improved.
116511              *
116512              * @returns undefined if the scope cannot be determined, implying that
116513              * a reference to a symbol can occur anywhere.
116514              */
116515             function getSymbolScope(symbol) {
116516                 // If this is the symbol of a named function expression or named class expression,
116517                 // then named references are limited to its own scope.
116518                 var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration;
116519                 if (valueDeclaration && (valueDeclaration.kind === 201 /* FunctionExpression */ || valueDeclaration.kind === 214 /* ClassExpression */)) {
116520                     return valueDeclaration;
116521                 }
116522                 if (!declarations) {
116523                     return undefined;
116524                 }
116525                 // If this is private property or method, the scope is the containing class
116526                 if (flags & (4 /* Property */ | 8192 /* Method */)) {
116527                     var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(d); });
116528                     if (privateDeclaration) {
116529                         return ts.getAncestor(privateDeclaration, 245 /* ClassDeclaration */);
116530                     }
116531                     // Else this is a public property and could be accessed from anywhere.
116532                     return undefined;
116533                 }
116534                 // If symbol is of object binding pattern element without property name we would want to
116535                 // look for property too and that could be anywhere
116536                 if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) {
116537                     return undefined;
116538                 }
116539                 /*
116540                 If the symbol has a parent, it's globally visible unless:
116541                 - It's a private property (handled above).
116542                 - It's a type parameter.
116543                 - The parent is an external module: then we should only search in the module (and recurse on the export later).
116544                 - But if the parent has `export as namespace`, the symbol is globally visible through that namespace.
116545                 */
116546                 var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */);
116547                 if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) {
116548                     return undefined;
116549                 }
116550                 var scope;
116551                 for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
116552                     var declaration = declarations_1[_i];
116553                     var container = ts.getContainerNode(declaration);
116554                     if (scope && scope !== container) {
116555                         // Different declarations have different containers, bail out
116556                         return undefined;
116557                     }
116558                     if (!container || container.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
116559                         // This is a global variable and not an external module, any declaration defined
116560                         // within this scope is visible outside the file
116561                         return undefined;
116562                     }
116563                     // The search scope is the container node
116564                     scope = container;
116565                 }
116566                 // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.)
116567                 // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.:
116568                 //     declare module "a" { export type T = number; }
116569                 //     declare module "b" { import { T } from "a"; export const x: T; }
116570                 // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.)
116571                 return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217
116572             }
116573             /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
116574             function isSymbolReferencedInFile(definition, checker, sourceFile, searchContainer) {
116575                 if (searchContainer === void 0) { searchContainer = sourceFile; }
116576                 return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }, searchContainer) || false;
116577             }
116578             Core.isSymbolReferencedInFile = isSymbolReferencedInFile;
116579             function eachSymbolReferenceInFile(definition, checker, sourceFile, cb, searchContainer) {
116580                 if (searchContainer === void 0) { searchContainer = sourceFile; }
116581                 var symbol = ts.isParameterPropertyDeclaration(definition.parent, definition.parent.parent)
116582                     ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text))
116583                     : checker.getSymbolAtLocation(definition);
116584                 if (!symbol)
116585                     return undefined;
116586                 for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer); _i < _a.length; _i++) {
116587                     var token = _a[_i];
116588                     if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText)
116589                         continue;
116590                     var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary
116591                     if (referenceSymbol === symbol
116592                         || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol
116593                         || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) {
116594                         var res = cb(token);
116595                         if (res)
116596                             return res;
116597                     }
116598                 }
116599             }
116600             Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile;
116601             function eachSignatureCall(signature, sourceFiles, checker, cb) {
116602                 if (!signature.name || !ts.isIdentifier(signature.name))
116603                     return;
116604                 var symbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(signature.name));
116605                 for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
116606                     var sourceFile = sourceFiles_3[_i];
116607                     for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
116608                         var name = _b[_a];
116609                         if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
116610                             continue;
116611                         var called = ts.climbPastPropertyAccess(name);
116612                         var call = called.parent;
116613                         if (!ts.isCallExpression(call) || call.expression !== called)
116614                             continue;
116615                         var referenceSymbol = checker.getSymbolAtLocation(name);
116616                         if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) {
116617                             cb(call);
116618                         }
116619                     }
116620                 }
116621             }
116622             Core.eachSignatureCall = eachSignatureCall;
116623             function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) {
116624                 if (container === void 0) { container = sourceFile; }
116625                 return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); });
116626             }
116627             function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) {
116628                 if (container === void 0) { container = sourceFile; }
116629                 var positions = [];
116630                 /// TODO: Cache symbol existence for files to save text search
116631                 // Also, need to make this work for unicode escapes.
116632                 // Be resilient in the face of a symbol with no name or zero length name
116633                 if (!symbolName || !symbolName.length) {
116634                     return positions;
116635                 }
116636                 var text = sourceFile.text;
116637                 var sourceLength = text.length;
116638                 var symbolNameLength = symbolName.length;
116639                 var position = text.indexOf(symbolName, container.pos);
116640                 while (position >= 0) {
116641                     // If we are past the end, stop looking
116642                     if (position > container.end)
116643                         break;
116644                     // We found a match.  Make sure it's not part of a larger word (i.e. the char
116645                     // before and after it have to be a non-identifier char).
116646                     var endPosition = position + symbolNameLength;
116647                     if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 99 /* Latest */)) &&
116648                         (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 99 /* Latest */))) {
116649                         // Found a real match.  Keep searching.
116650                         positions.push(position);
116651                     }
116652                     position = text.indexOf(symbolName, position + symbolNameLength + 1);
116653                 }
116654                 return positions;
116655             }
116656             function getLabelReferencesInNode(container, targetLabel) {
116657                 var sourceFile = container.getSourceFile();
116658                 var labelName = targetLabel.text;
116659                 var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) {
116660                     // Only pick labels that are either the target label, or have a target that is the target label
116661                     return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? nodeEntry(node) : undefined;
116662                 });
116663                 return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }];
116664             }
116665             function isValidReferencePosition(node, searchSymbolName) {
116666                 // Compare the length so we filter out strict superstrings of the symbol we are looking for
116667                 switch (node.kind) {
116668                     case 76 /* PrivateIdentifier */:
116669                     case 75 /* Identifier */:
116670                         return node.text.length === searchSymbolName.length;
116671                     case 14 /* NoSubstitutionTemplateLiteral */:
116672                     case 10 /* StringLiteral */: {
116673                         var str = node;
116674                         return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) &&
116675                             str.text.length === searchSymbolName.length;
116676                     }
116677                     case 8 /* NumericLiteral */:
116678                         return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length;
116679                     case 84 /* DefaultKeyword */:
116680                         return "default".length === searchSymbolName.length;
116681                     default:
116682                         return false;
116683                 }
116684             }
116685             function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken, filter) {
116686                 var references = ts.flatMap(sourceFiles, function (sourceFile) {
116687                     cancellationToken.throwIfCancellationRequested();
116688                     return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) {
116689                         if (referenceLocation.kind === keywordKind && (!filter || filter(referenceLocation))) {
116690                             return nodeEntry(referenceLocation);
116691                         }
116692                     });
116693                 });
116694                 return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined;
116695             }
116696             function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) {
116697                 if (addReferencesHere === void 0) { addReferencesHere = true; }
116698                 state.cancellationToken.throwIfCancellationRequested();
116699                 return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere);
116700             }
116701             /**
116702              * Search within node "container" for references for a search value, where the search value is defined as a
116703              * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
116704              * searchLocation: a node where the search value
116705              */
116706             function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) {
116707                 if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) {
116708                     return;
116709                 }
116710                 for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) {
116711                     var position = _a[_i];
116712                     getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
116713                 }
116714             }
116715             function hasMatchingMeaning(referenceLocation, state) {
116716                 return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
116717             }
116718             function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
116719                 var referenceLocation = ts.getTouchingPropertyName(sourceFile, position);
116720                 if (!isValidReferencePosition(referenceLocation, search.text)) {
116721                     // This wasn't the start of a token.  Check to see if it might be a
116722                     // match in a comment or string if that's what the caller is asking
116723                     // for.
116724                     if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) {
116725                         // In the case where we're looking inside comments/strings, we don't have
116726                         // an actual definition.  So just use 'undefined' here.  Features like
116727                         // 'Rename' won't care (as they ignore the definitions), and features like
116728                         // 'FindReferences' will just filter out these results.
116729                         state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length));
116730                     }
116731                     return;
116732                 }
116733                 if (!hasMatchingMeaning(referenceLocation, state))
116734                     return;
116735                 var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
116736                 if (!referenceSymbol) {
116737                     return;
116738                 }
116739                 var parent = referenceLocation.parent;
116740                 if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) {
116741                     // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again.
116742                     return;
116743                 }
116744                 if (ts.isExportSpecifier(parent)) {
116745                     ts.Debug.assert(referenceLocation.kind === 75 /* Identifier */);
116746                     getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere);
116747                     return;
116748                 }
116749                 var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state);
116750                 if (!relatedSymbol) {
116751                     getReferenceForShorthandProperty(referenceSymbol, search, state);
116752                     return;
116753                 }
116754                 switch (state.specialSearchKind) {
116755                     case 0 /* None */:
116756                         if (addReferencesHere)
116757                             addReference(referenceLocation, relatedSymbol, state);
116758                         break;
116759                     case 1 /* Constructor */:
116760                         addConstructorReferences(referenceLocation, sourceFile, search, state);
116761                         break;
116762                     case 2 /* Class */:
116763                         addClassStaticThisReferences(referenceLocation, search, state);
116764                         break;
116765                     default:
116766                         ts.Debug.assertNever(state.specialSearchKind);
116767                 }
116768                 getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
116769             }
116770             function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
116771                 ts.Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled");
116772                 var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
116773                 var exportDeclaration = parent.parent;
116774                 var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
116775                 if (!alwaysGetReferences && !search.includes(localSymbol)) {
116776                     return;
116777                 }
116778                 if (!propertyName) {
116779                     // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export)
116780                     if (!(state.options.use === 2 /* Rename */ && (name.escapedText === "default" /* Default */))) {
116781                         addRef();
116782                     }
116783                 }
116784                 else if (referenceLocation === propertyName) {
116785                     // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export.
116786                     // For `export { foo as bar };`, where `foo` is a local, so add it now.
116787                     if (!exportDeclaration.moduleSpecifier) {
116788                         addRef();
116789                     }
116790                     if (addReferencesHere && state.options.use !== 2 /* Rename */ && state.markSeenReExportRHS(name)) {
116791                         addReference(name, ts.Debug.checkDefined(exportSpecifier.symbol), state);
116792                     }
116793                 }
116794                 else {
116795                     if (state.markSeenReExportRHS(referenceLocation)) {
116796                         addRef();
116797                     }
116798                 }
116799                 // For `export { foo as bar }`, rename `foo`, but not `bar`.
116800                 if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
116801                     var isDefaultExport = referenceLocation.originalKeywordKind === 84 /* DefaultKeyword */
116802                         || exportSpecifier.name.originalKeywordKind === 84 /* DefaultKeyword */;
116803                     var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
116804                     var exportSymbol = ts.Debug.checkDefined(exportSpecifier.symbol);
116805                     var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker);
116806                     if (exportInfo) {
116807                         searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
116808                     }
116809                 }
116810                 // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
116811                 if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) {
116812                     var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
116813                     if (imported)
116814                         searchForImportedSymbol(imported, state);
116815                 }
116816                 function addRef() {
116817                     if (addReferencesHere)
116818                         addReference(referenceLocation, localSymbol, state);
116819                 }
116820             }
116821             function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
116822                 return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol;
116823             }
116824             function isExportSpecifierAlias(referenceLocation, exportSpecifier) {
116825                 var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
116826                 ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation);
116827                 if (propertyName) {
116828                     // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol.
116829                     return propertyName === referenceLocation;
116830                 }
116831                 else {
116832                     // `export { foo } from "foo"` is a re-export.
116833                     // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`.
116834                     return !parent.parent.moduleSpecifier;
116835                 }
116836             }
116837             function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) {
116838                 var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */);
116839                 if (!importOrExport)
116840                     return;
116841                 var symbol = importOrExport.symbol;
116842                 if (importOrExport.kind === 0 /* Import */) {
116843                     if (!(isForRenameWithPrefixAndSuffixText(state.options))) {
116844                         searchForImportedSymbol(symbol, state);
116845                     }
116846                 }
116847                 else {
116848                     searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
116849                 }
116850             }
116851             function getReferenceForShorthandProperty(_a, search, state) {
116852                 var flags = _a.flags, valueDeclaration = _a.valueDeclaration;
116853                 var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
116854                 var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration);
116855                 /*
116856                 * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment
116857                 * has two meanings: property name and property value. Therefore when we do findAllReference at the position where
116858                 * an identifier is declared, the language service should return the position of the variable declaration as well as
116859                 * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the
116860                 * position of property accessing, the referenceEntry of such position will be handled in the first case.
116861                 */
116862                 if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) {
116863                     addReference(name, shorthandValueSymbol, state);
116864                 }
116865             }
116866             function addReference(referenceLocation, relatedSymbol, state) {
116867                 var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; // eslint-disable-line no-in-operator
116868                 var addRef = state.referenceAdder(symbol);
116869                 if (state.options.implementations) {
116870                     addImplementationReferences(referenceLocation, addRef, state);
116871                 }
116872                 else {
116873                     addRef(referenceLocation, kind);
116874                 }
116875             }
116876             /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses.  */
116877             function addConstructorReferences(referenceLocation, sourceFile, search, state) {
116878                 if (ts.isNewExpressionTarget(referenceLocation)) {
116879                     addReference(referenceLocation, search.symbol, state);
116880                 }
116881                 var pusher = function () { return state.referenceAdder(search.symbol); };
116882                 if (ts.isClassLike(referenceLocation.parent)) {
116883                     ts.Debug.assert(referenceLocation.kind === 84 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
116884                     // This is the class declaration containing the constructor.
116885                     findOwnConstructorReferences(search.symbol, sourceFile, pusher());
116886                 }
116887                 else {
116888                     // If this class appears in `extends C`, then the extending class' "super" calls are references.
116889                     var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
116890                     if (classExtending) {
116891                         findSuperConstructorAccesses(classExtending, pusher());
116892                         findInheritedConstructorReferences(classExtending, state);
116893                     }
116894                 }
116895             }
116896             function addClassStaticThisReferences(referenceLocation, search, state) {
116897                 addReference(referenceLocation, search.symbol, state);
116898                 var classLike = referenceLocation.parent;
116899                 if (state.options.use === 2 /* Rename */ || !ts.isClassLike(classLike))
116900                     return;
116901                 ts.Debug.assert(classLike.name === referenceLocation);
116902                 var addRef = state.referenceAdder(search.symbol);
116903                 for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) {
116904                     var member = _a[_i];
116905                     if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) {
116906                         continue;
116907                     }
116908                     if (member.body) {
116909                         member.body.forEachChild(function cb(node) {
116910                             if (node.kind === 104 /* ThisKeyword */) {
116911                                 addRef(node);
116912                             }
116913                             else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
116914                                 node.forEachChild(cb);
116915                             }
116916                         });
116917                     }
116918                 }
116919             }
116920             /**
116921              * `classSymbol` is the class where the constructor was defined.
116922              * Reference the constructor and all calls to `new this()`.
116923              */
116924             function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
116925                 var constructorSymbol = getClassConstructorSymbol(classSymbol);
116926                 if (constructorSymbol && constructorSymbol.declarations) {
116927                     for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) {
116928                         var decl = _a[_i];
116929                         var ctrKeyword = ts.findChildOfKind(decl, 129 /* ConstructorKeyword */, sourceFile);
116930                         ts.Debug.assert(decl.kind === 162 /* Constructor */ && !!ctrKeyword);
116931                         addNode(ctrKeyword);
116932                     }
116933                 }
116934                 if (classSymbol.exports) {
116935                     classSymbol.exports.forEach(function (member) {
116936                         var decl = member.valueDeclaration;
116937                         if (decl && decl.kind === 161 /* MethodDeclaration */) {
116938                             var body = decl.body;
116939                             if (body) {
116940                                 forEachDescendantOfKind(body, 104 /* ThisKeyword */, function (thisKeyword) {
116941                                     if (ts.isNewExpressionTarget(thisKeyword)) {
116942                                         addNode(thisKeyword);
116943                                     }
116944                                 });
116945                             }
116946                         }
116947                     });
116948                 }
116949             }
116950             function getClassConstructorSymbol(classSymbol) {
116951                 return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
116952             }
116953             /** Find references to `super` in the constructor of an extending class.  */
116954             function findSuperConstructorAccesses(classDeclaration, addNode) {
116955                 var constructor = getClassConstructorSymbol(classDeclaration.symbol);
116956                 if (!(constructor && constructor.declarations)) {
116957                     return;
116958                 }
116959                 for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) {
116960                     var decl = _a[_i];
116961                     ts.Debug.assert(decl.kind === 162 /* Constructor */);
116962                     var body = decl.body;
116963                     if (body) {
116964                         forEachDescendantOfKind(body, 102 /* SuperKeyword */, function (node) {
116965                             if (ts.isCallExpressionTarget(node)) {
116966                                 addNode(node);
116967                             }
116968                         });
116969                     }
116970                 }
116971             }
116972             function hasOwnConstructor(classDeclaration) {
116973                 return !!getClassConstructorSymbol(classDeclaration.symbol);
116974             }
116975             function findInheritedConstructorReferences(classDeclaration, state) {
116976                 if (hasOwnConstructor(classDeclaration))
116977                     return;
116978                 var classSymbol = classDeclaration.symbol;
116979                 var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined);
116980                 getReferencesInContainerOrFiles(classSymbol, state, search);
116981             }
116982             function addImplementationReferences(refNode, addReference, state) {
116983                 // Check if we found a function/propertyAssignment/method with an implementation or initializer
116984                 if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
116985                     addReference(refNode);
116986                     return;
116987                 }
116988                 if (refNode.kind !== 75 /* Identifier */) {
116989                     return;
116990                 }
116991                 if (refNode.parent.kind === 282 /* ShorthandPropertyAssignment */) {
116992                     // Go ahead and dereference the shorthand assignment by going to its definition
116993                     getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference);
116994                 }
116995                 // Check if the node is within an extends or implements clause
116996                 var containingClass = getContainingClassIfInHeritageClause(refNode);
116997                 if (containingClass) {
116998                     addReference(containingClass);
116999                     return;
117000                 }
117001                 // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface
117002                 // Find the first node whose parent isn't a type node -- i.e., the highest type node.
117003                 var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); });
117004                 var typeHavingNode = typeNode.parent;
117005                 if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) {
117006                     if (ts.hasInitializer(typeHavingNode)) {
117007                         addIfImplementation(typeHavingNode.initializer);
117008                     }
117009                     else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) {
117010                         var body = typeHavingNode.body;
117011                         if (body.kind === 223 /* Block */) {
117012                             ts.forEachReturnStatement(body, function (returnStatement) {
117013                                 if (returnStatement.expression)
117014                                     addIfImplementation(returnStatement.expression);
117015                             });
117016                         }
117017                         else {
117018                             addIfImplementation(body);
117019                         }
117020                     }
117021                     else if (ts.isAssertionExpression(typeHavingNode)) {
117022                         addIfImplementation(typeHavingNode.expression);
117023                     }
117024                 }
117025                 function addIfImplementation(e) {
117026                     if (isImplementationExpression(e))
117027                         addReference(e);
117028                 }
117029             }
117030             function getContainingClassIfInHeritageClause(node) {
117031                 return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent)
117032                     : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined;
117033             }
117034             /**
117035              * Returns true if this is an expression that can be considered an implementation
117036              */
117037             function isImplementationExpression(node) {
117038                 switch (node.kind) {
117039                     case 200 /* ParenthesizedExpression */:
117040                         return isImplementationExpression(node.expression);
117041                     case 202 /* ArrowFunction */:
117042                     case 201 /* FunctionExpression */:
117043                     case 193 /* ObjectLiteralExpression */:
117044                     case 214 /* ClassExpression */:
117045                     case 192 /* ArrayLiteralExpression */:
117046                         return true;
117047                     default:
117048                         return false;
117049                 }
117050             }
117051             /**
117052              * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol
117053              * is an interface, determines if some ancestor of the child symbol extends or inherits from it.
117054              * Also takes in a cache of previous results which makes this slightly more efficient and is
117055              * necessary to avoid potential loops like so:
117056              *     class A extends B { }
117057              *     class B extends A { }
117058              *
117059              * We traverse the AST rather than using the type checker because users are typically only interested
117060              * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling
117061              * implementations of types that share a common ancestor with the type whose implementation we are
117062              * searching for need to be filtered out of the results. The type checker doesn't let us make the
117063              * distinction between structurally compatible implementations and explicit implementations, so we
117064              * must use the AST.
117065              *
117066              * @param symbol         A class or interface Symbol
117067              * @param parent        Another class or interface Symbol
117068              * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results
117069              */
117070             function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) {
117071                 if (symbol === parent) {
117072                     return true;
117073                 }
117074                 var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent);
117075                 var cached = cachedResults.get(key);
117076                 if (cached !== undefined) {
117077                     return cached;
117078                 }
117079                 // Set the key so that we don't infinitely recurse
117080                 cachedResults.set(key, false);
117081                 var inherits = !!symbol.declarations && symbol.declarations.some(function (declaration) {
117082                     return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) {
117083                         var type = checker.getTypeAtLocation(typeReference);
117084                         return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker);
117085                     });
117086                 });
117087                 cachedResults.set(key, inherits);
117088                 return inherits;
117089             }
117090             function getReferencesForSuperKeyword(superKeyword) {
117091                 var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false);
117092                 if (!searchSpaceNode) {
117093                     return undefined;
117094                 }
117095                 // Whether 'super' occurs in a static context within a class.
117096                 var staticFlag = 32 /* Static */;
117097                 switch (searchSpaceNode.kind) {
117098                     case 159 /* PropertyDeclaration */:
117099                     case 158 /* PropertySignature */:
117100                     case 161 /* MethodDeclaration */:
117101                     case 160 /* MethodSignature */:
117102                     case 162 /* Constructor */:
117103                     case 163 /* GetAccessor */:
117104                     case 164 /* SetAccessor */:
117105                         staticFlag &= ts.getModifierFlags(searchSpaceNode);
117106                         searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
117107                         break;
117108                     default:
117109                         return undefined;
117110                 }
117111                 var sourceFile = searchSpaceNode.getSourceFile();
117112                 var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) {
117113                     if (node.kind !== 102 /* SuperKeyword */) {
117114                         return;
117115                     }
117116                     var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false);
117117                     // If we have a 'super' container, we must have an enclosing class.
117118                     // Now make sure the owning class is the same as the search-space
117119                     // and has the same static qualifier as the original 'super's owner.
117120                     return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : undefined;
117121                 });
117122                 return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }];
117123             }
117124             function isParameterName(node) {
117125                 return node.kind === 75 /* Identifier */ && node.parent.kind === 156 /* Parameter */ && node.parent.name === node;
117126             }
117127             function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
117128                 var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
117129                 // Whether 'this' occurs in a static context within a class.
117130                 var staticFlag = 32 /* Static */;
117131                 switch (searchSpaceNode.kind) {
117132                     case 161 /* MethodDeclaration */:
117133                     case 160 /* MethodSignature */:
117134                         if (ts.isObjectLiteralMethod(searchSpaceNode)) {
117135                             break;
117136                         }
117137                     // falls through
117138                     case 159 /* PropertyDeclaration */:
117139                     case 158 /* PropertySignature */:
117140                     case 162 /* Constructor */:
117141                     case 163 /* GetAccessor */:
117142                     case 164 /* SetAccessor */:
117143                         staticFlag &= ts.getModifierFlags(searchSpaceNode);
117144                         searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
117145                         break;
117146                     case 290 /* SourceFile */:
117147                         if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
117148                             return undefined;
117149                         }
117150                     // falls through
117151                     case 244 /* FunctionDeclaration */:
117152                     case 201 /* FunctionExpression */:
117153                         break;
117154                     // Computed properties in classes are not handled here because references to this are illegal,
117155                     // so there is no point finding references to them.
117156                     default:
117157                         return undefined;
117158                 }
117159                 var references = ts.flatMap(searchSpaceNode.kind === 290 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
117160                     cancellationToken.throwIfCancellationRequested();
117161                     return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
117162                         if (!ts.isThis(node)) {
117163                             return false;
117164                         }
117165                         var container = ts.getThisContainer(node, /* includeArrowFunctions */ false);
117166                         switch (searchSpaceNode.kind) {
117167                             case 201 /* FunctionExpression */:
117168                             case 244 /* FunctionDeclaration */:
117169                                 return searchSpaceNode.symbol === container.symbol;
117170                             case 161 /* MethodDeclaration */:
117171                             case 160 /* MethodSignature */:
117172                                 return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol;
117173                             case 214 /* ClassExpression */:
117174                             case 245 /* ClassDeclaration */:
117175                                 // Make sure the container belongs to the same class
117176                                 // and has the appropriate static modifier from the original container.
117177                                 return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
117178                             case 290 /* SourceFile */:
117179                                 return container.kind === 290 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
117180                         }
117181                     });
117182                 }).map(function (n) { return nodeEntry(n); });
117183                 var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; });
117184                 return [{
117185                         definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword },
117186                         references: references
117187                     }];
117188             }
117189             function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
117190                 var references = ts.flatMap(sourceFiles, function (sourceFile) {
117191                     cancellationToken.throwIfCancellationRequested();
117192                     return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) {
117193                         return ts.isStringLiteral(ref) && ref.text === node.text ? nodeEntry(ref, 2 /* StringLiteral */) : undefined;
117194                     });
117195                 });
117196                 return [{
117197                         definition: { type: 4 /* String */, node: node },
117198                         references: references
117199                     }];
117200             }
117201             // For certain symbol kinds, we need to include other symbols in the search set.
117202             // This is not needed when searching for re-exports.
117203             function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) {
117204                 var result = [];
117205                 forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), function (sym, root, base) { result.push(base || root || sym); }, 
117206                 /*allowBaseTypes*/ function () { return !implementations; });
117207                 return result;
117208             }
117209             function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) {
117210                 var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location);
117211                 if (containingObjectLiteralElement) {
117212                     /* Because in short-hand property assignment, location has two meaning : property name and as value of the property
117213                     * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of
117214                     * property name and variable declaration of the identifier.
117215                     * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service
117216                     * should show both 'name' in 'obj' and 'name' in variable declaration
117217                     *      const name = "Foo";
117218                     *      const obj = { name };
117219                     * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment
117220                     * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration
117221                     * will be included correctly.
117222                     */
117223                     var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol
117224                     if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) {
117225                         // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property.
117226                         return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */);
117227                     }
117228                     // If the location is in a context sensitive location (i.e. in an object literal) try
117229                     // to get a contextual type for it, and add the property symbol from the contextual
117230                     // type to the search set
117231                     var contextualType = checker.getContextualType(containingObjectLiteralElement.parent);
117232                     var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); });
117233                     if (res_1)
117234                         return res_1;
117235                     // If the location is name of property symbol from object literal destructuring pattern
117236                     // Search the property symbol
117237                     //      for ( { property: p2 } of elems) { }
117238                     var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker);
117239                     var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */);
117240                     if (res1)
117241                         return res1;
117242                     var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */);
117243                     if (res2)
117244                         return res2;
117245                 }
117246                 var aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker);
117247                 if (aliasedSymbol) {
117248                     // In case of UMD module and global merging, search for global as well
117249                     var res_2 = cbSymbol(aliasedSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 1 /* Node */);
117250                     if (res_2)
117251                         return res_2;
117252                 }
117253                 var res = fromRoot(symbol);
117254                 if (res)
117255                     return res;
117256                 if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration, symbol.valueDeclaration.parent)) {
117257                     // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property).
117258                     var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name);
117259                     ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property]
117260                     return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]);
117261                 }
117262                 var exportSpecifier = ts.getDeclarationOfKind(symbol, 263 /* ExportSpecifier */);
117263                 if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) {
117264                     var localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
117265                     if (localSymbol) {
117266                         var res_3 = cbSymbol(localSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 1 /* Node */);
117267                         if (res_3)
117268                             return res_3;
117269                     }
117270                 }
117271                 // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property.
117272                 // Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local.
117273                 if (!isForRenamePopulateSearchSymbolSet) {
117274                     var bindingElementPropertySymbol = void 0;
117275                     if (onlyIncludeBindingElementAtReferenceLocation) {
117276                         bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined;
117277                     }
117278                     else {
117279                         bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
117280                     }
117281                     return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
117282                 }
117283                 ts.Debug.assert(isForRenamePopulateSearchSymbolSet);
117284                 // due to the above assert and the arguments at the uses of this function,
117285                 // (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds
117286                 var includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation;
117287                 if (includeOriginalSymbolOfBindingElement) {
117288                     var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
117289                     return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
117290                 }
117291                 function fromRoot(sym, kind) {
117292                     // If this is a union property:
117293                     //   - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types.
117294                     //   - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search.
117295                     // If the symbol is an instantiation from a another symbol (e.g. widened symbol):
117296                     //   - In populateSearchSymbolsSet, add the root the list
117297                     //   - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.)
117298                     return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) {
117299                         return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind)
117300                             // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
117301                             || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol)
117302                                 ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); })
117303                                 : undefined);
117304                     });
117305                 }
117306                 function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
117307                     var bindingElement = ts.getDeclarationOfKind(symbol, 191 /* BindingElement */);
117308                     if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) {
117309                         return ts.getPropertySymbolFromBindingElement(checker, bindingElement);
117310                     }
117311                 }
117312             }
117313             function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) {
117314                 var checker = state.checker;
117315                 return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, 
117316                 /*onlyIncludeBindingElementAtReferenceLocation*/ state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym)
117317                     // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol.
117318                     ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind }
117319                     : undefined; }, 
117320                 /*allowBaseTypes*/ function (rootSymbol) {
117321                     return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); }));
117322                 });
117323             }
117324             /**
117325              * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations
117326              * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class
117327              * then we need to widen the search to include type positions as well.
117328              * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated
117329              * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
117330              * do not intersect in any of the three spaces.
117331              */
117332             function getIntersectingMeaningFromDeclarations(node, symbol) {
117333                 var meaning = ts.getMeaningFromLocation(node);
117334                 var declarations = symbol.declarations;
117335                 if (declarations) {
117336                     var lastIterationMeaning = void 0;
117337                     do {
117338                         // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module]
117339                         // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module
117340                         // intersects with the class in the value space.
117341                         // To achieve that we will keep iterating until the result stabilizes.
117342                         // Remember the last meaning
117343                         lastIterationMeaning = meaning;
117344                         for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
117345                             var declaration = declarations_2[_i];
117346                             var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
117347                             if (declarationMeaning & meaning) {
117348                                 meaning |= declarationMeaning;
117349                             }
117350                         }
117351                     } while (meaning !== lastIterationMeaning);
117352                 }
117353                 return meaning;
117354             }
117355             Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
117356             function isImplementation(node) {
117357                 return !!(node.flags & 8388608 /* Ambient */) ? !(ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) :
117358                     (ts.isVariableLike(node) ? ts.hasInitializer(node) :
117359                         ts.isFunctionLikeDeclaration(node) ? !!node.body :
117360                             ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node));
117361             }
117362             function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) {
117363                 var refSymbol = checker.getSymbolAtLocation(node);
117364                 var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
117365                 if (shorthandSymbol) {
117366                     for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) {
117367                         var declaration = _a[_i];
117368                         if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) {
117369                             addReference(declaration);
117370                         }
117371                     }
117372                 }
117373             }
117374             Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment;
117375             function forEachDescendantOfKind(node, kind, action) {
117376                 ts.forEachChild(node, function (child) {
117377                     if (child.kind === kind) {
117378                         action(child);
117379                     }
117380                     forEachDescendantOfKind(child, kind, action);
117381                 });
117382             }
117383             /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */
117384             function tryGetClassByExtendingIdentifier(node) {
117385                 return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent);
117386             }
117387             /**
117388              * If we are just looking for implementations and this is a property access expression, we need to get the
117389              * symbol of the local type of the symbol the property is being accessed on. This is because our search
117390              * symbol may have a different parent symbol if the local type's symbol does not declare the property
117391              * being accessed (i.e. it is declared in some parent class or interface)
117392              */
117393             function getParentSymbolsOfPropertyAccess(location, symbol, checker) {
117394                 var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined;
117395                 var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression);
117396                 var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) {
117397                     return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined;
117398                 });
117399                 return res.length === 0 ? undefined : res;
117400             }
117401             function isForRenameWithPrefixAndSuffixText(options) {
117402                 return options.use === 2 /* Rename */ && options.providePrefixAndSuffixTextForRename;
117403             }
117404         })(Core = FindAllReferences.Core || (FindAllReferences.Core = {}));
117405     })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
117406 })(ts || (ts = {}));
117407 /* @internal */
117408 var ts;
117409 (function (ts) {
117410     var CallHierarchy;
117411     (function (CallHierarchy) {
117412         /** Indictates whether a node is named function or class expression. */
117413         function isNamedExpression(node) {
117414             return (ts.isFunctionExpression(node) || ts.isClassExpression(node)) && ts.isNamedDeclaration(node);
117415         }
117416         /** Indicates whether a node is a function, arrow, or class expression assigned to a constant variable. */
117417         function isConstNamedExpression(node) {
117418             return (ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node))
117419                 && ts.isVariableDeclaration(node.parent)
117420                 && node === node.parent.initializer
117421                 && ts.isIdentifier(node.parent.name)
117422                 && !!(ts.getCombinedNodeFlags(node.parent) & 2 /* Const */);
117423         }
117424         /**
117425          * Indicates whether a node could possibly be a call hierarchy declaration.
117426          *
117427          * See `resolveCallHierarchyDeclaration` for the specific rules.
117428          */
117429         function isPossibleCallHierarchyDeclaration(node) {
117430             return ts.isSourceFile(node)
117431                 || ts.isModuleDeclaration(node)
117432                 || ts.isFunctionDeclaration(node)
117433                 || ts.isFunctionExpression(node)
117434                 || ts.isClassDeclaration(node)
117435                 || ts.isClassExpression(node)
117436                 || ts.isMethodDeclaration(node)
117437                 || ts.isMethodSignature(node)
117438                 || ts.isGetAccessorDeclaration(node)
117439                 || ts.isSetAccessorDeclaration(node);
117440         }
117441         /**
117442          * Indicates whether a node is a valid a call hierarchy declaration.
117443          *
117444          * See `resolveCallHierarchyDeclaration` for the specific rules.
117445          */
117446         function isValidCallHierarchyDeclaration(node) {
117447             return ts.isSourceFile(node)
117448                 || ts.isModuleDeclaration(node) && ts.isIdentifier(node.name)
117449                 || ts.isFunctionDeclaration(node)
117450                 || ts.isClassDeclaration(node)
117451                 || ts.isMethodDeclaration(node)
117452                 || ts.isMethodSignature(node)
117453                 || ts.isGetAccessorDeclaration(node)
117454                 || ts.isSetAccessorDeclaration(node)
117455                 || isNamedExpression(node)
117456                 || isConstNamedExpression(node);
117457         }
117458         /** Gets the node that can be used as a reference to a call hierarchy declaration. */
117459         function getCallHierarchyDeclarationReferenceNode(node) {
117460             if (ts.isSourceFile(node))
117461                 return node;
117462             if (ts.isNamedDeclaration(node))
117463                 return node.name;
117464             if (isConstNamedExpression(node))
117465                 return node.parent.name;
117466             return ts.Debug.checkDefined(node.modifiers && ts.find(node.modifiers, isDefaultModifier));
117467         }
117468         function isDefaultModifier(node) {
117469             return node.kind === 84 /* DefaultKeyword */;
117470         }
117471         /** Gets the symbol for a call hierarchy declaration. */
117472         function getSymbolOfCallHierarchyDeclaration(typeChecker, node) {
117473             var location = getCallHierarchyDeclarationReferenceNode(node);
117474             return location && typeChecker.getSymbolAtLocation(location);
117475         }
117476         /** Gets the text and range for the name of a call hierarchy declaration. */
117477         function getCallHierarchyItemName(program, node) {
117478             if (ts.isSourceFile(node)) {
117479                 return { text: node.fileName, pos: 0, end: 0 };
117480             }
117481             if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) && !ts.isNamedDeclaration(node)) {
117482                 var defaultModifier = node.modifiers && ts.find(node.modifiers, isDefaultModifier);
117483                 if (defaultModifier) {
117484                     return { text: "default", pos: defaultModifier.getStart(), end: defaultModifier.getEnd() };
117485                 }
117486             }
117487             var declName = isConstNamedExpression(node) ? node.parent.name :
117488                 ts.Debug.checkDefined(ts.getNameOfDeclaration(node), "Expected call hierarchy item to have a name");
117489             var text = ts.isIdentifier(declName) ? ts.idText(declName) :
117490                 ts.isStringOrNumericLiteralLike(declName) ? declName.text :
117491                     ts.isComputedPropertyName(declName) ?
117492                         ts.isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text :
117493                             undefined :
117494                         undefined;
117495             if (text === undefined) {
117496                 var typeChecker = program.getTypeChecker();
117497                 var symbol = typeChecker.getSymbolAtLocation(declName);
117498                 if (symbol) {
117499                     text = typeChecker.symbolToString(symbol, node);
117500                 }
117501             }
117502             if (text === undefined) {
117503                 // get the text from printing the node on a single line without comments...
117504                 var printer_1 = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
117505                 text = ts.usingSingleLineStringWriter(function (writer) { return printer_1.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer); });
117506             }
117507             return { text: text, pos: declName.getStart(), end: declName.getEnd() };
117508         }
117509         function findImplementation(typeChecker, node) {
117510             if (node.body) {
117511                 return node;
117512             }
117513             if (ts.isConstructorDeclaration(node)) {
117514                 return ts.getFirstConstructorWithBody(node.parent);
117515             }
117516             if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
117517                 var symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
117518                 if (symbol && symbol.valueDeclaration && ts.isFunctionLikeDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.body) {
117519                     return symbol.valueDeclaration;
117520                 }
117521                 return undefined;
117522             }
117523             return node;
117524         }
117525         function findAllInitialDeclarations(typeChecker, node) {
117526             var symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
117527             var declarations;
117528             if (symbol && symbol.declarations) {
117529                 var indices = ts.indicesOf(symbol.declarations);
117530                 var keys_1 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); });
117531                 indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_1[a].file, keys_1[b].file) || keys_1[a].pos - keys_1[b].pos; });
117532                 var sortedDeclarations = ts.map(indices, function (i) { return symbol.declarations[i]; });
117533                 var lastDecl = void 0;
117534                 for (var _i = 0, sortedDeclarations_1 = sortedDeclarations; _i < sortedDeclarations_1.length; _i++) {
117535                     var decl = sortedDeclarations_1[_i];
117536                     if (isValidCallHierarchyDeclaration(decl)) {
117537                         if (!lastDecl || lastDecl.parent !== decl.parent || lastDecl.end !== decl.pos) {
117538                             declarations = ts.append(declarations, decl);
117539                         }
117540                         lastDecl = decl;
117541                     }
117542                 }
117543             }
117544             return declarations;
117545         }
117546         /** Find the implementation or the first declaration for a call hierarchy declaration. */
117547         function findImplementationOrAllInitialDeclarations(typeChecker, node) {
117548             var _a, _b, _c;
117549             if (ts.isFunctionLikeDeclaration(node)) {
117550                 return (_b = (_a = findImplementation(typeChecker, node)) !== null && _a !== void 0 ? _a : findAllInitialDeclarations(typeChecker, node)) !== null && _b !== void 0 ? _b : node;
117551             }
117552             return (_c = findAllInitialDeclarations(typeChecker, node)) !== null && _c !== void 0 ? _c : node;
117553         }
117554         /** Resolves the call hierarchy declaration for a node. */
117555         function resolveCallHierarchyDeclaration(program, location) {
117556             // A call hierarchy item must refer to either a SourceFile, Module Declaration, or something intrinsically callable that has a name:
117557             // - Class Declarations
117558             // - Class Expressions (with a name)
117559             // - Function Declarations
117560             // - Function Expressions (with a name or assigned to a const variable)
117561             // - Arrow Functions (assigned to a const variable)
117562             // - Constructors
117563             // - Methods
117564             // - Accessors
117565             //
117566             // If a call is contained in a non-named callable Node (function expression, arrow function, etc.), then
117567             // its containing `CallHierarchyItem` is a containing function or SourceFile that matches the above list.
117568             var typeChecker = program.getTypeChecker();
117569             var followingSymbol = false;
117570             while (true) {
117571                 if (isValidCallHierarchyDeclaration(location)) {
117572                     return findImplementationOrAllInitialDeclarations(typeChecker, location);
117573                 }
117574                 if (isPossibleCallHierarchyDeclaration(location)) {
117575                     var ancestor = ts.findAncestor(location, isValidCallHierarchyDeclaration);
117576                     return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
117577                 }
117578                 if (ts.isDeclarationName(location)) {
117579                     if (isValidCallHierarchyDeclaration(location.parent)) {
117580                         return findImplementationOrAllInitialDeclarations(typeChecker, location.parent);
117581                     }
117582                     if (isPossibleCallHierarchyDeclaration(location.parent)) {
117583                         var ancestor = ts.findAncestor(location.parent, isValidCallHierarchyDeclaration);
117584                         return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
117585                     }
117586                     if (ts.isVariableDeclaration(location.parent) && location.parent.initializer && isConstNamedExpression(location.parent.initializer)) {
117587                         return location.parent.initializer;
117588                     }
117589                     return undefined;
117590                 }
117591                 if (ts.isConstructorDeclaration(location)) {
117592                     if (isValidCallHierarchyDeclaration(location.parent)) {
117593                         return location.parent;
117594                     }
117595                     return undefined;
117596                 }
117597                 if (!followingSymbol) {
117598                     var symbol = typeChecker.getSymbolAtLocation(location);
117599                     if (symbol) {
117600                         if (symbol.flags & 2097152 /* Alias */) {
117601                             symbol = typeChecker.getAliasedSymbol(symbol);
117602                         }
117603                         if (symbol.valueDeclaration) {
117604                             followingSymbol = true;
117605                             location = symbol.valueDeclaration;
117606                             continue;
117607                         }
117608                     }
117609                 }
117610                 return undefined;
117611             }
117612         }
117613         CallHierarchy.resolveCallHierarchyDeclaration = resolveCallHierarchyDeclaration;
117614         /** Creates a `CallHierarchyItem` for a call hierarchy declaration. */
117615         function createCallHierarchyItem(program, node) {
117616             var sourceFile = node.getSourceFile();
117617             var name = getCallHierarchyItemName(program, node);
117618             var kind = ts.getNodeKind(node);
117619             var span = ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, node.getFullStart(), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true), node.getEnd());
117620             var selectionSpan = ts.createTextSpanFromBounds(name.pos, name.end);
117621             return { file: sourceFile.fileName, kind: kind, name: name.text, span: span, selectionSpan: selectionSpan };
117622         }
117623         CallHierarchy.createCallHierarchyItem = createCallHierarchyItem;
117624         function isDefined(x) {
117625             return x !== undefined;
117626         }
117627         function convertEntryToCallSite(entry) {
117628             if (entry.kind === 1 /* Node */) {
117629                 var node = entry.node;
117630                 if (ts.isCallOrNewExpressionTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
117631                     || ts.isTaggedTemplateTag(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
117632                     || ts.isDecoratorTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
117633                     || ts.isJsxOpeningLikeElementTagName(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
117634                     || ts.isRightSideOfPropertyAccess(node)
117635                     || ts.isArgumentExpressionOfElementAccess(node)) {
117636                     var sourceFile = node.getSourceFile();
117637                     var ancestor = ts.findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile;
117638                     return { declaration: ancestor, range: ts.createTextRangeFromNode(node, sourceFile) };
117639                 }
117640             }
117641         }
117642         function getCallSiteGroupKey(entry) {
117643             return "" + ts.getNodeId(entry.declaration);
117644         }
117645         function createCallHierarchyIncomingCall(from, fromSpans) {
117646             return { from: from, fromSpans: fromSpans };
117647         }
117648         function convertCallSiteGroupToIncomingCall(program, entries) {
117649             return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), ts.map(entries, function (entry) { return ts.createTextSpanFromRange(entry.range); }));
117650         }
117651         /** Gets the call sites that call into the provided call hierarchy declaration. */
117652         function getIncomingCalls(program, declaration, cancellationToken) {
117653             // Source files and modules have no incoming calls.
117654             if (ts.isSourceFile(declaration) || ts.isModuleDeclaration(declaration)) {
117655                 return [];
117656             }
117657             var location = getCallHierarchyDeclarationReferenceNode(declaration);
117658             var calls = ts.filter(ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, program.getSourceFiles(), location, /*position*/ 0, { use: 1 /* References */ }, convertEntryToCallSite), isDefined);
117659             return calls ? ts.group(calls, getCallSiteGroupKey, function (entries) { return convertCallSiteGroupToIncomingCall(program, entries); }) : [];
117660         }
117661         CallHierarchy.getIncomingCalls = getIncomingCalls;
117662         function createCallSiteCollector(program, callSites) {
117663             function recordCallSite(node) {
117664                 var target = ts.isTaggedTemplateExpression(node) ? node.tag :
117665                     ts.isJsxOpeningLikeElement(node) ? node.tagName :
117666                         ts.isAccessExpression(node) ? node :
117667                             node.expression;
117668                 var declaration = resolveCallHierarchyDeclaration(program, target);
117669                 if (declaration) {
117670                     var range = ts.createTextRangeFromNode(target, node.getSourceFile());
117671                     if (ts.isArray(declaration)) {
117672                         for (var _i = 0, declaration_1 = declaration; _i < declaration_1.length; _i++) {
117673                             var decl = declaration_1[_i];
117674                             callSites.push({ declaration: decl, range: range });
117675                         }
117676                     }
117677                     else {
117678                         callSites.push({ declaration: declaration, range: range });
117679                     }
117680                 }
117681             }
117682             function collect(node) {
117683                 if (!node)
117684                     return;
117685                 if (node.flags & 8388608 /* Ambient */) {
117686                     // do not descend into ambient nodes.
117687                     return;
117688                 }
117689                 if (isValidCallHierarchyDeclaration(node)) {
117690                     // do not descend into other call site declarations, other than class member names
117691                     if (ts.isClassLike(node)) {
117692                         for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
117693                             var member = _a[_i];
117694                             if (member.name && ts.isComputedPropertyName(member.name)) {
117695                                 collect(member.name.expression);
117696                             }
117697                         }
117698                     }
117699                     return;
117700                 }
117701                 switch (node.kind) {
117702                     case 75 /* Identifier */:
117703                     case 253 /* ImportEqualsDeclaration */:
117704                     case 254 /* ImportDeclaration */:
117705                     case 260 /* ExportDeclaration */:
117706                     case 246 /* InterfaceDeclaration */:
117707                     case 247 /* TypeAliasDeclaration */:
117708                         // do not descend into nodes that cannot contain callable nodes
117709                         return;
117710                     case 199 /* TypeAssertionExpression */:
117711                     case 217 /* AsExpression */:
117712                         // do not descend into the type side of an assertion
117713                         collect(node.expression);
117714                         return;
117715                     case 242 /* VariableDeclaration */:
117716                     case 156 /* Parameter */:
117717                         // do not descend into the type of a variable or parameter declaration
117718                         collect(node.name);
117719                         collect(node.initializer);
117720                         return;
117721                     case 196 /* CallExpression */:
117722                         // do not descend into the type arguments of a call expression
117723                         recordCallSite(node);
117724                         collect(node.expression);
117725                         ts.forEach(node.arguments, collect);
117726                         return;
117727                     case 197 /* NewExpression */:
117728                         // do not descend into the type arguments of a new expression
117729                         recordCallSite(node);
117730                         collect(node.expression);
117731                         ts.forEach(node.arguments, collect);
117732                         return;
117733                     case 198 /* TaggedTemplateExpression */:
117734                         // do not descend into the type arguments of a tagged template expression
117735                         recordCallSite(node);
117736                         collect(node.tag);
117737                         collect(node.template);
117738                         return;
117739                     case 268 /* JsxOpeningElement */:
117740                     case 267 /* JsxSelfClosingElement */:
117741                         // do not descend into the type arguments of a JsxOpeningLikeElement
117742                         recordCallSite(node);
117743                         collect(node.tagName);
117744                         collect(node.attributes);
117745                         return;
117746                     case 157 /* Decorator */:
117747                         recordCallSite(node);
117748                         collect(node.expression);
117749                         return;
117750                     case 194 /* PropertyAccessExpression */:
117751                     case 195 /* ElementAccessExpression */:
117752                         recordCallSite(node);
117753                         ts.forEachChild(node, collect);
117754                         break;
117755                 }
117756                 if (ts.isPartOfTypeNode(node)) {
117757                     // do not descend into types
117758                     return;
117759                 }
117760                 ts.forEachChild(node, collect);
117761             }
117762             return collect;
117763         }
117764         function collectCallSitesOfSourceFile(node, collect) {
117765             ts.forEach(node.statements, collect);
117766         }
117767         function collectCallSitesOfModuleDeclaration(node, collect) {
117768             if (!ts.hasModifier(node, 2 /* Ambient */) && node.body && ts.isModuleBlock(node.body)) {
117769                 ts.forEach(node.body.statements, collect);
117770             }
117771         }
117772         function collectCallSitesOfFunctionLikeDeclaration(typeChecker, node, collect) {
117773             var implementation = findImplementation(typeChecker, node);
117774             if (implementation) {
117775                 ts.forEach(implementation.parameters, collect);
117776                 collect(implementation.body);
117777             }
117778         }
117779         function collectCallSitesOfClassLikeDeclaration(node, collect) {
117780             ts.forEach(node.decorators, collect);
117781             var heritage = ts.getClassExtendsHeritageElement(node);
117782             if (heritage) {
117783                 collect(heritage.expression);
117784             }
117785             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
117786                 var member = _a[_i];
117787                 ts.forEach(member.decorators, collect);
117788                 if (ts.isPropertyDeclaration(member)) {
117789                     collect(member.initializer);
117790                 }
117791                 else if (ts.isConstructorDeclaration(member) && member.body) {
117792                     ts.forEach(member.parameters, collect);
117793                     collect(member.body);
117794                 }
117795             }
117796         }
117797         function collectCallSites(program, node) {
117798             var callSites = [];
117799             var collect = createCallSiteCollector(program, callSites);
117800             switch (node.kind) {
117801                 case 290 /* SourceFile */:
117802                     collectCallSitesOfSourceFile(node, collect);
117803                     break;
117804                 case 249 /* ModuleDeclaration */:
117805                     collectCallSitesOfModuleDeclaration(node, collect);
117806                     break;
117807                 case 244 /* FunctionDeclaration */:
117808                 case 201 /* FunctionExpression */:
117809                 case 202 /* ArrowFunction */:
117810                 case 161 /* MethodDeclaration */:
117811                 case 163 /* GetAccessor */:
117812                 case 164 /* SetAccessor */:
117813                     collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect);
117814                     break;
117815                 case 245 /* ClassDeclaration */:
117816                 case 214 /* ClassExpression */:
117817                     collectCallSitesOfClassLikeDeclaration(node, collect);
117818                     break;
117819                 default:
117820                     ts.Debug.assertNever(node);
117821             }
117822             return callSites;
117823         }
117824         function createCallHierarchyOutgoingCall(to, fromSpans) {
117825             return { to: to, fromSpans: fromSpans };
117826         }
117827         function convertCallSiteGroupToOutgoingCall(program, entries) {
117828             return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), ts.map(entries, function (entry) { return ts.createTextSpanFromRange(entry.range); }));
117829         }
117830         /** Gets the call sites that call out of the provided call hierarchy declaration. */
117831         function getOutgoingCalls(program, declaration) {
117832             if (declaration.flags & 8388608 /* Ambient */ || ts.isMethodSignature(declaration)) {
117833                 return [];
117834             }
117835             return ts.group(collectCallSites(program, declaration), getCallSiteGroupKey, function (entries) { return convertCallSiteGroupToOutgoingCall(program, entries); });
117836         }
117837         CallHierarchy.getOutgoingCalls = getOutgoingCalls;
117838     })(CallHierarchy = ts.CallHierarchy || (ts.CallHierarchy = {}));
117839 })(ts || (ts = {}));
117840 /* @internal */
117841 var ts;
117842 (function (ts) {
117843     function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) {
117844         var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
117845         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
117846         var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper);
117847         var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper);
117848         return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, function (changeTracker) {
117849             updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames);
117850             updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName);
117851         });
117852     }
117853     ts.getEditsForFileRename = getEditsForFileRename;
117854     // exported for tests
117855     function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) {
117856         var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath);
117857         return function (path) {
117858             var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 });
117859             var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path);
117860             return originalPath
117861                 ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName)
117862                 : updatedPath;
117863         };
117864         function getUpdatedPath(pathToUpdate) {
117865             if (getCanonicalFileName(pathToUpdate) === canonicalOldPath)
117866                 return newFileOrDirPath;
117867             var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName);
117868             return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix;
117869         }
117870     }
117871     ts.getPathUpdater = getPathUpdater;
117872     // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1.
117873     function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) {
117874         var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName);
117875         return combinePathsSafe(ts.getDirectoryPath(a1), rel);
117876     }
117877     function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) {
117878         var configFile = program.getCompilerOptions().configFile;
117879         if (!configFile)
117880             return;
117881         var configDir = ts.getDirectoryPath(configFile.fileName);
117882         var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile);
117883         if (!jsonObjectLiteral)
117884             return;
117885         forEachProperty(jsonObjectLiteral, function (property, propertyName) {
117886             switch (propertyName) {
117887                 case "files":
117888                 case "include":
117889                 case "exclude": {
117890                     var foundExactMatch = updatePaths(property);
117891                     if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) {
117892                         var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; });
117893                         var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory);
117894                         // If there isn't some include for this, add a new one.
117895                         if (ts.getRegexFromPattern(ts.Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) &&
117896                             !ts.getRegexFromPattern(ts.Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) {
117897                             changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath)));
117898                         }
117899                     }
117900                     break;
117901                 }
117902                 case "compilerOptions":
117903                     forEachProperty(property.initializer, function (property, propertyName) {
117904                         var option = ts.getOptionFromName(propertyName);
117905                         if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) {
117906                             updatePaths(property);
117907                         }
117908                         else if (propertyName === "paths") {
117909                             forEachProperty(property.initializer, function (pathsProperty) {
117910                                 if (!ts.isArrayLiteralExpression(pathsProperty.initializer))
117911                                     return;
117912                                 for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) {
117913                                     var e = _a[_i];
117914                                     tryUpdateString(e);
117915                                 }
117916                             });
117917                         }
117918                     });
117919                     break;
117920             }
117921         });
117922         function updatePaths(property) {
117923             // Type annotation needed due to #7294
117924             var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
117925             var foundExactMatch = false;
117926             for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
117927                 var element = elements_1[_i];
117928                 foundExactMatch = tryUpdateString(element) || foundExactMatch;
117929             }
117930             return foundExactMatch;
117931         }
117932         function tryUpdateString(element) {
117933             if (!ts.isStringLiteral(element))
117934                 return false;
117935             var elementFileName = combinePathsSafe(configDir, element.text);
117936             var updated = oldToNew(elementFileName);
117937             if (updated !== undefined) {
117938                 changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated));
117939                 return true;
117940             }
117941             return false;
117942         }
117943         function relativePath(path) {
117944             return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames);
117945         }
117946     }
117947     function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
117948         var allFiles = program.getSourceFiles();
117949         var _loop_4 = function (sourceFile) {
117950             var newFromOld = oldToNew(sourceFile.path);
117951             var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
117952             var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
117953             var oldFromNew = newToOld(sourceFile.fileName);
117954             var oldImportFromPath = oldFromNew || sourceFile.fileName;
117955             var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath);
117956             var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined;
117957             updateImportsWorker(sourceFile, changeTracker, function (referenceText) {
117958                 if (!ts.pathIsRelative(referenceText))
117959                     return undefined;
117960                 var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText);
117961                 var newAbsolute = oldToNew(oldAbsolute);
117962                 return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName));
117963             }, function (importLiteral) {
117964                 var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
117965                 // No need to update if it's an ambient module^M
117966                 if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); }))
117967                     return undefined;
117968                 var toImport = oldFromNew !== undefined
117969                     // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location.
117970                     // TODO:GH#18217
117971                     ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, allFiles)
117972                     : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
117973                 // Need an update if the imported file moved, or the importing file moved and was using a relative path.
117974                 return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text)))
117975                     ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, ts.createModuleSpecifierResolutionHost(program, host), importLiteral.text)
117976                     : undefined;
117977             });
117978         };
117979         for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
117980             var sourceFile = allFiles_1[_i];
117981             _loop_4(sourceFile);
117982         }
117983     }
117984     function combineNormal(pathA, pathB) {
117985         return ts.normalizePath(ts.combinePaths(pathA, pathB));
117986     }
117987     function combinePathsSafe(pathA, pathB) {
117988         return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB));
117989     }
117990     function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) {
117991         if (importedModuleSymbol) {
117992             // `find` should succeed because we checked for ambient modules before calling this function.
117993             var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName;
117994             var newFileName = oldToNew(oldFileName);
117995             return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true };
117996         }
117997         else {
117998             var resolved = host.resolveModuleNames
117999                 ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName)
118000                 : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName);
118001             return getSourceFileToImportFromResolved(resolved, oldToNew, program.getSourceFiles());
118002         }
118003     }
118004     function getSourceFileToImportFromResolved(resolved, oldToNew, sourceFiles) {
118005         // Search through all locations looking for a moved file, and only then test already existing files.
118006         // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location.
118007         if (!resolved)
118008             return undefined;
118009         // First try resolved module
118010         if (resolved.resolvedModule) {
118011             var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
118012             if (result_2)
118013                 return result_2;
118014         }
118015         // Then failed lookups that are in the list of sources
118016         var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJsonExisting)
118017             // Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
118018             || ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
118019         if (result)
118020             return result;
118021         // If nothing changed, then result is resolved module file thats not updated
118022         return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false };
118023         function tryChangeWithIgnoringPackageJsonExisting(oldFileName) {
118024             var newFileName = oldToNew(oldFileName);
118025             return newFileName && ts.find(sourceFiles, function (src) { return src.fileName === newFileName; })
118026                 ? tryChangeWithIgnoringPackageJson(oldFileName) : undefined;
118027         }
118028         function tryChangeWithIgnoringPackageJson(oldFileName) {
118029             return !ts.endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined;
118030         }
118031         function tryChange(oldFileName) {
118032             var newFileName = oldToNew(oldFileName);
118033             return newFileName && { newFileName: newFileName, updated: true };
118034         }
118035     }
118036     function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) {
118037         for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162
118038             var ref = _a[_i];
118039             var updated = updateRef(ref.fileName);
118040             if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end))
118041                 changeTracker.replaceRangeWithText(sourceFile, ref, updated);
118042         }
118043         for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) {
118044             var importStringLiteral = _c[_b];
118045             var updated = updateImport(importStringLiteral);
118046             if (updated !== undefined && updated !== importStringLiteral.text)
118047                 changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated);
118048         }
118049     }
118050     function createStringRange(node, sourceFile) {
118051         return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1);
118052     }
118053     function forEachProperty(objectLiteral, cb) {
118054         if (!ts.isObjectLiteralExpression(objectLiteral))
118055             return;
118056         for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) {
118057             var property = _a[_i];
118058             if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) {
118059                 cb(property, property.name.text);
118060             }
118061         }
118062     }
118063 })(ts || (ts = {}));
118064 /* @internal */
118065 var ts;
118066 (function (ts) {
118067     var GoToDefinition;
118068     (function (GoToDefinition) {
118069         function getDefinitionAtPosition(program, sourceFile, position) {
118070             var reference = getReferenceAtPosition(sourceFile, position, program);
118071             if (reference) {
118072                 return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)];
118073             }
118074             var node = ts.getTouchingPropertyName(sourceFile, position);
118075             if (node === sourceFile) {
118076                 return undefined;
118077             }
118078             var parent = node.parent;
118079             var typeChecker = program.getTypeChecker();
118080             // Labels
118081             if (ts.isJumpStatementTarget(node)) {
118082                 var label = ts.getTargetLabel(node.parent, node.text);
118083                 return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217
118084             }
118085             var symbol = getSymbol(node, typeChecker);
118086             // Could not find a symbol e.g. node is string or number keyword,
118087             // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol
118088             if (!symbol) {
118089                 return getDefinitionInfoForIndexSignatures(node, typeChecker);
118090             }
118091             var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
118092             // Don't go to the component constructor definition for a JSX element, just go to the component definition.
118093             if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) {
118094                 var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
118095                 // For a function, if this is the original function definition, return just sigInfo.
118096                 // If this is the original constructor definition, parent is the class.
118097                 if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) ||
118098                     // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias
118099                     symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) {
118100                     return [sigInfo];
118101                 }
118102                 else {
118103                     var defs = getDefinitionFromSymbol(typeChecker, symbol, node, calledDeclaration) || ts.emptyArray;
118104                     // For a 'super()' call, put the signature first, else put the variable first.
118105                     return node.kind === 102 /* SuperKeyword */ ? __spreadArrays([sigInfo], defs) : __spreadArrays(defs, [sigInfo]);
118106                 }
118107             }
118108             // Because name in short-hand property assignment has two different meanings: property name and property value,
118109             // using go-to-definition at such position should go to the variable declaration of the property value rather than
118110             // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition
118111             // is performed at the location of property access, we would like to go to definition of the property in the short-hand
118112             // assignment. This case and others are handled by the following code.
118113             if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
118114                 var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
118115                 return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : [];
118116             }
118117             // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the
118118             // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern
118119             // and return the property declaration for the referenced property.
118120             // For example:
118121             //      import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo"
118122             //
118123             //      function bar<T>(onfulfilled: (value: T) => void) { //....}
118124             //      interface Test {
118125             //          pr/*destination*/op1: number
118126             //      }
118127             //      bar<Test>(({pr/*goto*/op1})=>{});
118128             if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
118129                 (node === (parent.propertyName || parent.name))) {
118130                 var name_3 = ts.getNameFromPropertyName(node);
118131                 var type = typeChecker.getTypeAtLocation(parent.parent);
118132                 return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
118133                     var prop = t.getProperty(name_3);
118134                     return prop && getDefinitionFromSymbol(typeChecker, prop, node);
118135                 });
118136             }
118137             // If the current location we want to find its definition is in an object literal, try to get the contextual type for the
118138             // object literal, lookup the property symbol in the contextual type, and use this for goto-definition.
118139             // For example
118140             //      interface Props{
118141             //          /*first*/prop1: number
118142             //          prop2: boolean
118143             //      }
118144             //      function Foo(arg: Props) {}
118145             //      Foo( { pr/*1*/op1: 10, prop2: true })
118146             var element = ts.getContainingObjectLiteralElement(node);
118147             if (element) {
118148                 var contextualType = element && typeChecker.getContextualType(element.parent);
118149                 if (contextualType) {
118150                     return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) {
118151                         return getDefinitionFromSymbol(typeChecker, propertySymbol, node);
118152                     });
118153                 }
118154             }
118155             return getDefinitionFromSymbol(typeChecker, symbol, node);
118156         }
118157         GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition;
118158         /**
118159          * True if we should not add definitions for both the signature symbol and the definition symbol.
118160          * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`.
118161          */
118162         function symbolMatchesSignature(s, calledDeclaration) {
118163             return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent ||
118164                 !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol;
118165         }
118166         function getReferenceAtPosition(sourceFile, position, program) {
118167             var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
118168             if (referencePath) {
118169                 var file = program.getSourceFileFromReference(sourceFile, referencePath);
118170                 return file && { fileName: referencePath.fileName, file: file };
118171             }
118172             var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
118173             if (typeReferenceDirective) {
118174                 var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
118175                 var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217
118176                 return file && { fileName: typeReferenceDirective.fileName, file: file };
118177             }
118178             var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position);
118179             if (libReferenceDirective) {
118180                 var file = program.getLibFileFromReference(libReferenceDirective);
118181                 return file && { fileName: libReferenceDirective.fileName, file: file };
118182             }
118183             return undefined;
118184         }
118185         GoToDefinition.getReferenceAtPosition = getReferenceAtPosition;
118186         /// Goto type
118187         function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) {
118188             var node = ts.getTouchingPropertyName(sourceFile, position);
118189             if (node === sourceFile) {
118190                 return undefined;
118191             }
118192             var symbol = typeChecker.getSymbolAtLocation(node);
118193             if (!symbol)
118194                 return undefined;
118195             var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
118196             var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker);
118197             var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node);
118198             // If a function returns 'void' or some other type with no definition, just return the function definition.
118199             return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node);
118200         }
118201         GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition;
118202         function definitionFromType(type, checker, node) {
118203             return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) {
118204                 return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node);
118205             });
118206         }
118207         function tryGetReturnTypeOfFunction(symbol, type, checker) {
118208             // If the type is just a function's inferred type,
118209             // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway.
118210             if (type.symbol === symbol ||
118211                 // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}`
118212                 symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) {
118213                 var sigs = type.getCallSignatures();
118214                 if (sigs.length === 1)
118215                     return checker.getReturnTypeOfSignature(ts.first(sigs));
118216             }
118217             return undefined;
118218         }
118219         function getDefinitionAndBoundSpan(program, sourceFile, position) {
118220             var definitions = getDefinitionAtPosition(program, sourceFile, position);
118221             if (!definitions || definitions.length === 0) {
118222                 return undefined;
118223             }
118224             // Check if position is on triple slash reference.
118225             var comment = findReferenceInPosition(sourceFile.referencedFiles, position) ||
118226                 findReferenceInPosition(sourceFile.typeReferenceDirectives, position) ||
118227                 findReferenceInPosition(sourceFile.libReferenceDirectives, position);
118228             if (comment) {
118229                 return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) };
118230             }
118231             var node = ts.getTouchingPropertyName(sourceFile, position);
118232             var textSpan = ts.createTextSpan(node.getStart(), node.getWidth());
118233             return { definitions: definitions, textSpan: textSpan };
118234         }
118235         GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan;
118236         // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations.
118237         function getDefinitionInfoForIndexSignatures(node, checker) {
118238             if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node)
118239                 return;
118240             var type = checker.getTypeAtLocation(node.parent.expression);
118241             return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) {
118242                 var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */);
118243                 return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration);
118244             });
118245         }
118246         function getSymbol(node, checker) {
118247             var symbol = checker.getSymbolAtLocation(node);
118248             // If this is an alias, and the request came at the declaration location
118249             // get the aliased symbol instead. This allows for goto def on an import e.g.
118250             //   import {A, B} from "mod";
118251             // to jump to the implementation directly.
118252             if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) {
118253                 var aliased = checker.getAliasedSymbol(symbol);
118254                 if (aliased.declarations) {
118255                     return aliased;
118256                 }
118257             }
118258             if (symbol && ts.isInJSFile(node)) {
118259                 var requireCall = ts.forEach(symbol.declarations, function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true) ? d.initializer : undefined; });
118260                 if (requireCall) {
118261                     var moduleSymbol = checker.getSymbolAtLocation(requireCall.arguments[0]);
118262                     if (moduleSymbol) {
118263                         return checker.resolveExternalModuleSymbol(moduleSymbol);
118264                     }
118265                 }
118266             }
118267             return symbol;
118268         }
118269         // Go to the original declaration for cases:
118270         //
118271         //   (1) when the aliased symbol was declared in the location(parent).
118272         //   (2) when the aliased symbol is originating from an import.
118273         //
118274         function shouldSkipAlias(node, declaration) {
118275             if (node.kind !== 75 /* Identifier */) {
118276                 return false;
118277             }
118278             if (node.parent === declaration) {
118279                 return true;
118280             }
118281             switch (declaration.kind) {
118282                 case 255 /* ImportClause */:
118283                 case 253 /* ImportEqualsDeclaration */:
118284                     return true;
118285                 case 258 /* ImportSpecifier */:
118286                     return declaration.parent.kind === 257 /* NamedImports */;
118287                 default:
118288                     return false;
118289             }
118290         }
118291         function getDefinitionFromSymbol(typeChecker, symbol, node, declarationNode) {
118292             // There are cases when you extend a function by adding properties to it afterwards,
118293             // we want to strip those extra properties.
118294             // For deduping purposes, we also want to exclude any declarationNodes if provided.
118295             var filteredDeclarations = ts.filter(symbol.declarations, function (d) { return d !== declarationNode && (!ts.isAssignmentDeclaration(d) || d === symbol.valueDeclaration); }) || undefined;
118296             return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(filteredDeclarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); });
118297             function getConstructSignatureDefinition() {
118298                 // Applicable only if we are in a new expression, or we are on a constructor declaration
118299                 // and in either case the symbol has a construct signature definition, i.e. class
118300                 if (symbol.flags & 32 /* Class */ && !(symbol.flags & (16 /* Function */ | 3 /* Variable */)) && (ts.isNewExpressionTarget(node) || node.kind === 129 /* ConstructorKeyword */)) {
118301                     var cls = ts.find(filteredDeclarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration");
118302                     return getSignatureDefinition(cls.members, /*selectConstructors*/ true);
118303                 }
118304             }
118305             function getCallSignatureDefinition() {
118306                 return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node)
118307                     ? getSignatureDefinition(filteredDeclarations, /*selectConstructors*/ false)
118308                     : undefined;
118309             }
118310             function getSignatureDefinition(signatureDeclarations, selectConstructors) {
118311                 if (!signatureDeclarations) {
118312                     return undefined;
118313                 }
118314                 var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike);
118315                 var declarationsWithBody = declarations.filter(function (d) { return !!d.body; });
118316                 // declarations defined on the global scope can be defined on multiple files. Get all of them.
118317                 return declarations.length
118318                     ? declarationsWithBody.length !== 0
118319                         ? declarationsWithBody.map(function (x) { return createDefinitionInfo(x, typeChecker, symbol, node); })
118320                         : [createDefinitionInfo(ts.last(declarations), typeChecker, symbol, node)]
118321                     : undefined;
118322             }
118323         }
118324         /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */
118325         function createDefinitionInfo(declaration, checker, symbol, node) {
118326             var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
118327             var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node);
118328             var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : "";
118329             return createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName, containerName);
118330         }
118331         /** Creates a DefinitionInfo directly from the name of a declaration. */
118332         function createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName, containerName) {
118333             var name = ts.getNameOfDeclaration(declaration) || declaration;
118334             var sourceFile = name.getSourceFile();
118335             var textSpan = ts.createTextSpanFromNode(name, sourceFile);
118336             return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217
118337                 containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) });
118338         }
118339         function createDefinitionFromSignatureDeclaration(typeChecker, decl) {
118340             return createDefinitionInfo(decl, typeChecker, decl.symbol, decl);
118341         }
118342         function findReferenceInPosition(refs, pos) {
118343             return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); });
118344         }
118345         GoToDefinition.findReferenceInPosition = findReferenceInPosition;
118346         function getDefinitionInfoForFileReference(name, targetFileName) {
118347             return {
118348                 fileName: targetFileName,
118349                 textSpan: ts.createTextSpanFromBounds(0, 0),
118350                 kind: "script" /* scriptElement */,
118351                 name: name,
118352                 containerName: undefined,
118353                 containerKind: undefined,
118354             };
118355         }
118356         /** Returns a CallLikeExpression where `node` is the target being invoked. */
118357         function getAncestorCallLikeExpression(node) {
118358             var target = climbPastManyPropertyAccesses(node);
118359             var callLike = target.parent;
118360             return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined;
118361         }
118362         function climbPastManyPropertyAccesses(node) {
118363             return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node;
118364         }
118365         function tryGetSignatureDeclaration(typeChecker, node) {
118366             var callLike = getAncestorCallLikeExpression(node);
118367             var signature = callLike && typeChecker.getResolvedSignature(callLike);
118368             // Don't go to a function type, go to the value having that type.
118369             return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); });
118370         }
118371         function isConstructorLike(node) {
118372             switch (node.kind) {
118373                 case 162 /* Constructor */:
118374                 case 171 /* ConstructorType */:
118375                 case 166 /* ConstructSignature */:
118376                     return true;
118377                 default:
118378                     return false;
118379             }
118380         }
118381     })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {}));
118382 })(ts || (ts = {}));
118383 /* @internal */
118384 var ts;
118385 (function (ts) {
118386     var JsDoc;
118387     (function (JsDoc) {
118388         var jsDocTagNames = [
118389             "abstract",
118390             "access",
118391             "alias",
118392             "argument",
118393             "async",
118394             "augments",
118395             "author",
118396             "borrows",
118397             "callback",
118398             "class",
118399             "classdesc",
118400             "constant",
118401             "constructor",
118402             "constructs",
118403             "copyright",
118404             "default",
118405             "deprecated",
118406             "description",
118407             "emits",
118408             "enum",
118409             "event",
118410             "example",
118411             "exports",
118412             "extends",
118413             "external",
118414             "field",
118415             "file",
118416             "fileoverview",
118417             "fires",
118418             "function",
118419             "generator",
118420             "global",
118421             "hideconstructor",
118422             "host",
118423             "ignore",
118424             "implements",
118425             "inheritdoc",
118426             "inner",
118427             "instance",
118428             "interface",
118429             "kind",
118430             "lends",
118431             "license",
118432             "listens",
118433             "member",
118434             "memberof",
118435             "method",
118436             "mixes",
118437             "module",
118438             "name",
118439             "namespace",
118440             "override",
118441             "package",
118442             "param",
118443             "private",
118444             "property",
118445             "protected",
118446             "public",
118447             "readonly",
118448             "requires",
118449             "returns",
118450             "see",
118451             "since",
118452             "static",
118453             "summary",
118454             "template",
118455             "this",
118456             "throws",
118457             "todo",
118458             "tutorial",
118459             "type",
118460             "typedef",
118461             "var",
118462             "variation",
118463             "version",
118464             "virtual",
118465             "yields"
118466         ];
118467         var jsDocTagNameCompletionEntries;
118468         var jsDocTagCompletionEntries;
118469         function getJsDocCommentsFromDeclarations(declarations) {
118470             // Only collect doc comments from duplicate declarations once:
118471             // In case of a union property there might be same declaration multiple times
118472             // which only varies in type parameter
118473             // Eg. const a: Array<string> | Array<number>; a.length
118474             // The property length will have two declarations of property length coming
118475             // from Array<T> - Array<string> and Array<number>
118476             var documentationComment = [];
118477             ts.forEachUnique(declarations, function (declaration) {
118478                 for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) {
118479                     var comment = _a[_i].comment;
118480                     if (comment === undefined)
118481                         continue;
118482                     if (documentationComment.length) {
118483                         documentationComment.push(ts.lineBreakPart());
118484                     }
118485                     documentationComment.push(ts.textPart(comment));
118486                 }
118487             });
118488             return documentationComment;
118489         }
118490         JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
118491         function getCommentHavingNodes(declaration) {
118492             switch (declaration.kind) {
118493                 case 317 /* JSDocParameterTag */:
118494                 case 323 /* JSDocPropertyTag */:
118495                     return [declaration];
118496                 case 315 /* JSDocCallbackTag */:
118497                 case 322 /* JSDocTypedefTag */:
118498                     return [declaration, declaration.parent];
118499                 default:
118500                     return ts.getJSDocCommentsAndTags(declaration);
118501             }
118502         }
118503         function getJsDocTagsFromDeclarations(declarations) {
118504             // Only collect doc comments from duplicate declarations once.
118505             var tags = [];
118506             ts.forEachUnique(declarations, function (declaration) {
118507                 for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) {
118508                     var tag = _a[_i];
118509                     tags.push({ name: tag.tagName.text, text: getCommentText(tag) });
118510                 }
118511             });
118512             return tags;
118513         }
118514         JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations;
118515         function getCommentText(tag) {
118516             var comment = tag.comment;
118517             switch (tag.kind) {
118518                 case 308 /* JSDocImplementsTag */:
118519                     return withNode(tag.class);
118520                 case 307 /* JSDocAugmentsTag */:
118521                     return withNode(tag.class);
118522                 case 321 /* JSDocTemplateTag */:
118523                     return withList(tag.typeParameters);
118524                 case 320 /* JSDocTypeTag */:
118525                     return withNode(tag.typeExpression);
118526                 case 322 /* JSDocTypedefTag */:
118527                 case 315 /* JSDocCallbackTag */:
118528                 case 323 /* JSDocPropertyTag */:
118529                 case 317 /* JSDocParameterTag */:
118530                     var name = tag.name;
118531                     return name ? withNode(name) : comment;
118532                 default:
118533                     return comment;
118534             }
118535             function withNode(node) {
118536                 return addComment(node.getText());
118537             }
118538             function withList(list) {
118539                 return addComment(list.map(function (x) { return x.getText(); }).join(", "));
118540             }
118541             function addComment(s) {
118542                 return comment === undefined ? s : s + " " + comment;
118543             }
118544         }
118545         function getJSDocTagNameCompletions() {
118546             return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
118547                 return {
118548                     name: tagName,
118549                     kind: "keyword" /* keyword */,
118550                     kindModifiers: "",
118551                     sortText: "0",
118552                 };
118553             }));
118554         }
118555         JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions;
118556         JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails;
118557         function getJSDocTagCompletions() {
118558             return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
118559                 return {
118560                     name: "@" + tagName,
118561                     kind: "keyword" /* keyword */,
118562                     kindModifiers: "",
118563                     sortText: "0"
118564                 };
118565             }));
118566         }
118567         JsDoc.getJSDocTagCompletions = getJSDocTagCompletions;
118568         function getJSDocTagCompletionDetails(name) {
118569             return {
118570                 name: name,
118571                 kind: "" /* unknown */,
118572                 kindModifiers: "",
118573                 displayParts: [ts.textPart(name)],
118574                 documentation: ts.emptyArray,
118575                 tags: undefined,
118576                 codeActions: undefined,
118577             };
118578         }
118579         JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails;
118580         function getJSDocParameterNameCompletions(tag) {
118581             if (!ts.isIdentifier(tag.name)) {
118582                 return ts.emptyArray;
118583             }
118584             var nameThusFar = tag.name.text;
118585             var jsdoc = tag.parent;
118586             var fn = jsdoc.parent;
118587             if (!ts.isFunctionLike(fn))
118588                 return [];
118589             return ts.mapDefined(fn.parameters, function (param) {
118590                 if (!ts.isIdentifier(param.name))
118591                     return undefined;
118592                 var name = param.name.text;
118593                 if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217
118594                     || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) {
118595                     return undefined;
118596                 }
118597                 return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" };
118598             });
118599         }
118600         JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions;
118601         function getJSDocParameterNameCompletionDetails(name) {
118602             return {
118603                 name: name,
118604                 kind: "parameter" /* parameterElement */,
118605                 kindModifiers: "",
118606                 displayParts: [ts.textPart(name)],
118607                 documentation: ts.emptyArray,
118608                 tags: undefined,
118609                 codeActions: undefined,
118610             };
118611         }
118612         JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails;
118613         /**
118614          * Checks if position points to a valid position to add JSDoc comments, and if so,
118615          * returns the appropriate template. Otherwise returns an empty string.
118616          * Valid positions are
118617          *      - outside of comments, statements, and expressions, and
118618          *      - preceding a:
118619          *          - function/constructor/method declaration
118620          *          - class declarations
118621          *          - variable statements
118622          *          - namespace declarations
118623          *          - interface declarations
118624          *          - method signatures
118625          *          - type alias declarations
118626          *
118627          * Hosts should ideally check that:
118628          * - The line is all whitespace up to 'position' before performing the insertion.
118629          * - If the keystroke sequence "/\*\*" induced the call, we also check that the next
118630          * non-whitespace character is '*', which (approximately) indicates whether we added
118631          * the second '*' to complete an existing (JSDoc) comment.
118632          * @param fileName The file in which to perform the check.
118633          * @param position The (character-indexed) position in the file where the check should
118634          * be performed.
118635          */
118636         function getDocCommentTemplateAtPosition(newLine, sourceFile, position) {
118637             var tokenAtPos = ts.getTokenAtPosition(sourceFile, position);
118638             var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc);
118639             if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) {
118640                 // Non-empty comment already exists.
118641                 return undefined;
118642             }
118643             var tokenStart = tokenAtPos.getStart(sourceFile);
118644             // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.)
118645             if (!existingDocComment && tokenStart < position) {
118646                 return undefined;
118647             }
118648             var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos);
118649             if (!commentOwnerInfo) {
118650                 return undefined;
118651             }
118652             var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters;
118653             if (commentOwner.getStart(sourceFile) < position) {
118654                 return undefined;
118655             }
118656             if (!parameters || parameters.length === 0) {
118657                 // if there are no parameters, just complete to a single line JSDoc comment
118658                 var singleLineResult = "/** */";
118659                 return { newText: singleLineResult, caretOffset: 3 };
118660             }
118661             var indentationStr = getIndentationStringAtPosition(sourceFile, position);
118662             // A doc comment consists of the following
118663             // * The opening comment line
118664             // * the first line (without a param) for the object's untagged info (this is also where the caret ends up)
118665             // * the '@param'-tagged lines
118666             // * TODO: other tags.
118667             // * the closing comment line
118668             // * if the caret was directly in front of the object, then we add an extra line and indentation.
118669             var preamble = "/**" + newLine + indentationStr + " * ";
118670             var result = preamble + newLine +
118671                 parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) +
118672                 indentationStr + " */" +
118673                 (tokenStart === position ? newLine + indentationStr : "");
118674             return { newText: result, caretOffset: preamble.length };
118675         }
118676         JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition;
118677         function getIndentationStringAtPosition(sourceFile, position) {
118678             var text = sourceFile.text;
118679             var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
118680             var pos = lineStart;
118681             for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++)
118682                 ;
118683             return text.slice(lineStart, pos);
118684         }
118685         function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) {
118686             return parameters.map(function (_a, i) {
118687                 var name = _a.name, dotDotDotToken = _a.dotDotDotToken;
118688                 var paramName = name.kind === 75 /* Identifier */ ? name.text : "param" + i;
118689                 var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : "";
118690                 return indentationStr + " * @param " + type + paramName + newLine;
118691             }).join("");
118692         }
118693         function getCommentOwnerInfo(tokenAtPos) {
118694             return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker);
118695         }
118696         function getCommentOwnerInfoWorker(commentOwner) {
118697             switch (commentOwner.kind) {
118698                 case 244 /* FunctionDeclaration */:
118699                 case 201 /* FunctionExpression */:
118700                 case 161 /* MethodDeclaration */:
118701                 case 162 /* Constructor */:
118702                 case 160 /* MethodSignature */:
118703                     var parameters = commentOwner.parameters;
118704                     return { commentOwner: commentOwner, parameters: parameters };
118705                 case 281 /* PropertyAssignment */:
118706                     return getCommentOwnerInfoWorker(commentOwner.initializer);
118707                 case 245 /* ClassDeclaration */:
118708                 case 246 /* InterfaceDeclaration */:
118709                 case 158 /* PropertySignature */:
118710                 case 248 /* EnumDeclaration */:
118711                 case 284 /* EnumMember */:
118712                 case 247 /* TypeAliasDeclaration */:
118713                     return { commentOwner: commentOwner };
118714                 case 225 /* VariableStatement */: {
118715                     var varStatement = commentOwner;
118716                     var varDeclarations = varStatement.declarationList.declarations;
118717                     var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer
118718                         ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer)
118719                         : undefined;
118720                     return { commentOwner: commentOwner, parameters: parameters_1 };
118721                 }
118722                 case 290 /* SourceFile */:
118723                     return "quit";
118724                 case 249 /* ModuleDeclaration */:
118725                     // If in walking up the tree, we hit a a nested namespace declaration,
118726                     // then we must be somewhere within a dotted namespace name; however we don't
118727                     // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
118728                     return commentOwner.parent.kind === 249 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner };
118729                 case 226 /* ExpressionStatement */:
118730                     return getCommentOwnerInfoWorker(commentOwner.expression);
118731                 case 209 /* BinaryExpression */: {
118732                     var be = commentOwner;
118733                     if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) {
118734                         return "quit";
118735                     }
118736                     var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray;
118737                     return { commentOwner: commentOwner, parameters: parameters_2 };
118738                 }
118739                 case 159 /* PropertyDeclaration */:
118740                     var init = commentOwner.initializer;
118741                     if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) {
118742                         return { commentOwner: commentOwner, parameters: init.parameters };
118743                     }
118744             }
118745         }
118746         /**
118747          * Digs into an an initializer or RHS operand of an assignment operation
118748          * to get the parameters of an apt signature corresponding to a
118749          * function expression or a class expression.
118750          *
118751          * @param rightHandSide the expression which may contain an appropriate set of parameters
118752          * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
118753          */
118754         function getParametersFromRightHandSideOfAssignment(rightHandSide) {
118755             while (rightHandSide.kind === 200 /* ParenthesizedExpression */) {
118756                 rightHandSide = rightHandSide.expression;
118757             }
118758             switch (rightHandSide.kind) {
118759                 case 201 /* FunctionExpression */:
118760                 case 202 /* ArrowFunction */:
118761                     return rightHandSide.parameters;
118762                 case 214 /* ClassExpression */: {
118763                     var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration);
118764                     return ctr ? ctr.parameters : ts.emptyArray;
118765                 }
118766             }
118767             return ts.emptyArray;
118768         }
118769     })(JsDoc = ts.JsDoc || (ts.JsDoc = {}));
118770 })(ts || (ts = {}));
118771 /* @internal */
118772 var ts;
118773 (function (ts) {
118774     var NavigateTo;
118775     (function (NavigateTo) {
118776         function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
118777             var patternMatcher = ts.createPatternMatcher(searchValue);
118778             if (!patternMatcher)
118779                 return ts.emptyArray;
118780             var rawItems = [];
118781             var _loop_5 = function (sourceFile) {
118782                 cancellationToken.throwIfCancellationRequested();
118783                 if (excludeDtsFiles && sourceFile.isDeclarationFile) {
118784                     return "continue";
118785                 }
118786                 sourceFile.getNamedDeclarations().forEach(function (declarations, name) {
118787                     getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems);
118788                 });
118789             };
118790             // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
118791             for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
118792                 var sourceFile = sourceFiles_4[_i];
118793                 _loop_5(sourceFile);
118794             }
118795             rawItems.sort(compareNavigateToItems);
118796             return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
118797         }
118798         NavigateTo.getNavigateToItems = getNavigateToItems;
118799         function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) {
118800             // First do a quick check to see if the name of the declaration matches the
118801             // last portion of the (possibly) dotted name they're searching for.
118802             var match = patternMatcher.getMatchForLastSegmentOfPattern(name);
118803             if (!match) {
118804                 return; // continue to next named declarations
118805             }
118806             for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
118807                 var declaration = declarations_3[_i];
118808                 if (!shouldKeepItem(declaration, checker))
118809                     continue;
118810                 if (patternMatcher.patternContainsDots) {
118811                     // If the pattern has dots in it, then also see if the declaration container matches as well.
118812                     var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name);
118813                     if (fullMatch) {
118814                         rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration });
118815                     }
118816                 }
118817                 else {
118818                     rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration });
118819                 }
118820             }
118821         }
118822         function shouldKeepItem(declaration, checker) {
118823             switch (declaration.kind) {
118824                 case 255 /* ImportClause */:
118825                 case 258 /* ImportSpecifier */:
118826                 case 253 /* ImportEqualsDeclaration */:
118827                     var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217
118828                     var imported = checker.getAliasedSymbol(importer);
118829                     return importer.escapedName !== imported.escapedName;
118830                 default:
118831                     return true;
118832             }
118833         }
118834         function tryAddSingleDeclarationName(declaration, containers) {
118835             var name = ts.getNameOfDeclaration(declaration);
118836             return !!name && (pushLiteral(name, containers) || name.kind === 154 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers));
118837         }
118838         // Only added the names of computed properties if they're simple dotted expressions, like:
118839         //
118840         //      [X.Y.Z]() { }
118841         function tryAddComputedPropertyName(expression, containers) {
118842             return pushLiteral(expression, containers)
118843                 || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers);
118844         }
118845         function pushLiteral(node, containers) {
118846             return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true);
118847         }
118848         function getContainers(declaration) {
118849             var containers = [];
118850             // First, if we started with a computed property name, then add all but the last
118851             // portion into the container array.
118852             var name = ts.getNameOfDeclaration(declaration);
118853             if (name && name.kind === 154 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) {
118854                 return ts.emptyArray;
118855             }
118856             // Don't include the last portion.
118857             containers.shift();
118858             // Now, walk up our containers, adding all their names to the container array.
118859             var container = ts.getContainerNode(declaration);
118860             while (container) {
118861                 if (!tryAddSingleDeclarationName(container, containers)) {
118862                     return ts.emptyArray;
118863                 }
118864                 container = ts.getContainerNode(container);
118865             }
118866             return containers.reverse();
118867         }
118868         function compareNavigateToItems(i1, i2) {
118869             // TODO(cyrusn): get the gamut of comparisons that VS already uses here.
118870             return ts.compareValues(i1.matchKind, i2.matchKind)
118871                 || ts.compareStringsCaseSensitiveUI(i1.name, i2.name);
118872         }
118873         function createNavigateToItem(rawItem) {
118874             var declaration = rawItem.declaration;
118875             var container = ts.getContainerNode(declaration);
118876             var containerName = container && ts.getNameOfDeclaration(container);
118877             return {
118878                 name: rawItem.name,
118879                 kind: ts.getNodeKind(declaration),
118880                 kindModifiers: ts.getNodeModifiers(declaration),
118881                 matchKind: ts.PatternMatchKind[rawItem.matchKind],
118882                 isCaseSensitive: rawItem.isCaseSensitive,
118883                 fileName: rawItem.fileName,
118884                 textSpan: ts.createTextSpanFromNode(declaration),
118885                 // TODO(jfreeman): What should be the containerName when the container has a computed name?
118886                 containerName: containerName ? containerName.text : "",
118887                 containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */,
118888             };
118889         }
118890     })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {}));
118891 })(ts || (ts = {}));
118892 /* @internal */
118893 var ts;
118894 (function (ts) {
118895     var NavigationBar;
118896     (function (NavigationBar) {
118897         var _a;
118898         /**
118899          * Matches all whitespace characters in a string. Eg:
118900          *
118901          * "app.
118902          *
118903          * onactivated"
118904          *
118905          * matches because of the newline, whereas
118906          *
118907          * "app.onactivated"
118908          *
118909          * does not match.
118910          */
118911         var whiteSpaceRegex = /\s+/g;
118912         /**
118913          * Maximum amount of characters to return
118914          * The amount was chosen arbitrarily.
118915          */
118916         var maxLength = 150;
118917         // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`.
118918         var curCancellationToken;
118919         var curSourceFile;
118920         /**
118921          * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion.
118922          * `parent` is the current parent and is *not* stored in parentsStack.
118923          * `startNode` sets a new parent and `endNode` returns to the previous parent.
118924          */
118925         var parentsStack = [];
118926         var parent;
118927         var trackedEs5ClassesStack = [];
118928         var trackedEs5Classes;
118929         // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance.
118930         var emptyChildItemArray = [];
118931         function getNavigationBarItems(sourceFile, cancellationToken) {
118932             curCancellationToken = cancellationToken;
118933             curSourceFile = sourceFile;
118934             try {
118935                 return ts.map(primaryNavBarMenuItems(rootNavigationBarNode(sourceFile)), convertToPrimaryNavBarMenuItem);
118936             }
118937             finally {
118938                 reset();
118939             }
118940         }
118941         NavigationBar.getNavigationBarItems = getNavigationBarItems;
118942         function getNavigationTree(sourceFile, cancellationToken) {
118943             curCancellationToken = cancellationToken;
118944             curSourceFile = sourceFile;
118945             try {
118946                 return convertToTree(rootNavigationBarNode(sourceFile));
118947             }
118948             finally {
118949                 reset();
118950             }
118951         }
118952         NavigationBar.getNavigationTree = getNavigationTree;
118953         function reset() {
118954             curSourceFile = undefined;
118955             curCancellationToken = undefined;
118956             parentsStack = [];
118957             parent = undefined;
118958             emptyChildItemArray = [];
118959         }
118960         function nodeText(node) {
118961             return cleanText(node.getText(curSourceFile));
118962         }
118963         function navigationBarNodeKind(n) {
118964             return n.node.kind;
118965         }
118966         function pushChild(parent, child) {
118967             if (parent.children) {
118968                 parent.children.push(child);
118969             }
118970             else {
118971                 parent.children = [child];
118972             }
118973         }
118974         function rootNavigationBarNode(sourceFile) {
118975             ts.Debug.assert(!parentsStack.length);
118976             var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 };
118977             parent = root;
118978             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
118979                 var statement = _a[_i];
118980                 addChildrenRecursively(statement);
118981             }
118982             endNode();
118983             ts.Debug.assert(!parent && !parentsStack.length);
118984             return root;
118985         }
118986         function addLeafNode(node, name) {
118987             pushChild(parent, emptyNavigationBarNode(node, name));
118988         }
118989         function emptyNavigationBarNode(node, name) {
118990             return {
118991                 node: node,
118992                 name: name || (ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined),
118993                 additionalNodes: undefined,
118994                 parent: parent,
118995                 children: undefined,
118996                 indent: parent.indent + 1
118997             };
118998         }
118999         function addTrackedEs5Class(name) {
119000             if (!trackedEs5Classes) {
119001                 trackedEs5Classes = ts.createMap();
119002             }
119003             trackedEs5Classes.set(name, true);
119004         }
119005         function endNestedNodes(depth) {
119006             for (var i = 0; i < depth; i++)
119007                 endNode();
119008         }
119009         function startNestedNodes(targetNode, entityName) {
119010             var names = [];
119011             while (!ts.isPropertyNameLiteral(entityName)) {
119012                 var name = ts.getNameOrArgument(entityName);
119013                 var nameText = ts.getElementOrPropertyAccessName(entityName);
119014                 entityName = entityName.expression;
119015                 if (nameText === "prototype" || ts.isPrivateIdentifier(name))
119016                     continue;
119017                 names.push(name);
119018             }
119019             names.push(entityName);
119020             for (var i = names.length - 1; i > 0; i--) {
119021                 var name = names[i];
119022                 startNode(targetNode, name);
119023             }
119024             return [names.length - 1, names[0]];
119025         }
119026         /**
119027          * Add a new level of NavigationBarNodes.
119028          * This pushes to the stack, so you must call `endNode` when you are done adding to this node.
119029          */
119030         function startNode(node, name) {
119031             var navNode = emptyNavigationBarNode(node, name);
119032             pushChild(parent, navNode);
119033             // Save the old parent
119034             parentsStack.push(parent);
119035             trackedEs5ClassesStack.push(trackedEs5Classes);
119036             parent = navNode;
119037         }
119038         /** Call after calling `startNode` and adding children to it. */
119039         function endNode() {
119040             if (parent.children) {
119041                 mergeChildren(parent.children, parent);
119042                 sortChildren(parent.children);
119043             }
119044             parent = parentsStack.pop();
119045             trackedEs5Classes = trackedEs5ClassesStack.pop();
119046         }
119047         function addNodeWithRecursiveChild(node, child, name) {
119048             startNode(node, name);
119049             addChildrenRecursively(child);
119050             endNode();
119051         }
119052         /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */
119053         function addChildrenRecursively(node) {
119054             var _a;
119055             curCancellationToken.throwIfCancellationRequested();
119056             if (!node || ts.isToken(node)) {
119057                 return;
119058             }
119059             switch (node.kind) {
119060                 case 162 /* Constructor */:
119061                     // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it.
119062                     var ctr = node;
119063                     addNodeWithRecursiveChild(ctr, ctr.body);
119064                     // Parameter properties are children of the class, not the constructor.
119065                     for (var _i = 0, _b = ctr.parameters; _i < _b.length; _i++) {
119066                         var param = _b[_i];
119067                         if (ts.isParameterPropertyDeclaration(param, ctr)) {
119068                             addLeafNode(param);
119069                         }
119070                     }
119071                     break;
119072                 case 161 /* MethodDeclaration */:
119073                 case 163 /* GetAccessor */:
119074                 case 164 /* SetAccessor */:
119075                 case 160 /* MethodSignature */:
119076                     if (!ts.hasDynamicName(node)) {
119077                         addNodeWithRecursiveChild(node, node.body);
119078                     }
119079                     break;
119080                 case 159 /* PropertyDeclaration */:
119081                 case 158 /* PropertySignature */:
119082                     if (!ts.hasDynamicName(node)) {
119083                         addLeafNode(node);
119084                     }
119085                     break;
119086                 case 255 /* ImportClause */:
119087                     var importClause = node;
119088                     // Handle default import case e.g.:
119089                     //    import d from "mod";
119090                     if (importClause.name) {
119091                         addLeafNode(importClause.name);
119092                     }
119093                     // Handle named bindings in imports e.g.:
119094                     //    import * as NS from "mod";
119095                     //    import {a, b as B} from "mod";
119096                     var namedBindings = importClause.namedBindings;
119097                     if (namedBindings) {
119098                         if (namedBindings.kind === 256 /* NamespaceImport */) {
119099                             addLeafNode(namedBindings);
119100                         }
119101                         else {
119102                             for (var _c = 0, _d = namedBindings.elements; _c < _d.length; _c++) {
119103                                 var element = _d[_c];
119104                                 addLeafNode(element);
119105                             }
119106                         }
119107                     }
119108                     break;
119109                 case 282 /* ShorthandPropertyAssignment */:
119110                     addNodeWithRecursiveChild(node, node.name);
119111                     break;
119112                 case 283 /* SpreadAssignment */:
119113                     var expression = node.expression;
119114                     // Use the expression as the name of the SpreadAssignment, otherwise show as <unknown>.
119115                     ts.isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node);
119116                     break;
119117                 case 191 /* BindingElement */:
119118                 case 281 /* PropertyAssignment */:
119119                 case 242 /* VariableDeclaration */:
119120                     var _e = node, name = _e.name, initializer = _e.initializer;
119121                     if (ts.isBindingPattern(name)) {
119122                         addChildrenRecursively(name);
119123                     }
119124                     else if (initializer && isFunctionOrClassExpression(initializer)) {
119125                         // Add a node for the VariableDeclaration, but not for the initializer.
119126                         startNode(node);
119127                         ts.forEachChild(initializer, addChildrenRecursively);
119128                         endNode();
119129                     }
119130                     else {
119131                         addNodeWithRecursiveChild(node, initializer);
119132                     }
119133                     break;
119134                 case 244 /* FunctionDeclaration */:
119135                     var nameNode = node.name;
119136                     // If we see a function declaration track as a possible ES5 class
119137                     if (nameNode && ts.isIdentifier(nameNode)) {
119138                         addTrackedEs5Class(nameNode.text);
119139                     }
119140                     addNodeWithRecursiveChild(node, node.body);
119141                     break;
119142                 case 202 /* ArrowFunction */:
119143                 case 201 /* FunctionExpression */:
119144                     addNodeWithRecursiveChild(node, node.body);
119145                     break;
119146                 case 248 /* EnumDeclaration */:
119147                     startNode(node);
119148                     for (var _f = 0, _g = node.members; _f < _g.length; _f++) {
119149                         var member = _g[_f];
119150                         if (!isComputedProperty(member)) {
119151                             addLeafNode(member);
119152                         }
119153                     }
119154                     endNode();
119155                     break;
119156                 case 245 /* ClassDeclaration */:
119157                 case 214 /* ClassExpression */:
119158                 case 246 /* InterfaceDeclaration */:
119159                     startNode(node);
119160                     for (var _h = 0, _j = node.members; _h < _j.length; _h++) {
119161                         var member = _j[_h];
119162                         addChildrenRecursively(member);
119163                     }
119164                     endNode();
119165                     break;
119166                 case 249 /* ModuleDeclaration */:
119167                     addNodeWithRecursiveChild(node, getInteriorModule(node).body);
119168                     break;
119169                 case 259 /* ExportAssignment */:
119170                 case 263 /* ExportSpecifier */:
119171                 case 253 /* ImportEqualsDeclaration */:
119172                 case 167 /* IndexSignature */:
119173                 case 165 /* CallSignature */:
119174                 case 166 /* ConstructSignature */:
119175                 case 247 /* TypeAliasDeclaration */:
119176                     addLeafNode(node);
119177                     break;
119178                 case 196 /* CallExpression */:
119179                 case 209 /* BinaryExpression */: {
119180                     var special = ts.getAssignmentDeclarationKind(node);
119181                     switch (special) {
119182                         case 1 /* ExportsProperty */:
119183                         case 2 /* ModuleExports */:
119184                             addNodeWithRecursiveChild(node, node.right);
119185                             return;
119186                         case 6 /* Prototype */:
119187                         case 3 /* PrototypeProperty */: {
119188                             var binaryExpression = node;
119189                             var assignmentTarget = binaryExpression.left;
119190                             var prototypeAccess = special === 3 /* PrototypeProperty */ ?
119191                                 assignmentTarget.expression :
119192                                 assignmentTarget;
119193                             var depth = 0;
119194                             var className = void 0;
119195                             // If we see a prototype assignment, start tracking the target as a class
119196                             // This is only done for simple classes not nested assignments.
119197                             if (ts.isIdentifier(prototypeAccess.expression)) {
119198                                 addTrackedEs5Class(prototypeAccess.expression.text);
119199                                 className = prototypeAccess.expression;
119200                             }
119201                             else {
119202                                 _a = startNestedNodes(binaryExpression, prototypeAccess.expression), depth = _a[0], className = _a[1];
119203                             }
119204                             if (special === 6 /* Prototype */) {
119205                                 if (ts.isObjectLiteralExpression(binaryExpression.right)) {
119206                                     if (binaryExpression.right.properties.length > 0) {
119207                                         startNode(binaryExpression, className);
119208                                         ts.forEachChild(binaryExpression.right, addChildrenRecursively);
119209                                         endNode();
119210                                     }
119211                                 }
119212                             }
119213                             else if (ts.isFunctionExpression(binaryExpression.right) || ts.isArrowFunction(binaryExpression.right)) {
119214                                 addNodeWithRecursiveChild(node, binaryExpression.right, className);
119215                             }
119216                             else {
119217                                 startNode(binaryExpression, className);
119218                                 addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name);
119219                                 endNode();
119220                             }
119221                             endNestedNodes(depth);
119222                             return;
119223                         }
119224                         case 7 /* ObjectDefinePropertyValue */:
119225                         case 9 /* ObjectDefinePrototypeProperty */: {
119226                             var defineCall = node;
119227                             var className = special === 7 /* ObjectDefinePropertyValue */ ?
119228                                 defineCall.arguments[0] :
119229                                 defineCall.arguments[0].expression;
119230                             var memberName = defineCall.arguments[1];
119231                             var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1];
119232                             startNode(node, classNameIdentifier);
119233                             startNode(node, ts.setTextRange(ts.createIdentifier(memberName.text), memberName));
119234                             addChildrenRecursively(node.arguments[2]);
119235                             endNode();
119236                             endNode();
119237                             endNestedNodes(depth);
119238                             return;
119239                         }
119240                         case 5 /* Property */: {
119241                             var binaryExpression = node;
119242                             var assignmentTarget = binaryExpression.left;
119243                             var targetFunction = assignmentTarget.expression;
119244                             if (ts.isIdentifier(targetFunction) && ts.getElementOrPropertyAccessName(assignmentTarget) !== "prototype" &&
119245                                 trackedEs5Classes && trackedEs5Classes.has(targetFunction.text)) {
119246                                 if (ts.isFunctionExpression(binaryExpression.right) || ts.isArrowFunction(binaryExpression.right)) {
119247                                     addNodeWithRecursiveChild(node, binaryExpression.right, targetFunction);
119248                                 }
119249                                 else if (ts.isBindableStaticAccessExpression(assignmentTarget)) {
119250                                     startNode(binaryExpression, targetFunction);
119251                                     addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, ts.getNameOrArgument(assignmentTarget));
119252                                     endNode();
119253                                 }
119254                                 return;
119255                             }
119256                             break;
119257                         }
119258                         case 4 /* ThisProperty */:
119259                         case 0 /* None */:
119260                         case 8 /* ObjectDefinePropertyExports */:
119261                             break;
119262                         default:
119263                             ts.Debug.assertNever(special);
119264                     }
119265                 }
119266                 // falls through
119267                 default:
119268                     if (ts.hasJSDocNodes(node)) {
119269                         ts.forEach(node.jsDoc, function (jsDoc) {
119270                             ts.forEach(jsDoc.tags, function (tag) {
119271                                 if (ts.isJSDocTypeAlias(tag)) {
119272                                     addLeafNode(tag);
119273                                 }
119274                             });
119275                         });
119276                     }
119277                     ts.forEachChild(node, addChildrenRecursively);
119278             }
119279         }
119280         /** Merge declarations of the same kind. */
119281         function mergeChildren(children, node) {
119282             var nameToItems = ts.createMap();
119283             ts.filterMutate(children, function (child, index) {
119284                 var declName = child.name || ts.getNameOfDeclaration(child.node);
119285                 var name = declName && nodeText(declName);
119286                 if (!name) {
119287                     // Anonymous items are never merged.
119288                     return true;
119289                 }
119290                 var itemsWithSameName = nameToItems.get(name);
119291                 if (!itemsWithSameName) {
119292                     nameToItems.set(name, child);
119293                     return true;
119294                 }
119295                 if (itemsWithSameName instanceof Array) {
119296                     for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) {
119297                         var itemWithSameName = itemsWithSameName_1[_i];
119298                         if (tryMerge(itemWithSameName, child, index, node)) {
119299                             return false;
119300                         }
119301                     }
119302                     itemsWithSameName.push(child);
119303                     return true;
119304                 }
119305                 else {
119306                     var itemWithSameName = itemsWithSameName;
119307                     if (tryMerge(itemWithSameName, child, index, node)) {
119308                         return false;
119309                     }
119310                     nameToItems.set(name, [itemWithSameName, child]);
119311                     return true;
119312                 }
119313             });
119314         }
119315         var isEs5ClassMember = (_a = {},
119316             _a[5 /* Property */] = true,
119317             _a[3 /* PrototypeProperty */] = true,
119318             _a[7 /* ObjectDefinePropertyValue */] = true,
119319             _a[9 /* ObjectDefinePrototypeProperty */] = true,
119320             _a[0 /* None */] = false,
119321             _a[1 /* ExportsProperty */] = false,
119322             _a[2 /* ModuleExports */] = false,
119323             _a[8 /* ObjectDefinePropertyExports */] = false,
119324             _a[6 /* Prototype */] = true,
119325             _a[4 /* ThisProperty */] = false,
119326             _a);
119327         function tryMergeEs5Class(a, b, bIndex, parent) {
119328             function isPossibleConstructor(node) {
119329                 return ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isVariableDeclaration(node);
119330             }
119331             var bAssignmentDeclarationKind = ts.isBinaryExpression(b.node) || ts.isCallExpression(b.node) ?
119332                 ts.getAssignmentDeclarationKind(b.node) :
119333                 0 /* None */;
119334             var aAssignmentDeclarationKind = ts.isBinaryExpression(a.node) || ts.isCallExpression(a.node) ?
119335                 ts.getAssignmentDeclarationKind(a.node) :
119336                 0 /* None */;
119337             // We treat this as an es5 class and merge the nodes in in one of several cases
119338             if ((isEs5ClassMember[bAssignmentDeclarationKind] && isEs5ClassMember[aAssignmentDeclarationKind]) // merge two class elements
119339                 || (isPossibleConstructor(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // ctor function & member
119340                 || (isPossibleConstructor(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & ctor function
119341                 || (ts.isClassDeclaration(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // class (generated) & member
119342                 || (ts.isClassDeclaration(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & class (generated)
119343                 || (ts.isClassDeclaration(a.node) && isPossibleConstructor(b.node)) // class (generated) & ctor
119344                 || (ts.isClassDeclaration(b.node) && isPossibleConstructor(a.node)) // ctor & class (generated)
119345             ) {
119346                 var lastANode = a.additionalNodes && ts.lastOrUndefined(a.additionalNodes) || a.node;
119347                 if ((!ts.isClassDeclaration(a.node) && !ts.isClassDeclaration(b.node)) // If neither outline node is a class
119348                     || isPossibleConstructor(a.node) || isPossibleConstructor(b.node) // If either function is a constructor function
119349                 ) {
119350                     var ctorFunction = isPossibleConstructor(a.node) ? a.node :
119351                         isPossibleConstructor(b.node) ? b.node :
119352                             undefined;
119353                     if (ctorFunction !== undefined) {
119354                         var ctorNode = ts.setTextRange(ts.createConstructor(/* decorators */ undefined, /* modifiers */ undefined, [], /* body */ undefined), ctorFunction);
119355                         var ctor = emptyNavigationBarNode(ctorNode);
119356                         ctor.indent = a.indent + 1;
119357                         ctor.children = a.node === ctorFunction ? a.children : b.children;
119358                         a.children = a.node === ctorFunction ? ts.concatenate([ctor], b.children || [b]) : ts.concatenate(a.children || [a], [ctor]);
119359                     }
119360                     else {
119361                         if (a.children || b.children) {
119362                             a.children = ts.concatenate(a.children || [a], b.children || [b]);
119363                             if (a.children) {
119364                                 mergeChildren(a.children, a);
119365                                 sortChildren(a.children);
119366                             }
119367                         }
119368                     }
119369                     lastANode = a.node = ts.setTextRange(ts.createClassDeclaration(
119370                     /* decorators */ undefined, 
119371                     /* modifiers */ undefined, a.name || ts.createIdentifier("__class__"), 
119372                     /* typeParameters */ undefined, 
119373                     /* heritageClauses */ undefined, []), a.node);
119374                 }
119375                 else {
119376                     a.children = ts.concatenate(a.children, b.children);
119377                     if (a.children) {
119378                         mergeChildren(a.children, a);
119379                     }
119380                 }
119381                 var bNode = b.node;
119382                 // We merge if the outline node previous to b (bIndex - 1) is already part of the current class
119383                 // We do this so that statements between class members that do not generate outline nodes do not split up the class outline:
119384                 // Ex This should produce one outline node C:
119385                 //    function C() {}; a = 1; C.prototype.m = function () {}
119386                 // Ex This will produce 3 outline nodes: C, a, C
119387                 //    function C() {}; let a = 1; C.prototype.m = function () {}
119388                 if (parent.children[bIndex - 1].node.end === lastANode.end) {
119389                     ts.setTextRange(lastANode, { pos: lastANode.pos, end: bNode.end });
119390                 }
119391                 else {
119392                     if (!a.additionalNodes)
119393                         a.additionalNodes = [];
119394                     a.additionalNodes.push(ts.setTextRange(ts.createClassDeclaration(
119395                     /* decorators */ undefined, 
119396                     /* modifiers */ undefined, a.name || ts.createIdentifier("__class__"), 
119397                     /* typeParameters */ undefined, 
119398                     /* heritageClauses */ undefined, []), b.node));
119399                 }
119400                 return true;
119401             }
119402             return bAssignmentDeclarationKind === 0 /* None */ ? false : true;
119403         }
119404         function tryMerge(a, b, bIndex, parent) {
119405             // const v = false as boolean;
119406             if (tryMergeEs5Class(a, b, bIndex, parent)) {
119407                 return true;
119408             }
119409             if (shouldReallyMerge(a.node, b.node, parent)) {
119410                 merge(a, b);
119411                 return true;
119412             }
119413             return false;
119414         }
119415         /** a and b have the same name, but they may not be mergeable. */
119416         function shouldReallyMerge(a, b, parent) {
119417             if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) {
119418                 return false;
119419             }
119420             switch (a.kind) {
119421                 case 159 /* PropertyDeclaration */:
119422                 case 161 /* MethodDeclaration */:
119423                 case 163 /* GetAccessor */:
119424                 case 164 /* SetAccessor */:
119425                     return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */);
119426                 case 249 /* ModuleDeclaration */:
119427                     return areSameModule(a, b);
119428                 default:
119429                     return true;
119430             }
119431         }
119432         // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }`
119433         // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };`
119434         function isOwnChild(n, parent) {
119435             var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent;
119436             return par === parent.node || ts.contains(parent.additionalNodes, par);
119437         }
119438         // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes.
119439         // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'!
119440         function areSameModule(a, b) {
119441             // TODO: GH#18217
119442             return a.body.kind === b.body.kind && (a.body.kind !== 249 /* ModuleDeclaration */ || areSameModule(a.body, b.body));
119443         }
119444         /** Merge source into target. Source should be thrown away after this is called. */
119445         function merge(target, source) {
119446             var _a;
119447             target.additionalNodes = target.additionalNodes || [];
119448             target.additionalNodes.push(source.node);
119449             if (source.additionalNodes) {
119450                 (_a = target.additionalNodes).push.apply(_a, source.additionalNodes);
119451             }
119452             target.children = ts.concatenate(target.children, source.children);
119453             if (target.children) {
119454                 mergeChildren(target.children, target);
119455                 sortChildren(target.children);
119456             }
119457         }
119458         /** Recursively ensure that each NavNode's children are in sorted order. */
119459         function sortChildren(children) {
119460             children.sort(compareChildren);
119461         }
119462         function compareChildren(child1, child2) {
119463             return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217
119464                 || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2));
119465         }
119466         /**
119467          * This differs from getItemName because this is just used for sorting.
119468          * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like.
119469          * So `new()` can still come before an `aardvark` method.
119470          */
119471         function tryGetName(node) {
119472             if (node.kind === 249 /* ModuleDeclaration */) {
119473                 return getModuleName(node);
119474             }
119475             var declName = ts.getNameOfDeclaration(node);
119476             if (declName && ts.isPropertyName(declName)) {
119477                 var propertyName = ts.getPropertyNameForPropertyNameNode(declName);
119478                 return propertyName && ts.unescapeLeadingUnderscores(propertyName);
119479             }
119480             switch (node.kind) {
119481                 case 201 /* FunctionExpression */:
119482                 case 202 /* ArrowFunction */:
119483                 case 214 /* ClassExpression */:
119484                     return getFunctionOrClassName(node);
119485                 default:
119486                     return undefined;
119487             }
119488         }
119489         function getItemName(node, name) {
119490             if (node.kind === 249 /* ModuleDeclaration */) {
119491                 return cleanText(getModuleName(node));
119492             }
119493             if (name) {
119494                 var text = ts.isIdentifier(name) ? name.text
119495                     : ts.isElementAccessExpression(name) ? "[" + nodeText(name.argumentExpression) + "]"
119496                         : nodeText(name);
119497                 if (text.length > 0) {
119498                     return cleanText(text);
119499                 }
119500             }
119501             switch (node.kind) {
119502                 case 290 /* SourceFile */:
119503                     var sourceFile = node;
119504                     return ts.isExternalModule(sourceFile)
119505                         ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
119506                         : "<global>";
119507                 case 259 /* ExportAssignment */:
119508                     return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
119509                 case 202 /* ArrowFunction */:
119510                 case 244 /* FunctionDeclaration */:
119511                 case 201 /* FunctionExpression */:
119512                 case 245 /* ClassDeclaration */:
119513                 case 214 /* ClassExpression */:
119514                     if (ts.getModifierFlags(node) & 512 /* Default */) {
119515                         return "default";
119516                     }
119517                     // We may get a string with newlines or other whitespace in the case of an object dereference
119518                     // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the
119519                     // navigation bar.
119520                     return getFunctionOrClassName(node);
119521                 case 162 /* Constructor */:
119522                     return "constructor";
119523                 case 166 /* ConstructSignature */:
119524                     return "new()";
119525                 case 165 /* CallSignature */:
119526                     return "()";
119527                 case 167 /* IndexSignature */:
119528                     return "[]";
119529                 default:
119530                     return "<unknown>";
119531             }
119532         }
119533         /** Flattens the NavNode tree to a list of items to appear in the primary navbar menu. */
119534         function primaryNavBarMenuItems(root) {
119535             // The primary (middle) navbar menu displays the general code navigation hierarchy, similar to the navtree.
119536             // The secondary (right) navbar menu displays the child items of whichever primary item is selected.
119537             // Some less interesting items without their own child navigation items (e.g. a local variable declaration) only show up in the secondary menu.
119538             var primaryNavBarMenuItems = [];
119539             function recur(item) {
119540                 if (shouldAppearInPrimaryNavBarMenu(item)) {
119541                     primaryNavBarMenuItems.push(item);
119542                     if (item.children) {
119543                         for (var _i = 0, _a = item.children; _i < _a.length; _i++) {
119544                             var child = _a[_i];
119545                             recur(child);
119546                         }
119547                     }
119548                 }
119549             }
119550             recur(root);
119551             return primaryNavBarMenuItems;
119552             /** Determines if a node should appear in the primary navbar menu. */
119553             function shouldAppearInPrimaryNavBarMenu(item) {
119554                 // Items with children should always appear in the primary navbar menu.
119555                 if (item.children) {
119556                     return true;
119557                 }
119558                 // Some nodes are otherwise important enough to always include in the primary navigation menu.
119559                 switch (navigationBarNodeKind(item)) {
119560                     case 245 /* ClassDeclaration */:
119561                     case 214 /* ClassExpression */:
119562                     case 248 /* EnumDeclaration */:
119563                     case 246 /* InterfaceDeclaration */:
119564                     case 249 /* ModuleDeclaration */:
119565                     case 290 /* SourceFile */:
119566                     case 247 /* TypeAliasDeclaration */:
119567                     case 322 /* JSDocTypedefTag */:
119568                     case 315 /* JSDocCallbackTag */:
119569                         return true;
119570                     case 202 /* ArrowFunction */:
119571                     case 244 /* FunctionDeclaration */:
119572                     case 201 /* FunctionExpression */:
119573                         return isTopLevelFunctionDeclaration(item);
119574                     default:
119575                         return false;
119576                 }
119577                 function isTopLevelFunctionDeclaration(item) {
119578                     if (!item.node.body) {
119579                         return false;
119580                     }
119581                     switch (navigationBarNodeKind(item.parent)) {
119582                         case 250 /* ModuleBlock */:
119583                         case 290 /* SourceFile */:
119584                         case 161 /* MethodDeclaration */:
119585                         case 162 /* Constructor */:
119586                             return true;
119587                         default:
119588                             return false;
119589                     }
119590                 }
119591             }
119592         }
119593         function convertToTree(n) {
119594             return {
119595                 text: getItemName(n.node, n.name),
119596                 kind: ts.getNodeKind(n.node),
119597                 kindModifiers: getModifiers(n.node),
119598                 spans: getSpans(n),
119599                 nameSpan: n.name && getNodeSpan(n.name),
119600                 childItems: ts.map(n.children, convertToTree)
119601             };
119602         }
119603         function convertToPrimaryNavBarMenuItem(n) {
119604             return {
119605                 text: getItemName(n.node, n.name),
119606                 kind: ts.getNodeKind(n.node),
119607                 kindModifiers: getModifiers(n.node),
119608                 spans: getSpans(n),
119609                 childItems: ts.map(n.children, convertToSecondaryNavBarMenuItem) || emptyChildItemArray,
119610                 indent: n.indent,
119611                 bolded: false,
119612                 grayed: false
119613             };
119614             function convertToSecondaryNavBarMenuItem(n) {
119615                 return {
119616                     text: getItemName(n.node, n.name),
119617                     kind: ts.getNodeKind(n.node),
119618                     kindModifiers: ts.getNodeModifiers(n.node),
119619                     spans: getSpans(n),
119620                     childItems: emptyChildItemArray,
119621                     indent: 0,
119622                     bolded: false,
119623                     grayed: false
119624                 };
119625             }
119626         }
119627         function getSpans(n) {
119628             var spans = [getNodeSpan(n.node)];
119629             if (n.additionalNodes) {
119630                 for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) {
119631                     var node = _a[_i];
119632                     spans.push(getNodeSpan(node));
119633                 }
119634             }
119635             return spans;
119636         }
119637         function getModuleName(moduleDeclaration) {
119638             // We want to maintain quotation marks.
119639             if (ts.isAmbientModule(moduleDeclaration)) {
119640                 return ts.getTextOfNode(moduleDeclaration.name);
119641             }
119642             // Otherwise, we need to aggregate each identifier to build up the qualified name.
119643             var result = [];
119644             result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
119645             while (moduleDeclaration.body && moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
119646                 moduleDeclaration = moduleDeclaration.body;
119647                 result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
119648             }
119649             return result.join(".");
119650         }
119651         /**
119652          * For 'module A.B.C', we want to get the node for 'C'.
119653          * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again.
119654          */
119655         function getInteriorModule(decl) {
119656             return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl;
119657         }
119658         function isComputedProperty(member) {
119659             return !member.name || member.name.kind === 154 /* ComputedPropertyName */;
119660         }
119661         function getNodeSpan(node) {
119662             return node.kind === 290 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
119663         }
119664         function getModifiers(node) {
119665             if (node.parent && node.parent.kind === 242 /* VariableDeclaration */) {
119666                 node = node.parent;
119667             }
119668             return ts.getNodeModifiers(node);
119669         }
119670         function getFunctionOrClassName(node) {
119671             var parent = node.parent;
119672             if (node.name && ts.getFullWidth(node.name) > 0) {
119673                 return cleanText(ts.declarationNameToString(node.name));
119674             }
119675             // See if it is a var initializer. If so, use the var name.
119676             else if (ts.isVariableDeclaration(parent)) {
119677                 return cleanText(ts.declarationNameToString(parent.name));
119678             }
119679             // See if it is of the form "<expr> = function(){...}". If so, use the text from the left-hand side.
119680             else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */) {
119681                 return nodeText(parent.left).replace(whiteSpaceRegex, "");
119682             }
119683             // See if it is a property assignment, and if so use the property name
119684             else if (ts.isPropertyAssignment(parent)) {
119685                 return nodeText(parent.name);
119686             }
119687             // Default exports are named "default"
119688             else if (ts.getModifierFlags(node) & 512 /* Default */) {
119689                 return "default";
119690             }
119691             else if (ts.isClassLike(node)) {
119692                 return "<class>";
119693             }
119694             else if (ts.isCallExpression(parent)) {
119695                 var name = getCalledExpressionName(parent.expression);
119696                 if (name !== undefined) {
119697                     name = cleanText(name);
119698                     if (name.length > maxLength) {
119699                         return name + " callback";
119700                     }
119701                     var args = cleanText(ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined; }).join(", "));
119702                     return name + "(" + args + ") callback";
119703                 }
119704             }
119705             return "<function>";
119706         }
119707         // See also 'tryGetPropertyAccessOrIdentifierToString'
119708         function getCalledExpressionName(expr) {
119709             if (ts.isIdentifier(expr)) {
119710                 return expr.text;
119711             }
119712             else if (ts.isPropertyAccessExpression(expr)) {
119713                 var left = getCalledExpressionName(expr.expression);
119714                 var right = expr.name.text;
119715                 return left === undefined ? right : left + "." + right;
119716             }
119717             else {
119718                 return undefined;
119719             }
119720         }
119721         function isFunctionOrClassExpression(node) {
119722             switch (node.kind) {
119723                 case 202 /* ArrowFunction */:
119724                 case 201 /* FunctionExpression */:
119725                 case 214 /* ClassExpression */:
119726                     return true;
119727                 default:
119728                     return false;
119729             }
119730         }
119731         function cleanText(text) {
119732             // Truncate to maximum amount of characters as we don't want to do a big replace operation.
119733             text = text.length > maxLength ? text.substring(0, maxLength) + "..." : text;
119734             // Replaces ECMAScript line terminators and removes the trailing `\` from each line:
119735             // \n - Line Feed
119736             // \r - Carriage Return
119737             // \u2028 - Line separator
119738             // \u2029 - Paragraph separator
119739             return text.replace(/\\?(\r?\n|\r|\u2028|\u2029)/g, "");
119740         }
119741     })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {}));
119742 })(ts || (ts = {}));
119743 /* @internal */
119744 var ts;
119745 (function (ts) {
119746     var OrganizeImports;
119747     (function (OrganizeImports) {
119748         /**
119749          * Organize imports by:
119750          *   1) Removing unused imports
119751          *   2) Coalescing imports from the same module
119752          *   3) Sorting imports
119753          */
119754         function organizeImports(sourceFile, formatContext, host, program, preferences) {
119755             var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences });
119756             var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
119757             // All of the old ImportDeclarations in the file, in syntactic order.
119758             var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
119759             organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
119760             // All of the old ExportDeclarations in the file, in syntactic order.
119761             var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
119762             organizeImportsWorker(topLevelExportDecls, coalesceExports);
119763             for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
119764                 var ambientModule = _a[_i];
119765                 if (!ambientModule.body) {
119766                     continue;
119767                 }
119768                 var ambientModuleImportDecls = ambientModule.body.statements.filter(ts.isImportDeclaration);
119769                 organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
119770                 var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration);
119771                 organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
119772             }
119773             return changeTracker.getChanges();
119774             function organizeImportsWorker(oldImportDecls, coalesce) {
119775                 if (ts.length(oldImportDecls) === 0) {
119776                     return;
119777                 }
119778                 // Special case: normally, we'd expect leading and trailing trivia to follow each import
119779                 // around as it's sorted.  However, we do not want this to happen for leading trivia
119780                 // on the first import because it is probably the header comment for the file.
119781                 // Consider: we could do a more careful check that this trivia is actually a header,
119782                 // but the consequences of being wrong are very minor.
119783                 ts.suppressLeadingTrivia(oldImportDecls[0]);
119784                 var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
119785                 var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
119786                 var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
119787                     return getExternalModuleName(importGroup[0].moduleSpecifier)
119788                         ? coalesce(importGroup)
119789                         : importGroup;
119790                 });
119791                 // Delete or replace the first import.
119792                 if (newImportDecls.length === 0) {
119793                     changeTracker.delete(sourceFile, oldImportDecls[0]);
119794                 }
119795                 else {
119796                     // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
119797                     changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
119798                         leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
119799                         trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
119800                         suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
119801                     });
119802                 }
119803                 // Delete any subsequent imports.
119804                 for (var i = 1; i < oldImportDecls.length; i++) {
119805                     changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
119806                 }
119807             }
119808         }
119809         OrganizeImports.organizeImports = organizeImports;
119810         function removeUnusedImports(oldImports, sourceFile, program) {
119811             var typeChecker = program.getTypeChecker();
119812             var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
119813             var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
119814             var usedImports = [];
119815             for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
119816                 var importDecl = oldImports_1[_i];
119817                 var importClause = importDecl.importClause, moduleSpecifier = importDecl.moduleSpecifier;
119818                 if (!importClause) {
119819                     // Imports without import clauses are assumed to be included for their side effects and are not removed.
119820                     usedImports.push(importDecl);
119821                     continue;
119822                 }
119823                 var name = importClause.name, namedBindings = importClause.namedBindings;
119824                 // Default import
119825                 if (name && !isDeclarationUsed(name)) {
119826                     name = undefined;
119827                 }
119828                 if (namedBindings) {
119829                     if (ts.isNamespaceImport(namedBindings)) {
119830                         // Namespace import
119831                         if (!isDeclarationUsed(namedBindings.name)) {
119832                             namedBindings = undefined;
119833                         }
119834                     }
119835                     else {
119836                         // List of named imports
119837                         var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); });
119838                         if (newElements.length < namedBindings.elements.length) {
119839                             namedBindings = newElements.length
119840                                 ? ts.updateNamedImports(namedBindings, newElements)
119841                                 : undefined;
119842                         }
119843                     }
119844                 }
119845                 if (name || namedBindings) {
119846                     usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
119847                 }
119848                 // If a module is imported to be augmented, it’s used
119849                 else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) {
119850                     // If we’re in a declaration file, it’s safe to remove the import clause from it
119851                     if (sourceFile.isDeclarationFile) {
119852                         usedImports.push(ts.createImportDeclaration(importDecl.decorators, importDecl.modifiers, 
119853                         /*importClause*/ undefined, moduleSpecifier));
119854                     }
119855                     // If we’re not in a declaration file, we can’t remove the import clause even though
119856                     // the imported symbols are unused, because removing them makes it look like the import
119857                     // declaration has side effects, which will cause it to be preserved in the JS emit.
119858                     else {
119859                         usedImports.push(importDecl);
119860                     }
119861                 }
119862             }
119863             return usedImports;
119864             function isDeclarationUsed(identifier) {
119865                 // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed.
119866                 return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
119867             }
119868         }
119869         function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) {
119870             var moduleSpecifierText = ts.isStringLiteral(moduleSpecifier) && moduleSpecifier.text;
119871             return ts.isString(moduleSpecifierText) && ts.some(sourceFile.moduleAugmentations, function (moduleName) {
119872                 return ts.isStringLiteral(moduleName)
119873                     && moduleName.text === moduleSpecifierText;
119874             });
119875         }
119876         function getExternalModuleName(specifier) {
119877             return specifier !== undefined && ts.isStringLiteralLike(specifier)
119878                 ? specifier.text
119879                 : undefined;
119880         }
119881         // Internal for testing
119882         /**
119883          * @param importGroup a list of ImportDeclarations, all with the same module name.
119884          */
119885         function coalesceImports(importGroup) {
119886             var _a;
119887             if (importGroup.length === 0) {
119888                 return importGroup;
119889             }
119890             var _b = getCategorizedImports(importGroup), importWithoutClause = _b.importWithoutClause, typeOnlyImports = _b.typeOnlyImports, regularImports = _b.regularImports;
119891             var coalescedImports = [];
119892             if (importWithoutClause) {
119893                 coalescedImports.push(importWithoutClause);
119894             }
119895             for (var _i = 0, _c = [regularImports, typeOnlyImports]; _i < _c.length; _i++) {
119896                 var group_2 = _c[_i];
119897                 var isTypeOnly = group_2 === typeOnlyImports;
119898                 var defaultImports = group_2.defaultImports, namespaceImports = group_2.namespaceImports, namedImports = group_2.namedImports;
119899                 // Normally, we don't combine default and namespace imports, but it would be silly to
119900                 // produce two import declarations in this special case.
119901                 if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
119902                     // Add the namespace import to the existing default ImportDeclaration.
119903                     var defaultImport = defaultImports[0];
119904                     coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217
119905                     continue;
119906                 }
119907                 var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) {
119908                     return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name);
119909                 }); // TODO: GH#18217
119910                 for (var _d = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _d < sortedNamespaceImports_1.length; _d++) {
119911                     var namespaceImport = sortedNamespaceImports_1[_d];
119912                     // Drop the name, if any
119913                     coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217
119914                 }
119915                 if (defaultImports.length === 0 && namedImports.length === 0) {
119916                     continue;
119917                 }
119918                 var newDefaultImport = void 0;
119919                 var newImportSpecifiers = [];
119920                 if (defaultImports.length === 1) {
119921                     newDefaultImport = defaultImports[0].importClause.name;
119922                 }
119923                 else {
119924                     for (var _e = 0, defaultImports_1 = defaultImports; _e < defaultImports_1.length; _e++) {
119925                         var defaultImport = defaultImports_1[_e];
119926                         newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217
119927                     }
119928                 }
119929                 newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217
119930                 var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
119931                 var importDecl = defaultImports.length > 0
119932                     ? defaultImports[0]
119933                     : namedImports[0];
119934                 var newNamedImports = sortedImportSpecifiers.length === 0
119935                     ? newDefaultImport
119936                         ? undefined
119937                         : ts.createNamedImports(ts.emptyArray)
119938                     : namedImports.length === 0
119939                         ? ts.createNamedImports(sortedImportSpecifiers)
119940                         : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217
119941                 // Type-only imports are not allowed to mix default, namespace, and named imports in any combination.
119942                 // We could rewrite a default import as a named import (`import { default as name }`), but we currently
119943                 // choose not to as a stylistic preference.
119944                 if (isTypeOnly && newDefaultImport && newNamedImports) {
119945                     coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ undefined));
119946                     coalescedImports.push(updateImportDeclarationAndClause((_a = namedImports[0]) !== null && _a !== void 0 ? _a : importDecl, /*name*/ undefined, newNamedImports));
119947                 }
119948                 else {
119949                     coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
119950                 }
119951             }
119952             return coalescedImports;
119953         }
119954         OrganizeImports.coalesceImports = coalesceImports;
119955         /*
119956          * Returns entire import declarations because they may already have been rewritten and
119957          * may lack parent pointers.  The desired parts can easily be recovered based on the
119958          * categorization.
119959          *
119960          * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`.
119961          */
119962         function getCategorizedImports(importGroup) {
119963             var importWithoutClause;
119964             var typeOnlyImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
119965             var regularImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
119966             for (var _i = 0, importGroup_1 = importGroup; _i < importGroup_1.length; _i++) {
119967                 var importDeclaration = importGroup_1[_i];
119968                 if (importDeclaration.importClause === undefined) {
119969                     // Only the first such import is interesting - the others are redundant.
119970                     // Note: Unfortunately, we will lose trivia that was on this node.
119971                     importWithoutClause = importWithoutClause || importDeclaration;
119972                     continue;
119973                 }
119974                 var group_3 = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports;
119975                 var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
119976                 if (name) {
119977                     group_3.defaultImports.push(importDeclaration);
119978                 }
119979                 if (namedBindings) {
119980                     if (ts.isNamespaceImport(namedBindings)) {
119981                         group_3.namespaceImports.push(importDeclaration);
119982                     }
119983                     else {
119984                         group_3.namedImports.push(importDeclaration);
119985                     }
119986                 }
119987             }
119988             return {
119989                 importWithoutClause: importWithoutClause,
119990                 typeOnlyImports: typeOnlyImports,
119991                 regularImports: regularImports,
119992             };
119993         }
119994         // Internal for testing
119995         /**
119996          * @param exportGroup a list of ExportDeclarations, all with the same module name.
119997          */
119998         function coalesceExports(exportGroup) {
119999             if (exportGroup.length === 0) {
120000                 return exportGroup;
120001             }
120002             var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports, typeOnlyExports = _a.typeOnlyExports;
120003             var coalescedExports = [];
120004             if (exportWithoutClause) {
120005                 coalescedExports.push(exportWithoutClause);
120006             }
120007             for (var _i = 0, _b = [namedExports, typeOnlyExports]; _i < _b.length; _i++) {
120008                 var exportGroup_1 = _b[_i];
120009                 if (exportGroup_1.length === 0) {
120010                     continue;
120011                 }
120012                 var newExportSpecifiers = [];
120013                 newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(exportGroup_1, function (i) { return i.exportClause && ts.isNamedExports(i.exportClause) ? i.exportClause.elements : ts.emptyArray; }));
120014                 var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
120015                 var exportDecl = exportGroup_1[0];
120016                 coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ?
120017                     ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) :
120018                     ts.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.isTypeOnly));
120019             }
120020             return coalescedExports;
120021             /*
120022              * Returns entire export declarations because they may already have been rewritten and
120023              * may lack parent pointers.  The desired parts can easily be recovered based on the
120024              * categorization.
120025              */
120026             function getCategorizedExports(exportGroup) {
120027                 var exportWithoutClause;
120028                 var namedExports = [];
120029                 var typeOnlyExports = [];
120030                 for (var _i = 0, exportGroup_2 = exportGroup; _i < exportGroup_2.length; _i++) {
120031                     var exportDeclaration = exportGroup_2[_i];
120032                     if (exportDeclaration.exportClause === undefined) {
120033                         // Only the first such export is interesting - the others are redundant.
120034                         // Note: Unfortunately, we will lose trivia that was on this node.
120035                         exportWithoutClause = exportWithoutClause || exportDeclaration;
120036                     }
120037                     else if (exportDeclaration.isTypeOnly) {
120038                         typeOnlyExports.push(exportDeclaration);
120039                     }
120040                     else {
120041                         namedExports.push(exportDeclaration);
120042                     }
120043                 }
120044                 return {
120045                     exportWithoutClause: exportWithoutClause,
120046                     namedExports: namedExports,
120047                     typeOnlyExports: typeOnlyExports,
120048                 };
120049             }
120050         }
120051         OrganizeImports.coalesceExports = coalesceExports;
120052         function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
120053             return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings, importDeclaration.importClause.isTypeOnly), // TODO: GH#18217
120054             importDeclaration.moduleSpecifier);
120055         }
120056         function sortSpecifiers(specifiers) {
120057             return ts.stableSort(specifiers, function (s1, s2) {
120058                 return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
120059                     compareIdentifiers(s1.name, s2.name);
120060             });
120061         }
120062         /* internal */ // Exported for testing
120063         function compareModuleSpecifiers(m1, m2) {
120064             var name1 = getExternalModuleName(m1);
120065             var name2 = getExternalModuleName(m2);
120066             return ts.compareBooleans(name1 === undefined, name2 === undefined) ||
120067                 ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) ||
120068                 ts.compareStringsCaseInsensitive(name1, name2);
120069         }
120070         OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
120071         function compareIdentifiers(s1, s2) {
120072             return ts.compareStringsCaseInsensitive(s1.text, s2.text);
120073         }
120074     })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
120075 })(ts || (ts = {}));
120076 /* @internal */
120077 var ts;
120078 (function (ts) {
120079     var OutliningElementsCollector;
120080     (function (OutliningElementsCollector) {
120081         function collectElements(sourceFile, cancellationToken) {
120082             var res = [];
120083             addNodeOutliningSpans(sourceFile, cancellationToken, res);
120084             addRegionOutliningSpans(sourceFile, res);
120085             return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; });
120086         }
120087         OutliningElementsCollector.collectElements = collectElements;
120088         function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
120089             var depthRemaining = 40;
120090             var current = 0;
120091             // Includes the EOF Token so that comments which aren't attached to statements are included
120092             var statements = __spreadArrays(sourceFile.statements, [sourceFile.endOfFileToken]);
120093             var n = statements.length;
120094             while (current < n) {
120095                 while (current < n && !ts.isAnyImportSyntax(statements[current])) {
120096                     visitNonImportNode(statements[current]);
120097                     current++;
120098                 }
120099                 if (current === n)
120100                     break;
120101                 var firstImport = current;
120102                 while (current < n && ts.isAnyImportSyntax(statements[current])) {
120103                     addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
120104                     current++;
120105                 }
120106                 var lastImport = current - 1;
120107                 if (lastImport !== firstImport) {
120108                     out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 96 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
120109                 }
120110             }
120111             function visitNonImportNode(n) {
120112                 var _a;
120113                 if (depthRemaining === 0)
120114                     return;
120115                 cancellationToken.throwIfCancellationRequested();
120116                 if (ts.isDeclaration(n) || n.kind === 1 /* EndOfFileToken */) {
120117                     addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out);
120118                 }
120119                 if (isFunctionExpressionAssignedToVariable(n)) {
120120                     addOutliningForLeadingCommentsForNode(n.parent.parent.parent, sourceFile, cancellationToken, out);
120121                 }
120122                 var span = getOutliningSpanForNode(n, sourceFile);
120123                 if (span)
120124                     out.push(span);
120125                 depthRemaining--;
120126                 if (ts.isCallExpression(n)) {
120127                     depthRemaining++;
120128                     visitNonImportNode(n.expression);
120129                     depthRemaining--;
120130                     n.arguments.forEach(visitNonImportNode);
120131                     (_a = n.typeArguments) === null || _a === void 0 ? void 0 : _a.forEach(visitNonImportNode);
120132                 }
120133                 else if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
120134                     // Consider an 'else if' to be on the same depth as the 'if'.
120135                     visitNonImportNode(n.expression);
120136                     visitNonImportNode(n.thenStatement);
120137                     depthRemaining++;
120138                     visitNonImportNode(n.elseStatement);
120139                     depthRemaining--;
120140                 }
120141                 else {
120142                     n.forEachChild(visitNonImportNode);
120143                 }
120144                 depthRemaining++;
120145             }
120146             function isFunctionExpressionAssignedToVariable(n) {
120147                 if (!ts.isFunctionExpression(n) && !ts.isArrowFunction(n)) {
120148                     return false;
120149                 }
120150                 var ancestor = ts.findAncestor(n, ts.isVariableStatement);
120151                 return !!ancestor && ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration(ancestor) === n;
120152             }
120153         }
120154         function addRegionOutliningSpans(sourceFile, out) {
120155             var regions = [];
120156             var lineStarts = sourceFile.getLineStarts();
120157             for (var _i = 0, lineStarts_1 = lineStarts; _i < lineStarts_1.length; _i++) {
120158                 var currentLineStart = lineStarts_1[_i];
120159                 var lineEnd = sourceFile.getLineEndOfPosition(currentLineStart);
120160                 var lineText = sourceFile.text.substring(currentLineStart, lineEnd);
120161                 var result = isRegionDelimiter(lineText);
120162                 if (!result || ts.isInComment(sourceFile, currentLineStart)) {
120163                     continue;
120164                 }
120165                 if (!result[1]) {
120166                     var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
120167                     regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
120168                 }
120169                 else {
120170                     var region = regions.pop();
120171                     if (region) {
120172                         region.textSpan.length = lineEnd - region.textSpan.start;
120173                         region.hintSpan.length = lineEnd - region.textSpan.start;
120174                         out.push(region);
120175                     }
120176                 }
120177             }
120178         }
120179         var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/;
120180         function isRegionDelimiter(lineText) {
120181             return regionDelimiterRegExp.exec(lineText);
120182         }
120183         function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) {
120184             var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
120185             if (!comments)
120186                 return;
120187             var firstSingleLineCommentStart = -1;
120188             var lastSingleLineCommentEnd = -1;
120189             var singleLineCommentCount = 0;
120190             var sourceText = sourceFile.getFullText();
120191             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
120192                 var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
120193                 cancellationToken.throwIfCancellationRequested();
120194                 switch (kind) {
120195                     case 2 /* SingleLineCommentTrivia */:
120196                         // never fold region delimiters into single-line comment regions
120197                         var commentText = sourceText.slice(pos, end);
120198                         if (isRegionDelimiter(commentText)) {
120199                             combineAndAddMultipleSingleLineComments();
120200                             singleLineCommentCount = 0;
120201                             break;
120202                         }
120203                         // For single line comments, combine consecutive ones (2 or more) into
120204                         // a single span from the start of the first till the end of the last
120205                         if (singleLineCommentCount === 0) {
120206                             firstSingleLineCommentStart = pos;
120207                         }
120208                         lastSingleLineCommentEnd = end;
120209                         singleLineCommentCount++;
120210                         break;
120211                     case 3 /* MultiLineCommentTrivia */:
120212                         combineAndAddMultipleSingleLineComments();
120213                         out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
120214                         singleLineCommentCount = 0;
120215                         break;
120216                     default:
120217                         ts.Debug.assertNever(kind);
120218                 }
120219             }
120220             combineAndAddMultipleSingleLineComments();
120221             function combineAndAddMultipleSingleLineComments() {
120222                 // Only outline spans of two or more consecutive single line comments
120223                 if (singleLineCommentCount > 1) {
120224                     out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
120225                 }
120226             }
120227         }
120228         function createOutliningSpanFromBounds(pos, end, kind) {
120229             return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
120230         }
120231         function getOutliningSpanForNode(n, sourceFile) {
120232             switch (n.kind) {
120233                 case 223 /* Block */:
120234                     if (ts.isFunctionLike(n.parent)) {
120235                         return functionSpan(n.parent, n, sourceFile);
120236                     }
120237                     // Check if the block is standalone, or 'attached' to some parent statement.
120238                     // If the latter, we want to collapse the block, but consider its hint span
120239                     // to be the entire span of the parent.
120240                     switch (n.parent.kind) {
120241                         case 228 /* DoStatement */:
120242                         case 231 /* ForInStatement */:
120243                         case 232 /* ForOfStatement */:
120244                         case 230 /* ForStatement */:
120245                         case 227 /* IfStatement */:
120246                         case 229 /* WhileStatement */:
120247                         case 236 /* WithStatement */:
120248                         case 280 /* CatchClause */:
120249                             return spanForNode(n.parent);
120250                         case 240 /* TryStatement */:
120251                             // Could be the try-block, or the finally-block.
120252                             var tryStatement = n.parent;
120253                             if (tryStatement.tryBlock === n) {
120254                                 return spanForNode(n.parent);
120255                             }
120256                             else if (tryStatement.finallyBlock === n) {
120257                                 var node = ts.findChildOfKind(tryStatement, 92 /* FinallyKeyword */, sourceFile);
120258                                 if (node)
120259                                     return spanForNode(node);
120260                             }
120261                         // falls through
120262                         default:
120263                             // Block was a standalone block.  In this case we want to only collapse
120264                             // the span of the block, independent of any parent span.
120265                             return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
120266                     }
120267                 case 250 /* ModuleBlock */:
120268                     return spanForNode(n.parent);
120269                 case 245 /* ClassDeclaration */:
120270                 case 214 /* ClassExpression */:
120271                 case 246 /* InterfaceDeclaration */:
120272                 case 248 /* EnumDeclaration */:
120273                 case 251 /* CaseBlock */:
120274                 case 173 /* TypeLiteral */:
120275                     return spanForNode(n);
120276                 case 277 /* CaseClause */:
120277                 case 278 /* DefaultClause */:
120278                     return spanForNodeArray(n.statements);
120279                 case 193 /* ObjectLiteralExpression */:
120280                     return spanForObjectOrArrayLiteral(n);
120281                 case 192 /* ArrayLiteralExpression */:
120282                     return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */);
120283                 case 266 /* JsxElement */:
120284                     return spanForJSXElement(n);
120285                 case 270 /* JsxFragment */:
120286                     return spanForJSXFragment(n);
120287                 case 267 /* JsxSelfClosingElement */:
120288                 case 268 /* JsxOpeningElement */:
120289                     return spanForJSXAttributes(n.attributes);
120290                 case 211 /* TemplateExpression */:
120291                 case 14 /* NoSubstitutionTemplateLiteral */:
120292                     return spanForTemplateLiteral(n);
120293             }
120294             function spanForJSXElement(node) {
120295                 var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd());
120296                 var tagName = node.openingElement.tagName.getText(sourceFile);
120297                 var bannerText = "<" + tagName + ">...</" + tagName + ">";
120298                 return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText);
120299             }
120300             function spanForJSXFragment(node) {
120301                 var textSpan = ts.createTextSpanFromBounds(node.openingFragment.getStart(sourceFile), node.closingFragment.getEnd());
120302                 var bannerText = "<>...</>";
120303                 return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText);
120304             }
120305             function spanForJSXAttributes(node) {
120306                 if (node.properties.length === 0) {
120307                     return undefined;
120308                 }
120309                 return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
120310             }
120311             function spanForTemplateLiteral(node) {
120312                 if (node.kind === 14 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) {
120313                     return undefined;
120314                 }
120315                 return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
120316             }
120317             function spanForObjectOrArrayLiteral(node, open) {
120318                 if (open === void 0) { open = 18 /* OpenBraceToken */; }
120319                 // If the block has no leading keywords and is inside an array literal or call expression,
120320                 // we only want to collapse the span of the block.
120321                 // Otherwise, the collapsed section will include the end of the previous line.
120322                 return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent) && !ts.isCallExpression(node.parent), open);
120323             }
120324             function spanForNode(hintSpanNode, autoCollapse, useFullStart, open, close) {
120325                 if (autoCollapse === void 0) { autoCollapse = false; }
120326                 if (useFullStart === void 0) { useFullStart = true; }
120327                 if (open === void 0) { open = 18 /* OpenBraceToken */; }
120328                 if (close === void 0) { close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; }
120329                 var openToken = ts.findChildOfKind(n, open, sourceFile);
120330                 var closeToken = ts.findChildOfKind(n, close, sourceFile);
120331                 return openToken && closeToken && spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart);
120332             }
120333             function spanForNodeArray(nodeArray) {
120334                 return nodeArray.length ? createOutliningSpan(ts.createTextSpanFromRange(nodeArray), "code" /* Code */) : undefined;
120335             }
120336         }
120337         function functionSpan(node, body, sourceFile) {
120338             var openToken = ts.isNodeArrayMultiLine(node.parameters, sourceFile)
120339                 ? ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile)
120340                 : ts.findChildOfKind(body, 18 /* OpenBraceToken */, sourceFile);
120341             var closeToken = ts.findChildOfKind(body, 19 /* CloseBraceToken */, sourceFile);
120342             return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 202 /* ArrowFunction */);
120343         }
120344         function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart) {
120345             if (autoCollapse === void 0) { autoCollapse = false; }
120346             if (useFullStart === void 0) { useFullStart = true; }
120347             var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
120348             return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
120349         }
120350         function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
120351             if (hintSpan === void 0) { hintSpan = textSpan; }
120352             if (autoCollapse === void 0) { autoCollapse = false; }
120353             if (bannerText === void 0) { bannerText = "..."; }
120354             return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
120355         }
120356     })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
120357 })(ts || (ts = {}));
120358 /* @internal */
120359 var ts;
120360 (function (ts) {
120361     // Note(cyrusn): this enum is ordered from strongest match type to weakest match type.
120362     var PatternMatchKind;
120363     (function (PatternMatchKind) {
120364         PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact";
120365         PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix";
120366         PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring";
120367         PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase";
120368     })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {}));
120369     function createPatternMatch(kind, isCaseSensitive) {
120370         return {
120371             kind: kind,
120372             isCaseSensitive: isCaseSensitive
120373         };
120374     }
120375     function createPatternMatcher(pattern) {
120376         // We'll often see the same candidate string many times when searching (For example, when
120377         // we see the name of a module that is used everywhere, or the name of an overload).  As
120378         // such, we cache the information we compute about the candidate for the life of this
120379         // pattern matcher so we don't have to compute it multiple times.
120380         var stringToWordSpans = ts.createMap();
120381         var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); });
120382         // A segment is considered invalid if we couldn't find any words in it.
120383         if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; }))
120384             return undefined;
120385         return {
120386             getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); },
120387             getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); },
120388             patternContainsDots: dotSeparatedSegments.length > 1
120389         };
120390     }
120391     ts.createPatternMatcher = createPatternMatcher;
120392     function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) {
120393         // First, check that the last part of the dot separated pattern matches the name of the
120394         // candidate.  If not, then there's no point in proceeding and doing the more
120395         // expensive work.
120396         var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans);
120397         if (!candidateMatch) {
120398             return undefined;
120399         }
120400         // -1 because the last part was checked against the name, and only the rest
120401         // of the parts are checked against the container.
120402         if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
120403             // There weren't enough container parts to match against the pattern parts.
120404             // So this definitely doesn't match.
120405             return undefined;
120406         }
120407         var bestMatch;
120408         for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) {
120409             bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans));
120410         }
120411         return bestMatch;
120412     }
120413     function getWordSpans(word, stringToWordSpans) {
120414         var spans = stringToWordSpans.get(word);
120415         if (!spans) {
120416             stringToWordSpans.set(word, spans = breakIntoWordSpans(word));
120417         }
120418         return spans;
120419     }
120420     function matchTextChunk(candidate, chunk, stringToWordSpans) {
120421         var index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
120422         if (index === 0) {
120423             // a) Check if the word is a prefix of the candidate, in a case insensitive or
120424             //    sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match.
120425             return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
120426         }
120427         if (chunk.isLowerCase) {
120428             if (index === -1)
120429                 return undefined;
120430             // b) If the part is entirely lowercase, then check if it is contained anywhere in the
120431             //    candidate in a case insensitive manner.  If so, return that there was a substring
120432             //    match.
120433             //
120434             //    Note: We only have a substring match if the lowercase part is prefix match of some
120435             //    word part. That way we don't match something like 'Class' when the user types 'a'.
120436             //    But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
120437             var wordSpans = getWordSpans(candidate, stringToWordSpans);
120438             for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
120439                 var span = wordSpans_1[_i];
120440                 if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) {
120441                     return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false));
120442                 }
120443             }
120444             // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?
120445             // We could check every character boundary start of the candidate for the pattern. However, that's
120446             // an m * n operation in the wost case. Instead, find the first instance of the pattern
120447             // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
120448             // filter the list based on a substring that starts on a capital letter and also with a lowercase one.
120449             // (Pattern: fogbar, Candidate: quuxfogbarFogBar).
120450             if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) {
120451                 return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false);
120452             }
120453         }
120454         else {
120455             // d) If the part was not entirely lowercase, then check if it is contained in the
120456             //    candidate in a case *sensitive* manner. If so, return that there was a substring
120457             //    match.
120458             if (candidate.indexOf(chunk.text) > 0) {
120459                 return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true);
120460             }
120461             // e) If the part was not entirely lowercase, then attempt a camel cased match as well.
120462             if (chunk.characterSpans.length > 0) {
120463                 var candidateParts = getWordSpans(candidate, stringToWordSpans);
120464                 var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true
120465                     : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined;
120466                 if (isCaseSensitive !== undefined) {
120467                     return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive);
120468                 }
120469             }
120470         }
120471     }
120472     function matchSegment(candidate, segment, stringToWordSpans) {
120473         // First check if the segment matches as is.  This is also useful if the segment contains
120474         // characters we would normally strip when splitting into parts that we also may want to
120475         // match in the candidate.  For example if the segment is "@int" and the candidate is
120476         // "@int", then that will show up as an exact match here.
120477         //
120478         // Note: if the segment contains a space or an asterisk then we must assume that it's a
120479         // multi-word segment.
120480         if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) {
120481             var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans);
120482             if (match)
120483                 return match;
120484         }
120485         // The logic for pattern matching is now as follows:
120486         //
120487         // 1) Break the segment passed in into words.  Breaking is rather simple and a
120488         //    good way to think about it that if gives you all the individual alphanumeric words
120489         //    of the pattern.
120490         //
120491         // 2) For each word try to match the word against the candidate value.
120492         //
120493         // 3) Matching is as follows:
120494         //
120495         //   a) Check if the word is a prefix of the candidate, in a case insensitive or
120496         //      sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match.
120497         //
120498         //   If the word is entirely lowercase:
120499         //      b) Then check if it is contained anywhere in the
120500         //          candidate in a case insensitive manner.  If so, return that there was a substring
120501         //          match.
120502         //
120503         //          Note: We only have a substring match if the lowercase part is prefix match of
120504         //          some word part. That way we don't match something like 'Class' when the user
120505         //          types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with
120506         //          'a').
120507         //
120508         //       c) The word is all lower case. Is it a case insensitive substring of the candidate starting
120509         //          on a part boundary of the candidate?
120510         //
120511         //   Else:
120512         //       d) If the word was not entirely lowercase, then check if it is contained in the
120513         //          candidate in a case *sensitive* manner. If so, return that there was a substring
120514         //          match.
120515         //
120516         //       e) If the word was not entirely lowercase, then attempt a camel cased match as
120517         //          well.
120518         //
120519         // Only if all words have some sort of match is the pattern considered matched.
120520         var subWordTextChunks = segment.subWordTextChunks;
120521         var bestMatch;
120522         for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
120523             var subWordTextChunk = subWordTextChunks_1[_i];
120524             bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans));
120525         }
120526         return bestMatch;
120527     }
120528     function betterMatch(a, b) {
120529         return ts.min(a, b, compareMatches);
120530     }
120531     function compareMatches(a, b) {
120532         return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */
120533             : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive);
120534     }
120535     function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) {
120536         if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; }
120537         return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match.
120538             && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); });
120539     }
120540     function equalChars(ch1, ch2, ignoreCase) {
120541         return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2;
120542     }
120543     function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) {
120544         var chunkCharacterSpans = chunk.characterSpans;
120545         // Note: we may have more pattern parts than candidate parts.  This is because multiple
120546         // pattern parts may match a candidate part.  For example "SiUI" against "SimpleUI".
120547         // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI.  However, U
120548         // and I will both match in UI.
120549         var currentCandidate = 0;
120550         var currentChunkSpan = 0;
120551         var firstMatch;
120552         var contiguous;
120553         while (true) {
120554             // Let's consider our termination cases
120555             if (currentChunkSpan === chunkCharacterSpans.length) {
120556                 return true;
120557             }
120558             else if (currentCandidate === candidateParts.length) {
120559                 // No match, since we still have more of the pattern to hit
120560                 return false;
120561             }
120562             var candidatePart = candidateParts[currentCandidate];
120563             var gotOneMatchThisCandidate = false;
120564             // Consider the case of matching SiUI against SimpleUIElement. The candidate parts
120565             // will be Simple/UI/Element, and the pattern parts will be Si/U/I.  We'll match 'Si'
120566             // against 'Simple' first.  Then we'll match 'U' against 'UI'. However, we want to
120567             // still keep matching pattern parts against that candidate part.
120568             for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) {
120569                 var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
120570                 if (gotOneMatchThisCandidate) {
120571                     // We've already gotten one pattern part match in this candidate.  We will
120572                     // only continue trying to consumer pattern parts if the last part and this
120573                     // part are both upper case.
120574                     if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) ||
120575                         !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) {
120576                         break;
120577                     }
120578                 }
120579                 if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) {
120580                     break;
120581                 }
120582                 gotOneMatchThisCandidate = true;
120583                 firstMatch = firstMatch === undefined ? currentCandidate : firstMatch;
120584                 // If we were contiguous, then keep that value.  If we weren't, then keep that
120585                 // value.  If we don't know, then set the value to 'true' as an initial match is
120586                 // obviously contiguous.
120587                 contiguous = contiguous === undefined ? true : contiguous;
120588                 candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length);
120589             }
120590             // Check if we matched anything at all.  If we didn't, then we need to unset the
120591             // contiguous bit if we currently had it set.
120592             // If we haven't set the bit yet, then that means we haven't matched anything so
120593             // far, and we don't want to change that.
120594             if (!gotOneMatchThisCandidate && contiguous !== undefined) {
120595                 contiguous = false;
120596             }
120597             // Move onto the next candidate.
120598             currentCandidate++;
120599         }
120600     }
120601     function createSegment(text) {
120602         return {
120603             totalTextChunk: createTextChunk(text),
120604             subWordTextChunks: breakPatternIntoTextChunks(text)
120605         };
120606     }
120607     function isUpperCaseLetter(ch) {
120608         // Fast check for the ascii range.
120609         if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
120610             return true;
120611         }
120612         if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
120613             return false;
120614         }
120615         // TODO: find a way to determine this for any unicode characters in a
120616         // non-allocating manner.
120617         var str = String.fromCharCode(ch);
120618         return str === str.toUpperCase();
120619     }
120620     function isLowerCaseLetter(ch) {
120621         // Fast check for the ascii range.
120622         if (ch >= 97 /* a */ && ch <= 122 /* z */) {
120623             return true;
120624         }
120625         if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
120626             return false;
120627         }
120628         // TODO: find a way to determine this for any unicode characters in a
120629         // non-allocating manner.
120630         var str = String.fromCharCode(ch);
120631         return str === str.toLowerCase();
120632     }
120633     // Assumes 'value' is already lowercase.
120634     function indexOfIgnoringCase(str, value) {
120635         var n = str.length - value.length;
120636         var _loop_6 = function (start) {
120637             if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
120638                 return { value: start };
120639             }
120640         };
120641         for (var start = 0; start <= n; start++) {
120642             var state_1 = _loop_6(start);
120643             if (typeof state_1 === "object")
120644                 return state_1.value;
120645         }
120646         return -1;
120647     }
120648     function toLowerCase(ch) {
120649         // Fast convert for the ascii range.
120650         if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
120651             return 97 /* a */ + (ch - 65 /* A */);
120652         }
120653         if (ch < 127 /* maxAsciiCharacter */) {
120654             return ch;
120655         }
120656         // TODO: find a way to compute this for any unicode characters in a
120657         // non-allocating manner.
120658         return String.fromCharCode(ch).toLowerCase().charCodeAt(0);
120659     }
120660     function isDigit(ch) {
120661         // TODO(cyrusn): Find a way to support this for unicode digits.
120662         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
120663     }
120664     function isWordChar(ch) {
120665         return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */;
120666     }
120667     function breakPatternIntoTextChunks(pattern) {
120668         var result = [];
120669         var wordStart = 0;
120670         var wordLength = 0;
120671         for (var i = 0; i < pattern.length; i++) {
120672             var ch = pattern.charCodeAt(i);
120673             if (isWordChar(ch)) {
120674                 if (wordLength === 0) {
120675                     wordStart = i;
120676                 }
120677                 wordLength++;
120678             }
120679             else {
120680                 if (wordLength > 0) {
120681                     result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
120682                     wordLength = 0;
120683                 }
120684             }
120685         }
120686         if (wordLength > 0) {
120687             result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
120688         }
120689         return result;
120690     }
120691     function createTextChunk(text) {
120692         var textLowerCase = text.toLowerCase();
120693         return {
120694             text: text,
120695             textLowerCase: textLowerCase,
120696             isLowerCase: text === textLowerCase,
120697             characterSpans: breakIntoCharacterSpans(text)
120698         };
120699     }
120700     function breakIntoCharacterSpans(identifier) {
120701         return breakIntoSpans(identifier, /*word:*/ false);
120702     }
120703     ts.breakIntoCharacterSpans = breakIntoCharacterSpans;
120704     function breakIntoWordSpans(identifier) {
120705         return breakIntoSpans(identifier, /*word:*/ true);
120706     }
120707     ts.breakIntoWordSpans = breakIntoWordSpans;
120708     function breakIntoSpans(identifier, word) {
120709         var result = [];
120710         var wordStart = 0;
120711         for (var i = 1; i < identifier.length; i++) {
120712             var lastIsDigit = isDigit(identifier.charCodeAt(i - 1));
120713             var currentIsDigit = isDigit(identifier.charCodeAt(i));
120714             var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
120715             var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart);
120716             if (charIsPunctuation(identifier.charCodeAt(i - 1)) ||
120717                 charIsPunctuation(identifier.charCodeAt(i)) ||
120718                 lastIsDigit !== currentIsDigit ||
120719                 hasTransitionFromLowerToUpper ||
120720                 hasTransitionFromUpperToLower) {
120721                 if (!isAllPunctuation(identifier, wordStart, i)) {
120722                     result.push(ts.createTextSpan(wordStart, i - wordStart));
120723                 }
120724                 wordStart = i;
120725             }
120726         }
120727         if (!isAllPunctuation(identifier, wordStart, identifier.length)) {
120728             result.push(ts.createTextSpan(wordStart, identifier.length - wordStart));
120729         }
120730         return result;
120731     }
120732     function charIsPunctuation(ch) {
120733         switch (ch) {
120734             case 33 /* exclamation */:
120735             case 34 /* doubleQuote */:
120736             case 35 /* hash */:
120737             case 37 /* percent */:
120738             case 38 /* ampersand */:
120739             case 39 /* singleQuote */:
120740             case 40 /* openParen */:
120741             case 41 /* closeParen */:
120742             case 42 /* asterisk */:
120743             case 44 /* comma */:
120744             case 45 /* minus */:
120745             case 46 /* dot */:
120746             case 47 /* slash */:
120747             case 58 /* colon */:
120748             case 59 /* semicolon */:
120749             case 63 /* question */:
120750             case 64 /* at */:
120751             case 91 /* openBracket */:
120752             case 92 /* backslash */:
120753             case 93 /* closeBracket */:
120754             case 95 /* _ */:
120755             case 123 /* openBrace */:
120756             case 125 /* closeBrace */:
120757                 return true;
120758         }
120759         return false;
120760     }
120761     function isAllPunctuation(identifier, start, end) {
120762         return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end);
120763     }
120764     function transitionFromUpperToLower(identifier, index, wordStart) {
120765         // Cases this supports:
120766         // 1) IDisposable -> I, Disposable
120767         // 2) UIElement -> UI, Element
120768         // 3) HTMLDocument -> HTML, Document
120769         //
120770         // etc.
120771         // We have a transition from an upper to a lower letter here.  But we only
120772         // want to break if all the letters that preceded are uppercase.  i.e. if we
120773         // have "Foo" we don't want to break that into "F, oo".  But if we have
120774         // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI,
120775         // Foo".  i.e. the last uppercase letter belongs to the lowercase letters
120776         // that follows.  Note: this will make the following not split properly:
120777         // "HELLOthere".  However, these sorts of names do not show up in .Net
120778         // programs.
120779         return index !== wordStart
120780             && index + 1 < identifier.length
120781             && isUpperCaseLetter(identifier.charCodeAt(index))
120782             && isLowerCaseLetter(identifier.charCodeAt(index + 1))
120783             && every(identifier, isUpperCaseLetter, wordStart, index);
120784     }
120785     function transitionFromLowerToUpper(identifier, word, index) {
120786         var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1));
120787         var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
120788         // See if the casing indicates we're starting a new word. Note: if we're breaking on
120789         // words, then just seeing an upper case character isn't enough.  Instead, it has to
120790         // be uppercase and the previous character can't be uppercase.
120791         //
120792         // For example, breaking "AddMetadata" on words would make: Add Metadata
120793         //
120794         // on characters would be: A dd M etadata
120795         //
120796         // Break "AM" on words would be: AM
120797         //
120798         // on characters would be: A M
120799         //
120800         // We break the search string on characters.  But we break the symbol name on words.
120801         return currentIsUpper && (!word || !lastIsUpper);
120802     }
120803     function everyInRange(start, end, pred) {
120804         for (var i = start; i < end; i++) {
120805             if (!pred(i)) {
120806                 return false;
120807             }
120808         }
120809         return true;
120810     }
120811     function every(s, pred, start, end) {
120812         if (start === void 0) { start = 0; }
120813         if (end === void 0) { end = s.length; }
120814         return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); });
120815     }
120816 })(ts || (ts = {}));
120817 var ts;
120818 (function (ts) {
120819     function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
120820         if (readImportFiles === void 0) { readImportFiles = true; }
120821         if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
120822         var pragmaContext = {
120823             languageVersion: 1 /* ES5 */,
120824             pragmas: undefined,
120825             checkJsDirective: undefined,
120826             referencedFiles: [],
120827             typeReferenceDirectives: [],
120828             libReferenceDirectives: [],
120829             amdDependencies: [],
120830             hasNoDefaultLib: undefined,
120831             moduleName: undefined
120832         };
120833         var importedFiles = [];
120834         var ambientExternalModules;
120835         var lastToken;
120836         var currentToken;
120837         var braceNesting = 0;
120838         // assume that text represent an external module if it contains at least one top level import/export
120839         // ambient modules that are found inside external modules are interpreted as module augmentations
120840         var externalModule = false;
120841         function nextToken() {
120842             lastToken = currentToken;
120843             currentToken = ts.scanner.scan();
120844             if (currentToken === 18 /* OpenBraceToken */) {
120845                 braceNesting++;
120846             }
120847             else if (currentToken === 19 /* CloseBraceToken */) {
120848                 braceNesting--;
120849             }
120850             return currentToken;
120851         }
120852         function getFileReference() {
120853             var fileName = ts.scanner.getTokenValue();
120854             var pos = ts.scanner.getTokenPos();
120855             return { fileName: fileName, pos: pos, end: pos + fileName.length };
120856         }
120857         function recordAmbientExternalModule() {
120858             if (!ambientExternalModules) {
120859                 ambientExternalModules = [];
120860             }
120861             ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
120862         }
120863         function recordModuleName() {
120864             importedFiles.push(getFileReference());
120865             markAsExternalModuleIfTopLevel();
120866         }
120867         function markAsExternalModuleIfTopLevel() {
120868             if (braceNesting === 0) {
120869                 externalModule = true;
120870             }
120871         }
120872         /**
120873          * Returns true if at least one token was consumed from the stream
120874          */
120875         function tryConsumeDeclare() {
120876             var token = ts.scanner.getToken();
120877             if (token === 130 /* DeclareKeyword */) {
120878                 // declare module "mod"
120879                 token = nextToken();
120880                 if (token === 135 /* ModuleKeyword */) {
120881                     token = nextToken();
120882                     if (token === 10 /* StringLiteral */) {
120883                         recordAmbientExternalModule();
120884                     }
120885                 }
120886                 return true;
120887             }
120888             return false;
120889         }
120890         /**
120891          * Returns true if at least one token was consumed from the stream
120892          */
120893         function tryConsumeImport() {
120894             if (lastToken === 24 /* DotToken */) {
120895                 return false;
120896             }
120897             var token = ts.scanner.getToken();
120898             if (token === 96 /* ImportKeyword */) {
120899                 token = nextToken();
120900                 if (token === 20 /* OpenParenToken */) {
120901                     token = nextToken();
120902                     if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) {
120903                         // import("mod");
120904                         recordModuleName();
120905                         return true;
120906                     }
120907                 }
120908                 else if (token === 10 /* StringLiteral */) {
120909                     // import "mod";
120910                     recordModuleName();
120911                     return true;
120912                 }
120913                 else {
120914                     if (token === 145 /* TypeKeyword */) {
120915                         var skipTypeKeyword = ts.scanner.lookAhead(function () {
120916                             var token = ts.scanner.scan();
120917                             return token !== 149 /* FromKeyword */ && (token === 41 /* AsteriskToken */ ||
120918                                 token === 18 /* OpenBraceToken */ ||
120919                                 token === 75 /* Identifier */ ||
120920                                 ts.isKeyword(token));
120921                         });
120922                         if (skipTypeKeyword) {
120923                             token = nextToken();
120924                         }
120925                     }
120926                     if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
120927                         token = nextToken();
120928                         if (token === 149 /* FromKeyword */) {
120929                             token = nextToken();
120930                             if (token === 10 /* StringLiteral */) {
120931                                 // import d from "mod";
120932                                 recordModuleName();
120933                                 return true;
120934                             }
120935                         }
120936                         else if (token === 62 /* EqualsToken */) {
120937                             if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
120938                                 return true;
120939                             }
120940                         }
120941                         else if (token === 27 /* CommaToken */) {
120942                             // consume comma and keep going
120943                             token = nextToken();
120944                         }
120945                         else {
120946                             // unknown syntax
120947                             return true;
120948                         }
120949                     }
120950                     if (token === 18 /* OpenBraceToken */) {
120951                         token = nextToken();
120952                         // consume "{ a as B, c, d as D}" clauses
120953                         // make sure that it stops on EOF
120954                         while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
120955                             token = nextToken();
120956                         }
120957                         if (token === 19 /* CloseBraceToken */) {
120958                             token = nextToken();
120959                             if (token === 149 /* FromKeyword */) {
120960                                 token = nextToken();
120961                                 if (token === 10 /* StringLiteral */) {
120962                                     // import {a as A} from "mod";
120963                                     // import d, {a, b as B} from "mod"
120964                                     recordModuleName();
120965                                 }
120966                             }
120967                         }
120968                     }
120969                     else if (token === 41 /* AsteriskToken */) {
120970                         token = nextToken();
120971                         if (token === 123 /* AsKeyword */) {
120972                             token = nextToken();
120973                             if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
120974                                 token = nextToken();
120975                                 if (token === 149 /* FromKeyword */) {
120976                                     token = nextToken();
120977                                     if (token === 10 /* StringLiteral */) {
120978                                         // import * as NS from "mod"
120979                                         // import d, * as NS from "mod"
120980                                         recordModuleName();
120981                                     }
120982                                 }
120983                             }
120984                         }
120985                     }
120986                 }
120987                 return true;
120988             }
120989             return false;
120990         }
120991         function tryConsumeExport() {
120992             var token = ts.scanner.getToken();
120993             if (token === 89 /* ExportKeyword */) {
120994                 markAsExternalModuleIfTopLevel();
120995                 token = nextToken();
120996                 if (token === 145 /* TypeKeyword */) {
120997                     var skipTypeKeyword = ts.scanner.lookAhead(function () {
120998                         var token = ts.scanner.scan();
120999                         return token === 41 /* AsteriskToken */ ||
121000                             token === 18 /* OpenBraceToken */;
121001                     });
121002                     if (skipTypeKeyword) {
121003                         token = nextToken();
121004                     }
121005                 }
121006                 if (token === 18 /* OpenBraceToken */) {
121007                     token = nextToken();
121008                     // consume "{ a as B, c, d as D}" clauses
121009                     // make sure it stops on EOF
121010                     while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
121011                         token = nextToken();
121012                     }
121013                     if (token === 19 /* CloseBraceToken */) {
121014                         token = nextToken();
121015                         if (token === 149 /* FromKeyword */) {
121016                             token = nextToken();
121017                             if (token === 10 /* StringLiteral */) {
121018                                 // export {a as A} from "mod";
121019                                 // export {a, b as B} from "mod"
121020                                 recordModuleName();
121021                             }
121022                         }
121023                     }
121024                 }
121025                 else if (token === 41 /* AsteriskToken */) {
121026                     token = nextToken();
121027                     if (token === 149 /* FromKeyword */) {
121028                         token = nextToken();
121029                         if (token === 10 /* StringLiteral */) {
121030                             // export * from "mod"
121031                             recordModuleName();
121032                         }
121033                     }
121034                 }
121035                 else if (token === 96 /* ImportKeyword */) {
121036                     token = nextToken();
121037                     if (token === 145 /* TypeKeyword */) {
121038                         var skipTypeKeyword = ts.scanner.lookAhead(function () {
121039                             var token = ts.scanner.scan();
121040                             return token === 75 /* Identifier */ ||
121041                                 ts.isKeyword(token);
121042                         });
121043                         if (skipTypeKeyword) {
121044                             token = nextToken();
121045                         }
121046                     }
121047                     if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
121048                         token = nextToken();
121049                         if (token === 62 /* EqualsToken */) {
121050                             if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
121051                                 return true;
121052                             }
121053                         }
121054                     }
121055                 }
121056                 return true;
121057             }
121058             return false;
121059         }
121060         function tryConsumeRequireCall(skipCurrentToken, allowTemplateLiterals) {
121061             if (allowTemplateLiterals === void 0) { allowTemplateLiterals = false; }
121062             var token = skipCurrentToken ? nextToken() : ts.scanner.getToken();
121063             if (token === 139 /* RequireKeyword */) {
121064                 token = nextToken();
121065                 if (token === 20 /* OpenParenToken */) {
121066                     token = nextToken();
121067                     if (token === 10 /* StringLiteral */ ||
121068                         allowTemplateLiterals && token === 14 /* NoSubstitutionTemplateLiteral */) {
121069                         //  require("mod");
121070                         recordModuleName();
121071                     }
121072                 }
121073                 return true;
121074             }
121075             return false;
121076         }
121077         function tryConsumeDefine() {
121078             var token = ts.scanner.getToken();
121079             if (token === 75 /* Identifier */ && ts.scanner.getTokenValue() === "define") {
121080                 token = nextToken();
121081                 if (token !== 20 /* OpenParenToken */) {
121082                     return true;
121083                 }
121084                 token = nextToken();
121085                 if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) {
121086                     // looks like define ("modname", ... - skip string literal and comma
121087                     token = nextToken();
121088                     if (token === 27 /* CommaToken */) {
121089                         token = nextToken();
121090                     }
121091                     else {
121092                         // unexpected token
121093                         return true;
121094                     }
121095                 }
121096                 // should be start of dependency list
121097                 if (token !== 22 /* OpenBracketToken */) {
121098                     return true;
121099                 }
121100                 // skip open bracket
121101                 token = nextToken();
121102                 // scan until ']' or EOF
121103                 while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) {
121104                     // record string literals as module names
121105                     if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) {
121106                         recordModuleName();
121107                     }
121108                     token = nextToken();
121109                 }
121110                 return true;
121111             }
121112             return false;
121113         }
121114         function processImports() {
121115             ts.scanner.setText(sourceText);
121116             nextToken();
121117             // Look for:
121118             //    import "mod";
121119             //    import d from "mod"
121120             //    import {a as A } from "mod";
121121             //    import * as NS from "mod"
121122             //    import d, {a, b as B} from "mod"
121123             //    import i = require("mod");
121124             //    import("mod");
121125             //    export * from "mod"
121126             //    export {a as b} from "mod"
121127             //    export import i = require("mod")
121128             //    (for JavaScript files) require("mod")
121129             // Do not look for:
121130             //    AnySymbol.import("mod")
121131             //    AnySymbol.nested.import("mod")
121132             while (true) {
121133                 if (ts.scanner.getToken() === 1 /* EndOfFileToken */) {
121134                     break;
121135                 }
121136                 // check if at least one of alternative have moved scanner forward
121137                 if (tryConsumeDeclare() ||
121138                     tryConsumeImport() ||
121139                     tryConsumeExport() ||
121140                     (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false, /*allowTemplateLiterals*/ true) ||
121141                         tryConsumeDefine()))) {
121142                     continue;
121143                 }
121144                 else {
121145                     nextToken();
121146                 }
121147             }
121148             ts.scanner.setText(undefined);
121149         }
121150         if (readImportFiles) {
121151             processImports();
121152         }
121153         ts.processCommentPragmas(pragmaContext, sourceText);
121154         ts.processPragmasIntoFields(pragmaContext, ts.noop);
121155         if (externalModule) {
121156             // for external modules module all nested ambient modules are augmentations
121157             if (ambientExternalModules) {
121158                 // move all detected ambient modules to imported files since they need to be resolved
121159                 for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) {
121160                     var decl = ambientExternalModules_1[_i];
121161                     importedFiles.push(decl.ref);
121162                 }
121163             }
121164             return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined };
121165         }
121166         else {
121167             // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
121168             var ambientModuleNames = void 0;
121169             if (ambientExternalModules) {
121170                 for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) {
121171                     var decl = ambientExternalModules_2[_a];
121172                     if (decl.depth === 0) {
121173                         if (!ambientModuleNames) {
121174                             ambientModuleNames = [];
121175                         }
121176                         ambientModuleNames.push(decl.ref.fileName);
121177                     }
121178                     else {
121179                         importedFiles.push(decl.ref);
121180                     }
121181                 }
121182             }
121183             return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
121184         }
121185     }
121186     ts.preProcessFile = preProcessFile;
121187 })(ts || (ts = {}));
121188 /* @internal */
121189 var ts;
121190 (function (ts) {
121191     var Rename;
121192     (function (Rename) {
121193         function getRenameInfo(program, sourceFile, position, options) {
121194             var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position));
121195             if (nodeIsEligibleForRename(node)) {
121196                 var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options);
121197                 if (renameInfo) {
121198                     return renameInfo;
121199                 }
121200             }
121201             return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element);
121202         }
121203         Rename.getRenameInfo = getRenameInfo;
121204         function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) {
121205             var symbol = typeChecker.getSymbolAtLocation(node);
121206             if (!symbol)
121207                 return;
121208             // Only allow a symbol to be renamed if it actually has at least one declaration.
121209             var declarations = symbol.declarations;
121210             if (!declarations || declarations.length === 0)
121211                 return;
121212             // Disallow rename for elements that are defined in the standard TypeScript library.
121213             if (declarations.some(isDefinedInLibraryFile)) {
121214                 return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
121215             }
121216             // Cannot rename `default` as in `import { default as foo } from "./someModule";
121217             if (ts.isIdentifier(node) && node.originalKeywordKind === 84 /* DefaultKeyword */ && symbol.parent && symbol.parent.flags & 1536 /* Module */) {
121218                 return undefined;
121219             }
121220             if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) {
121221                 return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined;
121222             }
121223             var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
121224             var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 154 /* ComputedPropertyName */)
121225                 ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
121226                 : undefined;
121227             var displayName = specifierName || typeChecker.symbolToString(symbol);
121228             var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
121229             return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
121230         }
121231         function getRenameInfoForModule(node, sourceFile, moduleSymbol) {
121232             if (!ts.isExternalModuleNameRelative(node.text)) {
121233                 return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import);
121234             }
121235             var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile);
121236             if (!moduleSourceFile)
121237                 return undefined;
121238             var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index");
121239             var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex;
121240             var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */;
121241             var indexAfterLastSlash = node.text.lastIndexOf("/") + 1;
121242             // Span should only be the last component of the path. + 1 to account for the quote character.
121243             var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash);
121244             return {
121245                 canRename: true,
121246                 fileToRename: name,
121247                 kind: kind,
121248                 displayName: name,
121249                 fullDisplayName: name,
121250                 kindModifiers: "" /* none */,
121251                 triggerSpan: triggerSpan,
121252             };
121253         }
121254         function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
121255             return {
121256                 canRename: true,
121257                 fileToRename: undefined,
121258                 kind: kind,
121259                 displayName: displayName,
121260                 fullDisplayName: fullDisplayName,
121261                 kindModifiers: kindModifiers,
121262                 triggerSpan: createTriggerSpanForNode(node, sourceFile)
121263             };
121264         }
121265         function getRenameInfoError(diagnostic) {
121266             return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) };
121267         }
121268         function createTriggerSpanForNode(node, sourceFile) {
121269             var start = node.getStart(sourceFile);
121270             var width = node.getWidth(sourceFile);
121271             if (ts.isStringLiteralLike(node)) {
121272                 // Exclude the quotes
121273                 start += 1;
121274                 width -= 2;
121275             }
121276             return ts.createTextSpan(start, width);
121277         }
121278         function nodeIsEligibleForRename(node) {
121279             switch (node.kind) {
121280                 case 75 /* Identifier */:
121281                 case 76 /* PrivateIdentifier */:
121282                 case 10 /* StringLiteral */:
121283                 case 14 /* NoSubstitutionTemplateLiteral */:
121284                 case 104 /* ThisKeyword */:
121285                     return true;
121286                 case 8 /* NumericLiteral */:
121287                     return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node);
121288                 default:
121289                     return false;
121290             }
121291         }
121292     })(Rename = ts.Rename || (ts.Rename = {}));
121293 })(ts || (ts = {}));
121294 /* @internal */
121295 var ts;
121296 (function (ts) {
121297     var SmartSelectionRange;
121298     (function (SmartSelectionRange) {
121299         function getSmartSelectionRange(pos, sourceFile) {
121300             var selectionRange = {
121301                 textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd())
121302             };
121303             var parentNode = sourceFile;
121304             outer: while (true) {
121305                 var children = getSelectionChildren(parentNode);
121306                 if (!children.length)
121307                     break;
121308                 for (var i = 0; i < children.length; i++) {
121309                     var prevNode = children[i - 1];
121310                     var node = children[i];
121311                     var nextNode = children[i + 1];
121312                     if (node.getStart(sourceFile) > pos) {
121313                         break outer;
121314                     }
121315                     if (positionShouldSnapToNode(sourceFile, pos, node)) {
121316                         // 1. Blocks are effectively redundant with SyntaxLists.
121317                         // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping
121318                         //    of things that should be considered independently.
121319                         // 3. A VariableStatement’s children are just a VaraiableDeclarationList and a semicolon.
121320                         // 4. A lone VariableDeclaration in a VaraibleDeclaration feels redundant with the VariableStatement.
121321                         //
121322                         // Dive in without pushing a selection range.
121323                         if (ts.isBlock(node)
121324                             || ts.isTemplateSpan(node) || ts.isTemplateHead(node) || ts.isTemplateTail(node)
121325                             || prevNode && ts.isTemplateHead(prevNode)
121326                             || ts.isVariableDeclarationList(node) && ts.isVariableStatement(parentNode)
121327                             || ts.isSyntaxList(node) && ts.isVariableDeclarationList(parentNode)
121328                             || ts.isVariableDeclaration(node) && ts.isSyntaxList(parentNode) && children.length === 1) {
121329                             parentNode = node;
121330                             break;
121331                         }
121332                         // Synthesize a stop for '${ ... }' since '${' and '}' actually belong to siblings.
121333                         if (ts.isTemplateSpan(parentNode) && nextNode && ts.isTemplateMiddleOrTemplateTail(nextNode)) {
121334                             var start_2 = node.getFullStart() - "${".length;
121335                             var end_2 = nextNode.getStart() + "}".length;
121336                             pushSelectionRange(start_2, end_2);
121337                         }
121338                         // Blocks with braces, brackets, parens, or JSX tags on separate lines should be
121339                         // selected from open to close, including whitespace but not including the braces/etc. themselves.
121340                         var isBetweenMultiLineBookends = ts.isSyntaxList(node)
121341                             && isListOpener(prevNode)
121342                             && isListCloser(nextNode)
121343                             && !ts.positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile);
121344                         var jsDocCommentStart = ts.hasJSDocNodes(node) && node.jsDoc[0].getStart();
121345                         var start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart();
121346                         var end = isBetweenMultiLineBookends ? nextNode.getStart() : node.getEnd();
121347                         if (ts.isNumber(jsDocCommentStart)) {
121348                             pushSelectionRange(jsDocCommentStart, end);
121349                         }
121350                         pushSelectionRange(start, end);
121351                         // String literals should have a stop both inside and outside their quotes.
121352                         if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) {
121353                             pushSelectionRange(start + 1, end - 1);
121354                         }
121355                         parentNode = node;
121356                         break;
121357                     }
121358                     // If we made it to the end of the for loop, we’re done.
121359                     // In practice, I’ve only seen this happen at the very end
121360                     // of a SourceFile.
121361                     if (i === children.length - 1) {
121362                         break outer;
121363                     }
121364                 }
121365             }
121366             return selectionRange;
121367             function pushSelectionRange(start, end) {
121368                 // Skip empty ranges
121369                 if (start !== end) {
121370                     var textSpan = ts.createTextSpanFromBounds(start, end);
121371                     if (!selectionRange || (
121372                     // Skip ranges that are identical to the parent
121373                     !ts.textSpansEqual(textSpan, selectionRange.textSpan) &&
121374                         // Skip ranges that don’t contain the original position
121375                         ts.textSpanIntersectsWithPosition(textSpan, pos))) {
121376                         selectionRange = __assign({ textSpan: textSpan }, selectionRange && { parent: selectionRange });
121377                     }
121378                 }
121379             }
121380         }
121381         SmartSelectionRange.getSmartSelectionRange = getSmartSelectionRange;
121382         /**
121383          * Like `ts.positionBelongsToNode`, except positions immediately after nodes
121384          * count too, unless that position belongs to the next node. In effect, makes
121385          * selections able to snap to preceding tokens when the cursor is on the tail
121386          * end of them with only whitespace ahead.
121387          * @param sourceFile The source file containing the nodes.
121388          * @param pos The position to check.
121389          * @param node The candidate node to snap to.
121390          */
121391         function positionShouldSnapToNode(sourceFile, pos, node) {
121392             // Can’t use 'ts.positionBelongsToNode()' here because it cleverly accounts
121393             // for missing nodes, which can’t really be considered when deciding what
121394             // to select.
121395             ts.Debug.assert(node.pos <= pos);
121396             if (pos < node.end) {
121397                 return true;
121398             }
121399             var nodeEnd = node.getEnd();
121400             if (nodeEnd === pos) {
121401                 return ts.getTouchingPropertyName(sourceFile, pos).pos < node.end;
121402             }
121403             return false;
121404         }
121405         var isImport = ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration);
121406         /**
121407          * Gets the children of a node to be considered for selection ranging,
121408          * transforming them into an artificial tree according to their intuitive
121409          * grouping where no grouping actually exists in the parse tree. For example,
121410          * top-level imports are grouped into their own SyntaxList so they can be
121411          * selected all together, even though in the AST they’re just siblings of each
121412          * other as well as of other top-level statements and declarations.
121413          */
121414         function getSelectionChildren(node) {
121415             // Group top-level imports
121416             if (ts.isSourceFile(node)) {
121417                 return groupChildren(node.getChildAt(0).getChildren(), isImport);
121418             }
121419             // Mapped types _look_ like ObjectTypes with a single member,
121420             // but in fact don’t contain a SyntaxList or a node containing
121421             // the “key/value” pair like ObjectTypes do, but it seems intuitive
121422             // that the selection would snap to those points. The philosophy
121423             // of choosing a selection range is not so much about what the
121424             // syntax currently _is_ as what the syntax might easily become
121425             // if the user is making a selection; e.g., we synthesize a selection
121426             // around the “key/value” pair not because there’s a node there, but
121427             // because it allows the mapped type to become an object type with a
121428             // few keystrokes.
121429             if (ts.isMappedTypeNode(node)) {
121430                 var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1);
121431                 var closeBraceToken = ts.Debug.checkDefined(children.pop());
121432                 ts.Debug.assertEqual(openBraceToken.kind, 18 /* OpenBraceToken */);
121433                 ts.Debug.assertEqual(closeBraceToken.kind, 19 /* CloseBraceToken */);
121434                 // Group `-/+readonly` and `-/+?`
121435                 var groupedWithPlusMinusTokens = groupChildren(children, function (child) {
121436                     return child === node.readonlyToken || child.kind === 138 /* ReadonlyKeyword */ ||
121437                         child === node.questionToken || child.kind === 57 /* QuestionToken */;
121438                 });
121439                 // Group type parameter with surrounding brackets
121440                 var groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, function (_a) {
121441                     var kind = _a.kind;
121442                     return kind === 22 /* OpenBracketToken */ ||
121443                         kind === 155 /* TypeParameter */ ||
121444                         kind === 23 /* CloseBracketToken */;
121445                 });
121446                 return [
121447                     openBraceToken,
121448                     // Pivot on `:`
121449                     createSyntaxList(splitChildren(groupedWithBrackets, function (_a) {
121450                         var kind = _a.kind;
121451                         return kind === 58 /* ColonToken */;
121452                     })),
121453                     closeBraceToken,
121454                 ];
121455             }
121456             // Group modifiers and property name, then pivot on `:`.
121457             if (ts.isPropertySignature(node)) {
121458                 var children = groupChildren(node.getChildren(), function (child) {
121459                     return child === node.name || ts.contains(node.modifiers, child);
121460                 });
121461                 return splitChildren(children, function (_a) {
121462                     var kind = _a.kind;
121463                     return kind === 58 /* ColonToken */;
121464                 });
121465             }
121466             // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`.
121467             if (ts.isParameter(node)) {
121468                 var groupedDotDotDotAndName_1 = groupChildren(node.getChildren(), function (child) {
121469                     return child === node.dotDotDotToken || child === node.name;
121470                 });
121471                 var groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName_1, function (child) {
121472                     return child === groupedDotDotDotAndName_1[0] || child === node.questionToken;
121473                 });
121474                 return splitChildren(groupedWithQuestionToken, function (_a) {
121475                     var kind = _a.kind;
121476                     return kind === 62 /* EqualsToken */;
121477                 });
121478             }
121479             // Pivot on '='
121480             if (ts.isBindingElement(node)) {
121481                 return splitChildren(node.getChildren(), function (_a) {
121482                     var kind = _a.kind;
121483                     return kind === 62 /* EqualsToken */;
121484                 });
121485             }
121486             return node.getChildren();
121487         }
121488         /**
121489          * Groups sibling nodes together into their own SyntaxList if they
121490          * a) are adjacent, AND b) match a predicate function.
121491          */
121492         function groupChildren(children, groupOn) {
121493             var result = [];
121494             var group;
121495             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
121496                 var child = children_1[_i];
121497                 if (groupOn(child)) {
121498                     group = group || [];
121499                     group.push(child);
121500                 }
121501                 else {
121502                     if (group) {
121503                         result.push(createSyntaxList(group));
121504                         group = undefined;
121505                     }
121506                     result.push(child);
121507                 }
121508             }
121509             if (group) {
121510                 result.push(createSyntaxList(group));
121511             }
121512             return result;
121513         }
121514         /**
121515          * Splits sibling nodes into up to four partitions:
121516          * 1) everything left of the first node matched by `pivotOn`,
121517          * 2) the first node matched by `pivotOn`,
121518          * 3) everything right of the first node matched by `pivotOn`,
121519          * 4) a trailing semicolon, if `separateTrailingSemicolon` is enabled.
121520          * The left and right groups, if not empty, will each be grouped into their own containing SyntaxList.
121521          * @param children The sibling nodes to split.
121522          * @param pivotOn The predicate function to match the node to be the pivot. The first node that matches
121523          * the predicate will be used; any others that may match will be included into the right-hand group.
121524          * @param separateTrailingSemicolon If the last token is a semicolon, it will be returned as a separate
121525          * child rather than be included in the right-hand group.
121526          */
121527         function splitChildren(children, pivotOn, separateTrailingSemicolon) {
121528             if (separateTrailingSemicolon === void 0) { separateTrailingSemicolon = true; }
121529             if (children.length < 2) {
121530                 return children;
121531             }
121532             var splitTokenIndex = ts.findIndex(children, pivotOn);
121533             if (splitTokenIndex === -1) {
121534                 return children;
121535             }
121536             var leftChildren = children.slice(0, splitTokenIndex);
121537             var splitToken = children[splitTokenIndex];
121538             var lastToken = ts.last(children);
121539             var separateLastToken = separateTrailingSemicolon && lastToken.kind === 26 /* SemicolonToken */;
121540             var rightChildren = children.slice(splitTokenIndex + 1, separateLastToken ? children.length - 1 : undefined);
121541             var result = ts.compact([
121542                 leftChildren.length ? createSyntaxList(leftChildren) : undefined,
121543                 splitToken,
121544                 rightChildren.length ? createSyntaxList(rightChildren) : undefined,
121545             ]);
121546             return separateLastToken ? result.concat(lastToken) : result;
121547         }
121548         function createSyntaxList(children) {
121549             ts.Debug.assertGreaterThanOrEqual(children.length, 1);
121550             var syntaxList = ts.createNode(324 /* SyntaxList */, children[0].pos, ts.last(children).end);
121551             syntaxList._children = children;
121552             return syntaxList;
121553         }
121554         function isListOpener(token) {
121555             var kind = token && token.kind;
121556             return kind === 18 /* OpenBraceToken */
121557                 || kind === 22 /* OpenBracketToken */
121558                 || kind === 20 /* OpenParenToken */
121559                 || kind === 268 /* JsxOpeningElement */;
121560         }
121561         function isListCloser(token) {
121562             var kind = token && token.kind;
121563             return kind === 19 /* CloseBraceToken */
121564                 || kind === 23 /* CloseBracketToken */
121565                 || kind === 21 /* CloseParenToken */
121566                 || kind === 269 /* JsxClosingElement */;
121567         }
121568     })(SmartSelectionRange = ts.SmartSelectionRange || (ts.SmartSelectionRange = {}));
121569 })(ts || (ts = {}));
121570 /* @internal */
121571 var ts;
121572 (function (ts) {
121573     var SignatureHelp;
121574     (function (SignatureHelp) {
121575         var InvocationKind;
121576         (function (InvocationKind) {
121577             InvocationKind[InvocationKind["Call"] = 0] = "Call";
121578             InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs";
121579             InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual";
121580         })(InvocationKind || (InvocationKind = {}));
121581         function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) {
121582             var typeChecker = program.getTypeChecker();
121583             // Decide whether to show signature help
121584             var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position);
121585             if (!startingToken) {
121586                 // We are at the beginning of the file
121587                 return undefined;
121588             }
121589             // Only need to be careful if the user typed a character and signature help wasn't showing.
121590             var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped";
121591             // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it.
121592             if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) {
121593                 return undefined;
121594             }
121595             var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked";
121596             var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked);
121597             if (!argumentInfo)
121598                 return undefined;
121599             cancellationToken.throwIfCancellationRequested();
121600             // Extra syntactic and semantic filtering of signature help
121601             var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners);
121602             cancellationToken.throwIfCancellationRequested();
121603             if (!candidateInfo) {
121604                 // We didn't have any sig help items produced by the TS compiler.  If this is a JS
121605                 // file, then see if we can figure out anything better.
121606                 return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined;
121607             }
121608             return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
121609                 return candidateInfo.kind === 0 /* Candidate */
121610                     ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker)
121611                     : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker);
121612             });
121613         }
121614         SignatureHelp.getSignatureHelpItems = getSignatureHelpItems;
121615         var CandidateOrTypeKind;
121616         (function (CandidateOrTypeKind) {
121617             CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate";
121618             CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type";
121619         })(CandidateOrTypeKind || (CandidateOrTypeKind = {}));
121620         function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) {
121621             var invocation = _a.invocation, argumentCount = _a.argumentCount;
121622             switch (invocation.kind) {
121623                 case 0 /* Call */: {
121624                     if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) {
121625                         return undefined;
121626                     }
121627                     var candidates = [];
121628                     var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217
121629                     return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature };
121630                 }
121631                 case 1 /* TypeArgs */: {
121632                     var called = invocation.called;
121633                     if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) {
121634                         return undefined;
121635                     }
121636                     var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker);
121637                     if (candidates.length !== 0)
121638                         return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) };
121639                     var symbol = checker.getSymbolAtLocation(called);
121640                     return symbol && { kind: 1 /* Type */, symbol: symbol };
121641                 }
121642                 case 2 /* Contextual */:
121643                     return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature };
121644                 default:
121645                     return ts.Debug.assertNever(invocation);
121646             }
121647         }
121648         function isSyntacticOwner(startingToken, node, sourceFile) {
121649             if (!ts.isCallOrNewExpression(node))
121650                 return false;
121651             var invocationChildren = node.getChildren(sourceFile);
121652             switch (startingToken.kind) {
121653                 case 20 /* OpenParenToken */:
121654                     return ts.contains(invocationChildren, startingToken);
121655                 case 27 /* CommaToken */: {
121656                     var containingList = ts.findContainingList(startingToken);
121657                     return !!containingList && ts.contains(invocationChildren, containingList);
121658                 }
121659                 case 29 /* LessThanToken */:
121660                     return containsPrecedingToken(startingToken, sourceFile, node.expression);
121661                 default:
121662                     return false;
121663             }
121664         }
121665         function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) {
121666             if (argumentInfo.invocation.kind === 2 /* Contextual */)
121667                 return undefined;
121668             // See if we can find some symbol with the call expression name that has call signatures.
121669             var expression = getExpressionFromInvocation(argumentInfo.invocation);
121670             var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined;
121671             var typeChecker = program.getTypeChecker();
121672             return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) {
121673                 return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) {
121674                     var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration);
121675                     var callSignatures = type && type.getCallSignatures();
121676                     if (callSignatures && callSignatures.length) {
121677                         return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); });
121678                     }
121679                 });
121680             });
121681         }
121682         function containsPrecedingToken(startingToken, sourceFile, container) {
121683             var pos = startingToken.getFullStart();
121684             // There’s a possibility that `startingToken.parent` contains only `startingToken` and
121685             // missing nodes, none of which are valid to be returned by `findPrecedingToken`. In that
121686             // case, the preceding token we want is actually higher up the tree—almost definitely the
121687             // next parent, but theoretically the situation with missing nodes might be happening on
121688             // multiple nested levels.
121689             var currentParent = startingToken.parent;
121690             while (currentParent) {
121691                 var precedingToken = ts.findPrecedingToken(pos, sourceFile, currentParent, /*excludeJsdoc*/ true);
121692                 if (precedingToken) {
121693                     return ts.rangeContainsRange(container, precedingToken);
121694                 }
121695                 currentParent = currentParent.parent;
121696             }
121697             return ts.Debug.fail("Could not find preceding token");
121698         }
121699         function getArgumentInfoForCompletions(node, position, sourceFile) {
121700             var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile);
121701             return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined
121702                 : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex };
121703         }
121704         SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions;
121705         function getArgumentOrParameterListInfo(node, sourceFile) {
121706             var info = getArgumentOrParameterListAndIndex(node, sourceFile);
121707             if (!info)
121708                 return undefined;
121709             var list = info.list, argumentIndex = info.argumentIndex;
121710             var argumentCount = getArgumentCount(list);
121711             if (argumentIndex !== 0) {
121712                 ts.Debug.assertLessThan(argumentIndex, argumentCount);
121713             }
121714             var argumentsSpan = getApplicableSpanForArguments(list, sourceFile);
121715             return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan };
121716         }
121717         function getArgumentOrParameterListAndIndex(node, sourceFile) {
121718             if (node.kind === 29 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) {
121719                 // Find the list that starts right *after* the < or ( token.
121720                 // If the user has just opened a list, consider this item 0.
121721                 return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 };
121722             }
121723             else {
121724                 // findListItemInfo can return undefined if we are not in parent's argument list
121725                 // or type argument list. This includes cases where the cursor is:
121726                 //   - To the right of the closing parenthesis, non-substitution template, or template tail.
121727                 //   - Between the type arguments and the arguments (greater than token)
121728                 //   - On the target of the call (parent.func)
121729                 //   - On the 'new' keyword in a 'new' expression
121730                 var list = ts.findContainingList(node);
121731                 return list && { list: list, argumentIndex: getArgumentIndex(list, node) };
121732             }
121733         }
121734         /**
121735          * Returns relevant information for the argument list and the current argument if we are
121736          * in the argument of an invocation; returns undefined otherwise.
121737          */
121738         function getImmediatelyContainingArgumentInfo(node, position, sourceFile) {
121739             var parent = node.parent;
121740             if (ts.isCallOrNewExpression(parent)) {
121741                 var invocation = parent;
121742                 // There are 3 cases to handle:
121743                 //   1. The token introduces a list, and should begin a signature help session
121744                 //   2. The token is either not associated with a list, or ends a list, so the session should end
121745                 //   3. The token is buried inside a list, and should give signature help
121746                 //
121747                 // The following are examples of each:
121748                 //
121749                 //    Case 1:
121750                 //          foo<#T, U>(#a, b)    -> The token introduces a list, and should begin a signature help session
121751                 //    Case 2:
121752                 //          fo#o<T, U>#(a, b)#   -> The token is either not associated with a list, or ends a list, so the session should end
121753                 //    Case 3:
121754                 //          foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give signature help
121755                 // Find out if 'node' is an argument, a type argument, or neither
121756                 var info = getArgumentOrParameterListInfo(node, sourceFile);
121757                 if (!info)
121758                     return undefined;
121759                 var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
121760                 var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos;
121761                 return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount };
121762             }
121763             else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) {
121764                 // Check if we're actually inside the template;
121765                 // otherwise we'll fall out and return undefined.
121766                 if (ts.isInsideTemplateLiteral(node, position, sourceFile)) {
121767                     return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile);
121768                 }
121769                 return undefined;
121770             }
121771             else if (ts.isTemplateHead(node) && parent.parent.kind === 198 /* TaggedTemplateExpression */) {
121772                 var templateExpression = parent;
121773                 var tagExpression = templateExpression.parent;
121774                 ts.Debug.assert(templateExpression.kind === 211 /* TemplateExpression */);
121775                 var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1;
121776                 return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
121777             }
121778             else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) {
121779                 var templateSpan = parent;
121780                 var tagExpression = parent.parent.parent;
121781                 // If we're just after a template tail, don't show signature help.
121782                 if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) {
121783                     return undefined;
121784                 }
121785                 var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan);
121786                 var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile);
121787                 return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
121788             }
121789             else if (ts.isJsxOpeningLikeElement(parent)) {
121790                 // Provide a signature help for JSX opening element or JSX self-closing element.
121791                 // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems")
121792                 // i.e
121793                 //      export function MainButton(props: ButtonProps, context: any): JSX.Element { ... }
121794                 //      <MainButton /*signatureHelp*/
121795                 var attributeSpanStart = parent.attributes.pos;
121796                 var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, /*stopAfterLineBreak*/ false);
121797                 return {
121798                     isTypeParameterList: false,
121799                     invocation: { kind: 0 /* Call */, node: parent },
121800                     argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart),
121801                     argumentIndex: 0,
121802                     argumentCount: 1
121803                 };
121804             }
121805             else {
121806                 var typeArgInfo = ts.getPossibleTypeArgumentsInfo(node, sourceFile);
121807                 if (typeArgInfo) {
121808                     var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments;
121809                     var invocation = { kind: 1 /* TypeArgs */, called: called };
121810                     var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end);
121811                     return { isTypeParameterList: true, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 };
121812                 }
121813                 return undefined;
121814             }
121815         }
121816         function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) {
121817             return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile);
121818         }
121819         function getHighestBinary(b) {
121820             return ts.isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b;
121821         }
121822         function countBinaryExpressionParameters(b) {
121823             return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2;
121824         }
121825         function tryGetParameterInfo(startingToken, _position, sourceFile, checker) {
121826             var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker);
121827             if (!info)
121828                 return undefined;
121829             var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
121830             var signatures = contextualType.getCallSignatures();
121831             if (signatures.length !== 1)
121832                 return undefined;
121833             var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(contextualType.symbol) };
121834             return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount };
121835         }
121836         function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) {
121837             if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */)
121838                 return undefined;
121839             var parent = startingToken.parent;
121840             switch (parent.kind) {
121841                 case 200 /* ParenthesizedExpression */:
121842                 case 161 /* MethodDeclaration */:
121843                 case 201 /* FunctionExpression */:
121844                 case 202 /* ArrowFunction */:
121845                     var info = getArgumentOrParameterListInfo(startingToken, sourceFile);
121846                     if (!info)
121847                         return undefined;
121848                     var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
121849                     var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent);
121850                     return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan };
121851                 case 209 /* BinaryExpression */: {
121852                     var highestBinary = getHighestBinary(parent);
121853                     var contextualType_1 = checker.getContextualType(highestBinary);
121854                     var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1;
121855                     var argumentCount_1 = countBinaryExpressionParameters(highestBinary);
121856                     return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) };
121857                 }
121858                 default:
121859                     return undefined;
121860             }
121861         }
121862         // The type of a function type node has a symbol at that node, but it's better to use the symbol for a parameter or type alias.
121863         function chooseBetterSymbol(s) {
121864             return s.name === "__type" /* Type */
121865                 ? ts.firstDefined(s.declarations, function (d) { return ts.isFunctionTypeNode(d) ? d.parent.symbol : undefined; }) || s
121866                 : s;
121867         }
121868         function getArgumentIndex(argumentsList, node) {
121869             // The list we got back can include commas.  In the presence of errors it may
121870             // also just have nodes without commas.  For example "Foo(a b c)" will have 3
121871             // args without commas. We want to find what index we're at.  So we count
121872             // forward until we hit ourselves, only incrementing the index if it isn't a
121873             // comma.
121874             //
121875             // Note: the subtlety around trailing commas (in getArgumentCount) does not apply
121876             // here.  That's because we're only walking forward until we hit the node we're
121877             // on.  In that case, even if we're after the trailing comma, we'll still see
121878             // that trailing comma in the list, and we'll have generated the appropriate
121879             // arg index.
121880             var argumentIndex = 0;
121881             for (var _i = 0, _a = argumentsList.getChildren(); _i < _a.length; _i++) {
121882                 var child = _a[_i];
121883                 if (child === node) {
121884                     break;
121885                 }
121886                 if (child.kind !== 27 /* CommaToken */) {
121887                     argumentIndex++;
121888                 }
121889             }
121890             return argumentIndex;
121891         }
121892         function getArgumentCount(argumentsList) {
121893             // The argument count for a list is normally the number of non-comma children it has.
121894             // For example, if you have "Foo(a,b)" then there will be three children of the arg
121895             // list 'a' '<comma>' 'b'.  So, in this case the arg count will be 2.  However, there
121896             // is a small subtlety.  If you have "Foo(a,)", then the child list will just have
121897             // 'a' '<comma>'.  So, in the case where the last child is a comma, we increase the
121898             // arg count by one to compensate.
121899             //
121900             // Note: this subtlety only applies to the last comma.  If you had "Foo(a,," then
121901             // we'll have: 'a' '<comma>' '<missing>'
121902             // That will give us 2 non-commas.  We then add one for the last comma, giving us an
121903             // arg count of 3.
121904             var listChildren = argumentsList.getChildren();
121905             var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; });
121906             if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) {
121907                 argumentCount++;
121908             }
121909             return argumentCount;
121910         }
121911         // spanIndex is either the index for a given template span.
121912         // This does not give appropriate results for a NoSubstitutionTemplateLiteral
121913         function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) {
121914             // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1.
121915             // There are three cases we can encounter:
121916             //      1. We are precisely in the template literal (argIndex = 0).
121917             //      2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1).
121918             //      3. We are directly to the right of the template literal, but because we look for the token on the left,
121919             //          not enough to put us in the substitution expression; we should consider ourselves part of
121920             //          the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1).
121921             //
121922             /* eslint-disable no-double-space */
121923             // Example: f  `# abcd $#{#  1 + 1#  }# efghi ${ #"#hello"#  }  #  `
121924             //              ^       ^ ^       ^   ^          ^ ^      ^     ^
121925             // Case:        1       1 3       2   1          3 2      2     1
121926             /* eslint-enable no-double-space */
121927             ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node.");
121928             if (ts.isTemplateLiteralToken(node)) {
121929                 if (ts.isInsideTemplateLiteral(node, position, sourceFile)) {
121930                     return 0;
121931                 }
121932                 return spanIndex + 2;
121933             }
121934             return spanIndex + 1;
121935         }
121936         function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) {
121937             // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument.
121938             var argumentCount = ts.isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1;
121939             if (argumentIndex !== 0) {
121940                 ts.Debug.assertLessThan(argumentIndex, argumentCount);
121941             }
121942             return {
121943                 isTypeParameterList: false,
121944                 invocation: { kind: 0 /* Call */, node: tagExpression },
121945                 argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile),
121946                 argumentIndex: argumentIndex,
121947                 argumentCount: argumentCount
121948             };
121949         }
121950         function getApplicableSpanForArguments(argumentsList, sourceFile) {
121951             // We use full start and skip trivia on the end because we want to include trivia on
121952             // both sides. For example,
121953             //
121954             //    foo(   /*comment */     a, b, c      /*comment*/     )
121955             //        |                                               |
121956             //
121957             // The applicable span is from the first bar to the second bar (inclusive,
121958             // but not including parentheses)
121959             var applicableSpanStart = argumentsList.getFullStart();
121960             var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false);
121961             return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
121962         }
121963         function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) {
121964             var template = taggedTemplate.template;
121965             var applicableSpanStart = template.getStart();
121966             var applicableSpanEnd = template.getEnd();
121967             // We need to adjust the end position for the case where the template does not have a tail.
121968             // Otherwise, we will not show signature help past the expression.
121969             // For example,
121970             //
121971             //      ` ${ 1 + 1 foo(10)
121972             //       |       |
121973             // This is because a Missing node has no width. However, what we actually want is to include trivia
121974             // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail.
121975             if (template.kind === 211 /* TemplateExpression */) {
121976                 var lastSpan = ts.last(template.templateSpans);
121977                 if (lastSpan.literal.getFullWidth() === 0) {
121978                     applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false);
121979                 }
121980             }
121981             return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
121982         }
121983         function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
121984             var _loop_7 = function (n) {
121985                 // If the node is not a subspan of its parent, this is a big problem.
121986                 // There have been crashes that might be caused by this violation.
121987                 ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); });
121988                 var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker);
121989                 if (argumentInfo) {
121990                     return { value: argumentInfo };
121991                 }
121992             };
121993             for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
121994                 var state_2 = _loop_7(n);
121995                 if (typeof state_2 === "object")
121996                     return state_2.value;
121997             }
121998             return undefined;
121999         }
122000         function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) {
122001             var children = parent.getChildren(sourceFile);
122002             var indexOfOpenerToken = children.indexOf(openerToken);
122003             ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1);
122004             return children[indexOfOpenerToken + 1];
122005         }
122006         function getExpressionFromInvocation(invocation) {
122007             return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called;
122008         }
122009         function getEnclosingDeclarationFromInvocation(invocation) {
122010             return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
122011         }
122012         var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
122013         function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
122014             var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
122015             var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
122016             var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation));
122017             var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray;
122018             var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); });
122019             if (argumentIndex !== 0) {
122020                 ts.Debug.assertLessThan(argumentIndex, argumentCount);
122021             }
122022             var selectedItemIndex = candidates.indexOf(resolvedSignature);
122023             ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function.
122024             return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount };
122025         }
122026         function createTypeHelpItems(symbol, _a, sourceFile, checker) {
122027             var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
122028             var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
122029             if (!typeParameters)
122030                 return undefined;
122031             var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)];
122032             return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount };
122033         }
122034         function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) {
122035             var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol);
122036             var printer = ts.createPrinter({ removeComments: true });
122037             var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
122038             var documentation = symbol.getDocumentationComment(checker);
122039             var tags = symbol.getJsDocTags();
122040             var prefixDisplayParts = __spreadArrays(typeSymbolDisplay, [ts.punctuationPart(29 /* LessThanToken */)]);
122041             return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(31 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
122042         }
122043         var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()];
122044         function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) {
122045             var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix;
122046             var prefixDisplayParts = __spreadArrays(callTargetDisplayParts, prefix);
122047             var suffixDisplayParts = __spreadArrays(suffix, returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker));
122048             var documentation = candidateSignature.getDocumentationComment(checker);
122049             var tags = candidateSignature.getJsDocTags();
122050             return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
122051         }
122052         function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) {
122053             return ts.mapToDisplayParts(function (writer) {
122054                 writer.writePunctuation(":");
122055                 writer.writeSpace(" ");
122056                 var predicate = checker.getTypePredicateOfSignature(candidateSignature);
122057                 if (predicate) {
122058                     checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer);
122059                 }
122060                 else {
122061                     checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer);
122062                 }
122063             });
122064         }
122065         function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
122066             var typeParameters = (candidateSignature.target || candidateSignature).typeParameters;
122067             var printer = ts.createPrinter({ removeComments: true });
122068             var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
122069             var parameterParts = ts.mapToDisplayParts(function (writer) {
122070                 var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : [];
122071                 var params = ts.createNodeArray(__spreadArrays(thisParameter, checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
122072                 printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
122073             });
122074             return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(29 /* LessThanToken */)], suffix: __spreadArrays([ts.punctuationPart(31 /* GreaterThanToken */)], parameterParts) };
122075         }
122076         function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
122077             var isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
122078             var printer = ts.createPrinter({ removeComments: true });
122079             var typeParameterParts = ts.mapToDisplayParts(function (writer) {
122080                 if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
122081                     var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags); }));
122082                     printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
122083                 }
122084             });
122085             var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
122086             return { isVariadic: isVariadic, parameters: parameters, prefix: __spreadArrays(typeParameterParts, [ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] };
122087         }
122088         function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
122089             var displayParts = ts.mapToDisplayParts(function (writer) {
122090                 var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
122091                 printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
122092             });
122093             var isOptional = checker.isOptionalParameter(parameter.valueDeclaration);
122094             return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional };
122095         }
122096         function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) {
122097             var displayParts = ts.mapToDisplayParts(function (writer) {
122098                 var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
122099                 printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
122100             });
122101             return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false };
122102         }
122103     })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {}));
122104 })(ts || (ts = {}));
122105 /* @internal */
122106 var ts;
122107 (function (ts) {
122108     var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
122109     function getSourceMapper(host) {
122110         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
122111         var currentDirectory = host.getCurrentDirectory();
122112         var sourceFileLike = ts.createMap();
122113         var documentPositionMappers = ts.createMap();
122114         return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache };
122115         function toPath(fileName) {
122116             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
122117         }
122118         function getDocumentPositionMapper(generatedFileName, sourceFileName) {
122119             var path = toPath(generatedFileName);
122120             var value = documentPositionMappers.get(path);
122121             if (value)
122122                 return value;
122123             var mapper;
122124             if (host.getDocumentPositionMapper) {
122125                 mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName);
122126             }
122127             else if (host.readFile) {
122128                 var file = getSourceFileLike(generatedFileName);
122129                 mapper = file && ts.getDocumentPositionMapper({ getSourceFileLike: getSourceFileLike, getCanonicalFileName: getCanonicalFileName, log: function (s) { return host.log(s); } }, generatedFileName, ts.getLineInfo(file.text, ts.getLineStarts(file)), function (f) { return !host.fileExists || host.fileExists(f) ? host.readFile(f) : undefined; });
122130             }
122131             documentPositionMappers.set(path, mapper || ts.identitySourceMapConsumer);
122132             return mapper || ts.identitySourceMapConsumer;
122133         }
122134         function tryGetSourcePosition(info) {
122135             if (!ts.isDeclarationFileName(info.fileName))
122136                 return undefined;
122137             var file = getSourceFile(info.fileName);
122138             if (!file)
122139                 return undefined;
122140             var newLoc = getDocumentPositionMapper(info.fileName).getSourcePosition(info);
122141             return !newLoc || newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc;
122142         }
122143         function tryGetGeneratedPosition(info) {
122144             if (ts.isDeclarationFileName(info.fileName))
122145                 return undefined;
122146             var sourceFile = getSourceFile(info.fileName);
122147             if (!sourceFile)
122148                 return undefined;
122149             var program = host.getProgram();
122150             // If this is source file of project reference source (instead of redirect) there is no generated position
122151             if (program.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) {
122152                 return undefined;
122153             }
122154             var options = program.getCompilerOptions();
122155             var outPath = options.outFile || options.out;
122156             var declarationPath = outPath ?
122157                 ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ :
122158                 ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName);
122159             if (declarationPath === undefined)
122160                 return undefined;
122161             var newLoc = getDocumentPositionMapper(declarationPath, info.fileName).getGeneratedPosition(info);
122162             return newLoc === info ? undefined : newLoc;
122163         }
122164         function getSourceFile(fileName) {
122165             var program = host.getProgram();
122166             if (!program)
122167                 return undefined;
122168             var path = toPath(fileName);
122169             // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file
122170             var file = program.getSourceFileByPath(path);
122171             return file && file.resolvedPath === path ? file : undefined;
122172         }
122173         function getOrCreateSourceFileLike(fileName) {
122174             var path = toPath(fileName);
122175             var fileFromCache = sourceFileLike.get(path);
122176             if (fileFromCache !== undefined)
122177                 return fileFromCache ? fileFromCache : undefined;
122178             if (!host.readFile || host.fileExists && !host.fileExists(path)) {
122179                 sourceFileLike.set(path, false);
122180                 return undefined;
122181             }
122182             // And failing that, check the disk
122183             var text = host.readFile(path);
122184             var file = text ? createSourceFileLike(text) : false;
122185             sourceFileLike.set(path, file);
122186             return file ? file : undefined;
122187         }
122188         // This can be called from source mapper in either source program or program that includes generated file
122189         function getSourceFileLike(fileName) {
122190             return !host.getSourceFileLike ?
122191                 getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) :
122192                 host.getSourceFileLike(fileName);
122193         }
122194         function toLineColumnOffset(fileName, position) {
122195             var file = getSourceFileLike(fileName); // TODO: GH#18217
122196             return file.getLineAndCharacterOfPosition(position);
122197         }
122198         function clearCache() {
122199             sourceFileLike.clear();
122200             documentPositionMappers.clear();
122201         }
122202     }
122203     ts.getSourceMapper = getSourceMapper;
122204     function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) {
122205         var mapFileName = ts.tryGetSourceMappingURL(generatedFileLineInfo);
122206         if (mapFileName) {
122207             var match = base64UrlRegExp.exec(mapFileName);
122208             if (match) {
122209                 if (match[1]) {
122210                     var base64Object = match[1];
122211                     return convertDocumentToSourceMapper(host, ts.base64decode(ts.sys, base64Object), generatedFileName);
122212                 }
122213                 // Not a data URL we can parse, skip it
122214                 mapFileName = undefined;
122215             }
122216         }
122217         var possibleMapLocations = [];
122218         if (mapFileName) {
122219             possibleMapLocations.push(mapFileName);
122220         }
122221         possibleMapLocations.push(generatedFileName + ".map");
122222         var originalMapFileName = mapFileName && ts.getNormalizedAbsolutePath(mapFileName, ts.getDirectoryPath(generatedFileName));
122223         for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) {
122224             var location = possibleMapLocations_1[_i];
122225             var mapFileName_1 = ts.getNormalizedAbsolutePath(location, ts.getDirectoryPath(generatedFileName));
122226             var mapFileContents = readMapFile(mapFileName_1, originalMapFileName);
122227             if (ts.isString(mapFileContents)) {
122228                 return convertDocumentToSourceMapper(host, mapFileContents, mapFileName_1);
122229             }
122230             if (mapFileContents !== undefined) {
122231                 return mapFileContents || undefined;
122232             }
122233         }
122234         return undefined;
122235     }
122236     ts.getDocumentPositionMapper = getDocumentPositionMapper;
122237     function convertDocumentToSourceMapper(host, contents, mapFileName) {
122238         var map = ts.tryParseRawSourceMap(contents);
122239         if (!map || !map.sources || !map.file || !map.mappings) {
122240             // obviously invalid map
122241             return undefined;
122242         }
122243         // Dont support sourcemaps that contain inlined sources
122244         if (map.sourcesContent && map.sourcesContent.some(ts.isString))
122245             return undefined;
122246         return ts.createDocumentPositionMapper(host, map, mapFileName);
122247     }
122248     function createSourceFileLike(text, lineMap) {
122249         return {
122250             text: text,
122251             lineMap: lineMap,
122252             getLineAndCharacterOfPosition: function (pos) {
122253                 return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos);
122254             }
122255         };
122256     }
122257 })(ts || (ts = {}));
122258 /* @internal */
122259 var ts;
122260 (function (ts) {
122261     var visitedNestedConvertibleFunctions = ts.createMap();
122262     function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) {
122263         program.getSemanticDiagnostics(sourceFile, cancellationToken);
122264         var diags = [];
122265         var checker = program.getTypeChecker();
122266         if (sourceFile.commonJsModuleIndicator &&
122267             (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) &&
122268             containsTopLevelCommonjs(sourceFile)) {
122269             diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
122270         }
122271         var isJsFile = ts.isSourceFileJS(sourceFile);
122272         visitedNestedConvertibleFunctions.clear();
122273         check(sourceFile);
122274         if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
122275             for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
122276                 var moduleSpecifier = _a[_i];
122277                 var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
122278                 var name = importNameForConvertToDefaultImport(importNode);
122279                 if (!name)
122280                     continue;
122281                 var module_1 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
122282                 var resolvedFile = module_1 && program.getSourceFile(module_1.resolvedFileName);
122283                 if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
122284                     diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
122285                 }
122286             }
122287         }
122288         ts.addRange(diags, sourceFile.bindSuggestionDiagnostics);
122289         ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken));
122290         return diags.sort(function (d1, d2) { return d1.start - d2.start; });
122291         function check(node) {
122292             if (isJsFile) {
122293                 if (canBeConvertedToClass(node)) {
122294                     diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
122295                 }
122296             }
122297             else {
122298                 if (ts.isVariableStatement(node) &&
122299                     node.parent === sourceFile &&
122300                     node.declarationList.flags & 2 /* Const */ &&
122301                     node.declarationList.declarations.length === 1) {
122302                     var init = node.declarationList.declarations[0].initializer;
122303                     if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) {
122304                         diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import));
122305                     }
122306                 }
122307                 if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) {
122308                     diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
122309                 }
122310             }
122311             if (ts.isFunctionLikeDeclaration(node)) {
122312                 addConvertToAsyncFunctionDiagnostics(node, checker, diags);
122313             }
122314             node.forEachChild(check);
122315         }
122316     }
122317     ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
122318     // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes.
122319     function containsTopLevelCommonjs(sourceFile) {
122320         return sourceFile.statements.some(function (statement) {
122321             switch (statement.kind) {
122322                 case 225 /* VariableStatement */:
122323                     return statement.declarationList.declarations.some(function (decl) {
122324                         return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true);
122325                     });
122326                 case 226 /* ExpressionStatement */: {
122327                     var expression = statement.expression;
122328                     if (!ts.isBinaryExpression(expression))
122329                         return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
122330                     var kind = ts.getAssignmentDeclarationKind(expression);
122331                     return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
122332                 }
122333                 default:
122334                     return false;
122335             }
122336         });
122337     }
122338     function propertyAccessLeftHandSide(node) {
122339         return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
122340     }
122341     function importNameForConvertToDefaultImport(node) {
122342         switch (node.kind) {
122343             case 254 /* ImportDeclaration */:
122344                 var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
122345                 return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 256 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
122346                     ? importClause.namedBindings.name
122347                     : undefined;
122348             case 253 /* ImportEqualsDeclaration */:
122349                 return node.name;
122350             default:
122351                 return undefined;
122352         }
122353     }
122354     function addConvertToAsyncFunctionDiagnostics(node, checker, diags) {
122355         // need to check function before checking map so that deeper levels of nested callbacks are checked
122356         if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) {
122357             diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function));
122358         }
122359     }
122360     function isConvertibleFunction(node, checker) {
122361         return !ts.isAsyncFunction(node) &&
122362             node.body &&
122363             ts.isBlock(node.body) &&
122364             hasReturnStatementWithPromiseHandler(node.body) &&
122365             returnsPromise(node, checker);
122366     }
122367     function returnsPromise(node, checker) {
122368         var functionType = checker.getTypeAtLocation(node);
122369         var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */);
122370         var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined;
122371         return !!returnType && !!checker.getPromisedTypeOfPromise(returnType);
122372     }
122373     function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) {
122374         return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator;
122375     }
122376     function hasReturnStatementWithPromiseHandler(body) {
122377         return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler);
122378     }
122379     function isReturnStatementWithFixablePromiseHandler(node) {
122380         return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression);
122381     }
122382     ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler;
122383     // Should be kept up to date with transformExpression in convertToAsyncFunction.ts
122384     function isFixablePromiseHandler(node) {
122385         // ensure outermost call exists and is a promise handler
122386         if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) {
122387             return false;
122388         }
122389         // ensure all chained calls are valid
122390         var currentNode = node.expression;
122391         while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) {
122392             if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) {
122393                 return false;
122394             }
122395             currentNode = currentNode.expression;
122396         }
122397         return true;
122398     }
122399     ts.isFixablePromiseHandler = isFixablePromiseHandler;
122400     function isPromiseHandler(node) {
122401         return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") && hasSupportedNumberOfArguments(node) ||
122402             ts.hasPropertyAccessExpressionWithName(node, "catch"));
122403     }
122404     function hasSupportedNumberOfArguments(node) {
122405         if (node.arguments.length > 2)
122406             return false;
122407         if (node.arguments.length < 2)
122408             return true;
122409         return ts.some(node.arguments, function (arg) {
122410             return arg.kind === 100 /* NullKeyword */ ||
122411                 ts.isIdentifier(arg) && arg.text === "undefined";
122412         });
122413     }
122414     // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts
122415     function isFixablePromiseArgument(arg) {
122416         switch (arg.kind) {
122417             case 244 /* FunctionDeclaration */:
122418             case 201 /* FunctionExpression */:
122419             case 202 /* ArrowFunction */:
122420                 visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true);
122421             // falls through
122422             case 100 /* NullKeyword */:
122423             case 75 /* Identifier */: // identifier includes undefined
122424                 return true;
122425             default:
122426                 return false;
122427         }
122428     }
122429     function getKeyFromNode(exp) {
122430         return exp.pos.toString() + ":" + exp.end.toString();
122431     }
122432     function canBeConvertedToClass(node) {
122433         var _a, _b, _c, _d;
122434         if (node.kind === 201 /* FunctionExpression */) {
122435             if (ts.isVariableDeclaration(node.parent) && ((_a = node.symbol.members) === null || _a === void 0 ? void 0 : _a.size)) {
122436                 return true;
122437             }
122438             var decl = ts.getDeclarationOfExpando(node);
122439             var symbol = decl === null || decl === void 0 ? void 0 : decl.symbol;
122440             return !!(symbol && (((_b = symbol.exports) === null || _b === void 0 ? void 0 : _b.size) || ((_c = symbol.members) === null || _c === void 0 ? void 0 : _c.size)));
122441         }
122442         if (node.kind === 244 /* FunctionDeclaration */) {
122443             return !!((_d = node.symbol.members) === null || _d === void 0 ? void 0 : _d.size);
122444         }
122445         return false;
122446     }
122447 })(ts || (ts = {}));
122448 /* @internal */
122449 var ts;
122450 (function (ts) {
122451     var SymbolDisplay;
122452     (function (SymbolDisplay) {
122453         var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
122454         // TODO(drosen): use contextual SemanticMeaning.
122455         function getSymbolKind(typeChecker, symbol, location) {
122456             var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
122457             if (result !== "" /* unknown */) {
122458                 return result;
122459             }
122460             var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
122461             if (flags & 32 /* Class */) {
122462                 return ts.getDeclarationOfKind(symbol, 214 /* ClassExpression */) ?
122463                     "local class" /* localClassElement */ : "class" /* classElement */;
122464             }
122465             if (flags & 384 /* Enum */)
122466                 return "enum" /* enumElement */;
122467             if (flags & 524288 /* TypeAlias */)
122468                 return "type" /* typeElement */;
122469             if (flags & 64 /* Interface */)
122470                 return "interface" /* interfaceElement */;
122471             if (flags & 262144 /* TypeParameter */)
122472                 return "type parameter" /* typeParameterElement */;
122473             if (flags & 8 /* EnumMember */)
122474                 return "enum member" /* enumMemberElement */;
122475             if (flags & 2097152 /* Alias */)
122476                 return "alias" /* alias */;
122477             if (flags & 1536 /* Module */)
122478                 return "module" /* moduleElement */;
122479             return result;
122480         }
122481         SymbolDisplay.getSymbolKind = getSymbolKind;
122482         function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) {
122483             var roots = typeChecker.getRootSymbols(symbol);
122484             // If this is a method from a mapped type, leave as a method so long as it still has a call signature.
122485             if (roots.length === 1
122486                 && ts.first(roots).flags & 8192 /* Method */
122487                 // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`.
122488                 && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) {
122489                 return "method" /* memberFunctionElement */;
122490             }
122491             if (typeChecker.isUndefinedSymbol(symbol)) {
122492                 return "var" /* variableElement */;
122493             }
122494             if (typeChecker.isArgumentsSymbol(symbol)) {
122495                 return "local var" /* localVariableElement */;
122496             }
122497             if (location.kind === 104 /* ThisKeyword */ && ts.isExpression(location)) {
122498                 return "parameter" /* parameterElement */;
122499             }
122500             var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
122501             if (flags & 3 /* Variable */) {
122502                 if (ts.isFirstDeclarationOfSymbolParameter(symbol)) {
122503                     return "parameter" /* parameterElement */;
122504                 }
122505                 else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) {
122506                     return "const" /* constElement */;
122507                 }
122508                 else if (ts.forEach(symbol.declarations, ts.isLet)) {
122509                     return "let" /* letElement */;
122510                 }
122511                 return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */;
122512             }
122513             if (flags & 16 /* Function */)
122514                 return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */;
122515             if (flags & 32768 /* GetAccessor */)
122516                 return "getter" /* memberGetAccessorElement */;
122517             if (flags & 65536 /* SetAccessor */)
122518                 return "setter" /* memberSetAccessorElement */;
122519             if (flags & 8192 /* Method */)
122520                 return "method" /* memberFunctionElement */;
122521             if (flags & 16384 /* Constructor */)
122522                 return "constructor" /* constructorImplementationElement */;
122523             if (flags & 4 /* Property */) {
122524                 if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) {
122525                     // If union property is result of union of non method (property/accessors/variables), it is labeled as property
122526                     var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) {
122527                         var rootSymbolFlags = rootSymbol.getFlags();
122528                         if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) {
122529                             return "property" /* memberVariableElement */;
122530                         }
122531                         // May be a Function if this was from `typeof N` with `namespace N { function f();. }`.
122532                         ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */)));
122533                     });
122534                     if (!unionPropertyKind) {
122535                         // If this was union of all methods,
122536                         // make sure it has call signatures before we can label it as method
122537                         var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
122538                         if (typeOfUnionProperty.getCallSignatures().length) {
122539                             return "method" /* memberFunctionElement */;
122540                         }
122541                         return "property" /* memberVariableElement */;
122542                     }
122543                     return unionPropertyKind;
122544                 }
122545                 // If we requested completions after `x.` at the top-level, we may be at a source file location.
122546                 switch (location.parent && location.parent.kind) {
122547                     // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'.
122548                     case 268 /* JsxOpeningElement */:
122549                     case 266 /* JsxElement */:
122550                     case 267 /* JsxSelfClosingElement */:
122551                         return location.kind === 75 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */;
122552                     case 273 /* JsxAttribute */:
122553                         return "JSX attribute" /* jsxAttribute */;
122554                     default:
122555                         return "property" /* memberVariableElement */;
122556                 }
122557             }
122558             return "" /* unknown */;
122559         }
122560         function getSymbolModifiers(symbol) {
122561             var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0
122562                 ? ts.getNodeModifiers(symbol.declarations[0])
122563                 : "" /* none */;
122564             var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ?
122565                 "optional" /* optionalModifier */
122566                 : "" /* none */;
122567             return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers;
122568         }
122569         SymbolDisplay.getSymbolModifiers = getSymbolModifiers;
122570         // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location
122571         function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) {
122572             if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); }
122573             var displayParts = [];
122574             var documentation = [];
122575             var tags = [];
122576             var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
122577             var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */;
122578             var hasAddedSymbolInfo = false;
122579             var isThisExpression = location.kind === 104 /* ThisKeyword */ && ts.isInExpressionContext(location);
122580             var type;
122581             var printer;
122582             var documentationFromAlias;
122583             var tagsFromAlias;
122584             var hasMultipleSignatures = false;
122585             if (location.kind === 104 /* ThisKeyword */ && !isThisExpression) {
122586                 return { displayParts: [ts.keywordPart(104 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined };
122587             }
122588             // Class at constructor site need to be shown as constructor apart from property,method, vars
122589             if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) {
122590                 // If it is accessor they are allowed only if location is at name of the accessor
122591                 if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) {
122592                     symbolKind = "property" /* memberVariableElement */;
122593                 }
122594                 var signature = void 0;
122595                 type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location);
122596                 if (location.parent && location.parent.kind === 194 /* PropertyAccessExpression */) {
122597                     var right = location.parent.name;
122598                     // Either the location is on the right of a property access, or on the left and the right is missing
122599                     if (right === location || (right && right.getFullWidth() === 0)) {
122600                         location = location.parent;
122601                     }
122602                 }
122603                 // try get the call/construct signature from the type if it matches
122604                 var callExpressionLike = void 0;
122605                 if (ts.isCallOrNewExpression(location)) {
122606                     callExpressionLike = location;
122607                 }
122608                 else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) {
122609                     callExpressionLike = location.parent;
122610                 }
122611                 else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) {
122612                     callExpressionLike = location.parent;
122613                 }
122614                 if (callExpressionLike) {
122615                     signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217
122616                     var useConstructSignatures = callExpressionLike.kind === 197 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 102 /* SuperKeyword */);
122617                     var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
122618                     if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) {
122619                         // Get the first signature if there is one -- allSignatures may contain
122620                         // either the original signature or its target, so check for either
122621                         signature = allSignatures.length ? allSignatures[0] : undefined;
122622                     }
122623                     if (signature) {
122624                         if (useConstructSignatures && (symbolFlags & 32 /* Class */)) {
122625                             // Constructor
122626                             symbolKind = "constructor" /* constructorImplementationElement */;
122627                             addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
122628                         }
122629                         else if (symbolFlags & 2097152 /* Alias */) {
122630                             symbolKind = "alias" /* alias */;
122631                             pushSymbolKind(symbolKind);
122632                             displayParts.push(ts.spacePart());
122633                             if (useConstructSignatures) {
122634                                 displayParts.push(ts.keywordPart(99 /* NewKeyword */));
122635                                 displayParts.push(ts.spacePart());
122636                             }
122637                             addFullSymbolName(symbol);
122638                         }
122639                         else {
122640                             addPrefixForAnyFunctionOrVar(symbol, symbolKind);
122641                         }
122642                         switch (symbolKind) {
122643                             case "JSX attribute" /* jsxAttribute */:
122644                             case "property" /* memberVariableElement */:
122645                             case "var" /* variableElement */:
122646                             case "const" /* constElement */:
122647                             case "let" /* letElement */:
122648                             case "parameter" /* parameterElement */:
122649                             case "local var" /* localVariableElement */:
122650                                 // If it is call or construct signature of lambda's write type name
122651                                 displayParts.push(ts.punctuationPart(58 /* ColonToken */));
122652                                 displayParts.push(ts.spacePart());
122653                                 if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) {
122654                                     ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */));
122655                                     displayParts.push(ts.lineBreakPart());
122656                                 }
122657                                 if (useConstructSignatures) {
122658                                     displayParts.push(ts.keywordPart(99 /* NewKeyword */));
122659                                     displayParts.push(ts.spacePart());
122660                                 }
122661                                 addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */);
122662                                 break;
122663                             default:
122664                                 // Just signature
122665                                 addSignatureDisplayParts(signature, allSignatures);
122666                         }
122667                         hasAddedSymbolInfo = true;
122668                         hasMultipleSignatures = allSignatures.length > 1;
122669                     }
122670                 }
122671                 else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration
122672                     (location.kind === 129 /* ConstructorKeyword */ && location.parent.kind === 162 /* Constructor */)) { // At constructor keyword of constructor declaration
122673                     // get the signature from the declaration and write it
122674                     var functionDeclaration_1 = location.parent;
122675                     // Use function declaration to write the signatures only if the symbol corresponding to this declaration
122676                     var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) {
122677                         return declaration === (location.kind === 129 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1);
122678                     });
122679                     if (locationIsSymbolDeclaration) {
122680                         var allSignatures = functionDeclaration_1.kind === 162 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
122681                         if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) {
122682                             signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217
122683                         }
122684                         else {
122685                             signature = allSignatures[0];
122686                         }
122687                         if (functionDeclaration_1.kind === 162 /* Constructor */) {
122688                             // show (constructor) Type(...) signature
122689                             symbolKind = "constructor" /* constructorImplementationElement */;
122690                             addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
122691                         }
122692                         else {
122693                             // (function/method) symbol(..signature)
122694                             addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 165 /* CallSignature */ &&
122695                                 !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind);
122696                         }
122697                         addSignatureDisplayParts(signature, allSignatures);
122698                         hasAddedSymbolInfo = true;
122699                         hasMultipleSignatures = allSignatures.length > 1;
122700                     }
122701                 }
122702             }
122703             if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) {
122704                 addAliasPrefixIfNecessary();
122705                 if (ts.getDeclarationOfKind(symbol, 214 /* ClassExpression */)) {
122706                     // Special case for class expressions because we would like to indicate that
122707                     // the class name is local to the class body (similar to function expression)
122708                     //      (local class) class <className>
122709                     pushSymbolKind("local class" /* localClassElement */);
122710                 }
122711                 else {
122712                     // Class declaration has name which is not local.
122713                     displayParts.push(ts.keywordPart(80 /* ClassKeyword */));
122714                 }
122715                 displayParts.push(ts.spacePart());
122716                 addFullSymbolName(symbol);
122717                 writeTypeParametersOfSymbol(symbol, sourceFile);
122718             }
122719             if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) {
122720                 prefixNextMeaning();
122721                 displayParts.push(ts.keywordPart(114 /* InterfaceKeyword */));
122722                 displayParts.push(ts.spacePart());
122723                 addFullSymbolName(symbol);
122724                 writeTypeParametersOfSymbol(symbol, sourceFile);
122725             }
122726             if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) {
122727                 prefixNextMeaning();
122728                 displayParts.push(ts.keywordPart(145 /* TypeKeyword */));
122729                 displayParts.push(ts.spacePart());
122730                 addFullSymbolName(symbol);
122731                 writeTypeParametersOfSymbol(symbol, sourceFile);
122732                 displayParts.push(ts.spacePart());
122733                 displayParts.push(ts.operatorPart(62 /* EqualsToken */));
122734                 displayParts.push(ts.spacePart());
122735                 ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */));
122736             }
122737             if (symbolFlags & 384 /* Enum */) {
122738                 prefixNextMeaning();
122739                 if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) {
122740                     displayParts.push(ts.keywordPart(81 /* ConstKeyword */));
122741                     displayParts.push(ts.spacePart());
122742                 }
122743                 displayParts.push(ts.keywordPart(88 /* EnumKeyword */));
122744                 displayParts.push(ts.spacePart());
122745                 addFullSymbolName(symbol);
122746             }
122747             if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
122748                 prefixNextMeaning();
122749                 var declaration = ts.getDeclarationOfKind(symbol, 249 /* ModuleDeclaration */);
122750                 var isNamespace = declaration && declaration.name && declaration.name.kind === 75 /* Identifier */;
122751                 displayParts.push(ts.keywordPart(isNamespace ? 136 /* NamespaceKeyword */ : 135 /* ModuleKeyword */));
122752                 displayParts.push(ts.spacePart());
122753                 addFullSymbolName(symbol);
122754             }
122755             if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) {
122756                 prefixNextMeaning();
122757                 displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
122758                 displayParts.push(ts.textPart("type parameter"));
122759                 displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
122760                 displayParts.push(ts.spacePart());
122761                 addFullSymbolName(symbol);
122762                 if (symbol.parent) {
122763                     // Class/Interface type parameter
122764                     addInPrefix();
122765                     addFullSymbolName(symbol.parent, enclosingDeclaration);
122766                     writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration);
122767                 }
122768                 else {
122769                     // Method/function type parameter
122770                     var decl = ts.getDeclarationOfKind(symbol, 155 /* TypeParameter */);
122771                     if (decl === undefined)
122772                         return ts.Debug.fail();
122773                     var declaration = decl.parent;
122774                     if (declaration) {
122775                         if (ts.isFunctionLikeKind(declaration.kind)) {
122776                             addInPrefix();
122777                             var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217
122778                             if (declaration.kind === 166 /* ConstructSignature */) {
122779                                 displayParts.push(ts.keywordPart(99 /* NewKeyword */));
122780                                 displayParts.push(ts.spacePart());
122781                             }
122782                             else if (declaration.kind !== 165 /* CallSignature */ && declaration.name) {
122783                                 addFullSymbolName(declaration.symbol);
122784                             }
122785                             ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */));
122786                         }
122787                         else if (declaration.kind === 247 /* TypeAliasDeclaration */) {
122788                             // Type alias type parameter
122789                             // For example
122790                             //      type list<T> = T[]; // Both T will go through same code path
122791                             addInPrefix();
122792                             displayParts.push(ts.keywordPart(145 /* TypeKeyword */));
122793                             displayParts.push(ts.spacePart());
122794                             addFullSymbolName(declaration.symbol);
122795                             writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
122796                         }
122797                     }
122798                 }
122799             }
122800             if (symbolFlags & 8 /* EnumMember */) {
122801                 symbolKind = "enum member" /* enumMemberElement */;
122802                 addPrefixForAnyFunctionOrVar(symbol, "enum member");
122803                 var declaration = symbol.declarations[0];
122804                 if (declaration.kind === 284 /* EnumMember */) {
122805                     var constantValue = typeChecker.getConstantValue(declaration);
122806                     if (constantValue !== undefined) {
122807                         displayParts.push(ts.spacePart());
122808                         displayParts.push(ts.operatorPart(62 /* EqualsToken */));
122809                         displayParts.push(ts.spacePart());
122810                         displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral));
122811                     }
122812                 }
122813             }
122814             if (symbolFlags & 2097152 /* Alias */) {
122815                 prefixNextMeaning();
122816                 if (!hasAddedSymbolInfo) {
122817                     var resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
122818                     if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) {
122819                         var resolvedNode = resolvedSymbol.declarations[0];
122820                         var declarationName = ts.getNameOfDeclaration(resolvedNode);
122821                         if (declarationName) {
122822                             var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) &&
122823                                 ts.hasModifier(resolvedNode, 2 /* Ambient */);
122824                             var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration;
122825                             var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol);
122826                             displayParts.push.apply(displayParts, resolvedInfo.displayParts);
122827                             displayParts.push(ts.lineBreakPart());
122828                             documentationFromAlias = resolvedInfo.documentation;
122829                             tagsFromAlias = resolvedInfo.tags;
122830                         }
122831                     }
122832                 }
122833                 switch (symbol.declarations[0].kind) {
122834                     case 252 /* NamespaceExportDeclaration */:
122835                         displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
122836                         displayParts.push(ts.spacePart());
122837                         displayParts.push(ts.keywordPart(136 /* NamespaceKeyword */));
122838                         break;
122839                     case 259 /* ExportAssignment */:
122840                         displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
122841                         displayParts.push(ts.spacePart());
122842                         displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 84 /* DefaultKeyword */));
122843                         break;
122844                     case 263 /* ExportSpecifier */:
122845                         displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
122846                         break;
122847                     default:
122848                         displayParts.push(ts.keywordPart(96 /* ImportKeyword */));
122849                 }
122850                 displayParts.push(ts.spacePart());
122851                 addFullSymbolName(symbol);
122852                 ts.forEach(symbol.declarations, function (declaration) {
122853                     if (declaration.kind === 253 /* ImportEqualsDeclaration */) {
122854                         var importEqualsDeclaration = declaration;
122855                         if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
122856                             displayParts.push(ts.spacePart());
122857                             displayParts.push(ts.operatorPart(62 /* EqualsToken */));
122858                             displayParts.push(ts.spacePart());
122859                             displayParts.push(ts.keywordPart(139 /* RequireKeyword */));
122860                             displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
122861                             displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral));
122862                             displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
122863                         }
122864                         else {
122865                             var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference);
122866                             if (internalAliasSymbol) {
122867                                 displayParts.push(ts.spacePart());
122868                                 displayParts.push(ts.operatorPart(62 /* EqualsToken */));
122869                                 displayParts.push(ts.spacePart());
122870                                 addFullSymbolName(internalAliasSymbol, enclosingDeclaration);
122871                             }
122872                         }
122873                         return true;
122874                     }
122875                 });
122876             }
122877             if (!hasAddedSymbolInfo) {
122878                 if (symbolKind !== "" /* unknown */) {
122879                     if (type) {
122880                         if (isThisExpression) {
122881                             prefixNextMeaning();
122882                             displayParts.push(ts.keywordPart(104 /* ThisKeyword */));
122883                         }
122884                         else {
122885                             addPrefixForAnyFunctionOrVar(symbol, symbolKind);
122886                         }
122887                         // For properties, variables and local vars: show the type
122888                         if (symbolKind === "property" /* memberVariableElement */ ||
122889                             symbolKind === "JSX attribute" /* jsxAttribute */ ||
122890                             symbolFlags & 3 /* Variable */ ||
122891                             symbolKind === "local var" /* localVariableElement */ ||
122892                             isThisExpression) {
122893                             displayParts.push(ts.punctuationPart(58 /* ColonToken */));
122894                             displayParts.push(ts.spacePart());
122895                             // If the type is type parameter, format it specially
122896                             if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) {
122897                                 var typeParameterParts = ts.mapToDisplayParts(function (writer) {
122898                                     var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags);
122899                                     getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer);
122900                                 });
122901                                 ts.addRange(displayParts, typeParameterParts);
122902                             }
122903                             else {
122904                                 ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration));
122905                             }
122906                         }
122907                         else if (symbolFlags & 16 /* Function */ ||
122908                             symbolFlags & 8192 /* Method */ ||
122909                             symbolFlags & 16384 /* Constructor */ ||
122910                             symbolFlags & 131072 /* Signature */ ||
122911                             symbolFlags & 98304 /* Accessor */ ||
122912                             symbolKind === "method" /* memberFunctionElement */) {
122913                             var allSignatures = type.getNonNullableType().getCallSignatures();
122914                             if (allSignatures.length) {
122915                                 addSignatureDisplayParts(allSignatures[0], allSignatures);
122916                                 hasMultipleSignatures = allSignatures.length > 1;
122917                             }
122918                         }
122919                     }
122920                 }
122921                 else {
122922                     symbolKind = getSymbolKind(typeChecker, symbol, location);
122923                 }
122924             }
122925             if (documentation.length === 0 && !hasMultipleSignatures) {
122926                 documentation = symbol.getDocumentationComment(typeChecker);
122927             }
122928             if (documentation.length === 0 && symbolFlags & 4 /* Property */) {
122929                 // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
122930                 // there documentation comments might be attached to the right hand side symbol of their declarations.
122931                 // The pattern of such special property access is that the parent symbol is the symbol of the file.
122932                 if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 290 /* SourceFile */; })) {
122933                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
122934                         var declaration = _a[_i];
122935                         if (!declaration.parent || declaration.parent.kind !== 209 /* BinaryExpression */) {
122936                             continue;
122937                         }
122938                         var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right);
122939                         if (!rhsSymbol) {
122940                             continue;
122941                         }
122942                         documentation = rhsSymbol.getDocumentationComment(typeChecker);
122943                         tags = rhsSymbol.getJsDocTags();
122944                         if (documentation.length > 0) {
122945                             break;
122946                         }
122947                     }
122948                 }
122949             }
122950             if (tags.length === 0 && !hasMultipleSignatures) {
122951                 tags = symbol.getJsDocTags();
122952             }
122953             if (documentation.length === 0 && documentationFromAlias) {
122954                 documentation = documentationFromAlias;
122955             }
122956             if (tags.length === 0 && tagsFromAlias) {
122957                 tags = tagsFromAlias;
122958             }
122959             return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags };
122960             function getPrinter() {
122961                 if (!printer) {
122962                     printer = ts.createPrinter({ removeComments: true });
122963                 }
122964                 return printer;
122965             }
122966             function prefixNextMeaning() {
122967                 if (displayParts.length) {
122968                     displayParts.push(ts.lineBreakPart());
122969                 }
122970                 addAliasPrefixIfNecessary();
122971             }
122972             function addAliasPrefixIfNecessary() {
122973                 if (alias) {
122974                     pushSymbolKind("alias" /* alias */);
122975                     displayParts.push(ts.spacePart());
122976                 }
122977             }
122978             function addInPrefix() {
122979                 displayParts.push(ts.spacePart());
122980                 displayParts.push(ts.keywordPart(97 /* InKeyword */));
122981                 displayParts.push(ts.spacePart());
122982             }
122983             function addFullSymbolName(symbolToDisplay, enclosingDeclaration) {
122984                 if (alias && symbolToDisplay === symbol) {
122985                     symbolToDisplay = alias;
122986                 }
122987                 var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */);
122988                 ts.addRange(displayParts, fullSymbolDisplayParts);
122989                 if (symbol.flags & 16777216 /* Optional */) {
122990                     displayParts.push(ts.punctuationPart(57 /* QuestionToken */));
122991                 }
122992             }
122993             function addPrefixForAnyFunctionOrVar(symbol, symbolKind) {
122994                 prefixNextMeaning();
122995                 if (symbolKind) {
122996                     pushSymbolKind(symbolKind);
122997                     if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) {
122998                         displayParts.push(ts.spacePart());
122999                         addFullSymbolName(symbol);
123000                     }
123001                 }
123002             }
123003             function pushSymbolKind(symbolKind) {
123004                 switch (symbolKind) {
123005                     case "var" /* variableElement */:
123006                     case "function" /* functionElement */:
123007                     case "let" /* letElement */:
123008                     case "const" /* constElement */:
123009                     case "constructor" /* constructorImplementationElement */:
123010                         displayParts.push(ts.textOrKeywordPart(symbolKind));
123011                         return;
123012                     default:
123013                         displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
123014                         displayParts.push(ts.textOrKeywordPart(symbolKind));
123015                         displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
123016                         return;
123017                 }
123018             }
123019             function addSignatureDisplayParts(signature, allSignatures, flags) {
123020                 if (flags === void 0) { flags = 0 /* None */; }
123021                 ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */));
123022                 if (allSignatures.length > 1) {
123023                     displayParts.push(ts.spacePart());
123024                     displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
123025                     displayParts.push(ts.operatorPart(39 /* PlusToken */));
123026                     displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral));
123027                     displayParts.push(ts.spacePart());
123028                     displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads"));
123029                     displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
123030                 }
123031                 documentation = signature.getDocumentationComment(typeChecker);
123032                 tags = signature.getJsDocTags();
123033                 if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) {
123034                     documentation = allSignatures[0].getDocumentationComment(typeChecker);
123035                     tags = allSignatures[0].getJsDocTags();
123036                 }
123037             }
123038             function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) {
123039                 var typeParameterParts = ts.mapToDisplayParts(function (writer) {
123040                     var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration, symbolDisplayNodeBuilderFlags);
123041                     getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer);
123042                 });
123043                 ts.addRange(displayParts, typeParameterParts);
123044             }
123045         }
123046         SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind;
123047         function isLocalVariableOrFunction(symbol) {
123048             if (symbol.parent) {
123049                 return false; // This is exported symbol
123050             }
123051             return ts.forEach(symbol.declarations, function (declaration) {
123052                 // Function expressions are local
123053                 if (declaration.kind === 201 /* FunctionExpression */) {
123054                     return true;
123055                 }
123056                 if (declaration.kind !== 242 /* VariableDeclaration */ && declaration.kind !== 244 /* FunctionDeclaration */) {
123057                     return false;
123058                 }
123059                 // If the parent is not sourceFile or module block it is local variable
123060                 for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
123061                     // Reached source file or module block
123062                     if (parent.kind === 290 /* SourceFile */ || parent.kind === 250 /* ModuleBlock */) {
123063                         return false;
123064                     }
123065                 }
123066                 // parent is in function block
123067                 return true;
123068             });
123069         }
123070     })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {}));
123071 })(ts || (ts = {}));
123072 var ts;
123073 (function (ts) {
123074     /*
123075      * This function will compile source text from 'input' argument using specified compiler options.
123076      * If not options are provided - it will use a set of default compiler options.
123077      * Extra compiler options that will unconditionally be used by this function are:
123078      * - isolatedModules = true
123079      * - allowNonTsExtensions = true
123080      * - noLib = true
123081      * - noResolve = true
123082      */
123083     function transpileModule(input, transpileOptions) {
123084         var diagnostics = [];
123085         var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : {};
123086         // mix in default options
123087         var defaultOptions = ts.getDefaultCompilerOptions();
123088         for (var key in defaultOptions) {
123089             if (ts.hasProperty(defaultOptions, key) && options[key] === undefined) {
123090                 options[key] = defaultOptions[key];
123091             }
123092         }
123093         for (var _i = 0, transpileOptionValueCompilerOptions_1 = ts.transpileOptionValueCompilerOptions; _i < transpileOptionValueCompilerOptions_1.length; _i++) {
123094             var option = transpileOptionValueCompilerOptions_1[_i];
123095             options[option.name] = option.transpileOptionValue;
123096         }
123097         // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths.
123098         options.suppressOutputPathCheck = true;
123099         // Filename can be non-ts file.
123100         options.allowNonTsExtensions = true;
123101         // if jsx is specified then treat file as .tsx
123102         var inputFileName = transpileOptions.fileName || (transpileOptions.compilerOptions && transpileOptions.compilerOptions.jsx ? "module.tsx" : "module.ts");
123103         var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217
123104         if (transpileOptions.moduleName) {
123105             sourceFile.moduleName = transpileOptions.moduleName;
123106         }
123107         if (transpileOptions.renamedDependencies) {
123108             sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies);
123109         }
123110         var newLine = ts.getNewLineCharacter(options);
123111         // Output
123112         var outputText;
123113         var sourceMapText;
123114         // Create a compilerHost object to allow the compiler to read and write files
123115         var compilerHost = {
123116             getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; },
123117             writeFile: function (name, text) {
123118                 if (ts.fileExtensionIs(name, ".map")) {
123119                     ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name);
123120                     sourceMapText = text;
123121                 }
123122                 else {
123123                     ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name);
123124                     outputText = text;
123125                 }
123126             },
123127             getDefaultLibFileName: function () { return "lib.d.ts"; },
123128             useCaseSensitiveFileNames: function () { return false; },
123129             getCanonicalFileName: function (fileName) { return fileName; },
123130             getCurrentDirectory: function () { return ""; },
123131             getNewLine: function () { return newLine; },
123132             fileExists: function (fileName) { return fileName === inputFileName; },
123133             readFile: function () { return ""; },
123134             directoryExists: function () { return true; },
123135             getDirectories: function () { return []; }
123136         };
123137         var program = ts.createProgram([inputFileName], options, compilerHost);
123138         if (transpileOptions.reportDiagnostics) {
123139             ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile));
123140             ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics());
123141         }
123142         // Emit
123143         program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers);
123144         if (outputText === undefined)
123145             return ts.Debug.fail("Output generation failed");
123146         return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText };
123147     }
123148     ts.transpileModule = transpileModule;
123149     /*
123150      * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result.
123151      */
123152     function transpile(input, compilerOptions, fileName, diagnostics, moduleName) {
123153         var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName });
123154         // addRange correctly handles cases when wither 'from' or 'to' argument is missing
123155         ts.addRange(diagnostics, output.diagnostics);
123156         return output.outputText;
123157     }
123158     ts.transpile = transpile;
123159     var commandLineOptionsStringToEnum;
123160     /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */
123161     /*@internal*/
123162     function fixupCompilerOptions(options, diagnostics) {
123163         // Lazily create this value to fix module loading errors.
123164         commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) {
123165             return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
123166         });
123167         options = ts.cloneCompilerOptions(options);
123168         var _loop_8 = function (opt) {
123169             if (!ts.hasProperty(options, opt.name)) {
123170                 return "continue";
123171             }
123172             var value = options[opt.name];
123173             // Value should be a key of opt.type
123174             if (ts.isString(value)) {
123175                 // If value is not a string, this will fail
123176                 options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics);
123177             }
123178             else {
123179                 if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) {
123180                     // Supplied value isn't a valid enum value.
123181                     diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt));
123182                 }
123183             }
123184         };
123185         for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
123186             var opt = commandLineOptionsStringToEnum_1[_i];
123187             _loop_8(opt);
123188         }
123189         return options;
123190     }
123191     ts.fixupCompilerOptions = fixupCompilerOptions;
123192 })(ts || (ts = {}));
123193 /* @internal */
123194 var ts;
123195 (function (ts) {
123196     var formatting;
123197     (function (formatting) {
123198         var FormattingRequestKind;
123199         (function (FormattingRequestKind) {
123200             FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument";
123201             FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection";
123202             FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter";
123203             FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon";
123204             FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace";
123205             FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace";
123206         })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {}));
123207         var FormattingContext = /** @class */ (function () {
123208             function FormattingContext(sourceFile, formattingRequestKind, options) {
123209                 this.sourceFile = sourceFile;
123210                 this.formattingRequestKind = formattingRequestKind;
123211                 this.options = options;
123212             }
123213             FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
123214                 this.currentTokenSpan = ts.Debug.checkDefined(currentRange);
123215                 this.currentTokenParent = ts.Debug.checkDefined(currentTokenParent);
123216                 this.nextTokenSpan = ts.Debug.checkDefined(nextRange);
123217                 this.nextTokenParent = ts.Debug.checkDefined(nextTokenParent);
123218                 this.contextNode = ts.Debug.checkDefined(commonParent);
123219                 // drop cached results
123220                 this.contextNodeAllOnSameLine = undefined;
123221                 this.nextNodeAllOnSameLine = undefined;
123222                 this.tokensAreOnSameLine = undefined;
123223                 this.contextNodeBlockIsOnOneLine = undefined;
123224                 this.nextNodeBlockIsOnOneLine = undefined;
123225             };
123226             FormattingContext.prototype.ContextNodeAllOnSameLine = function () {
123227                 if (this.contextNodeAllOnSameLine === undefined) {
123228                     this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode);
123229                 }
123230                 return this.contextNodeAllOnSameLine;
123231             };
123232             FormattingContext.prototype.NextNodeAllOnSameLine = function () {
123233                 if (this.nextNodeAllOnSameLine === undefined) {
123234                     this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent);
123235                 }
123236                 return this.nextNodeAllOnSameLine;
123237             };
123238             FormattingContext.prototype.TokensAreOnSameLine = function () {
123239                 if (this.tokensAreOnSameLine === undefined) {
123240                     var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
123241                     var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
123242                     this.tokensAreOnSameLine = (startLine === endLine);
123243                 }
123244                 return this.tokensAreOnSameLine;
123245             };
123246             FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () {
123247                 if (this.contextNodeBlockIsOnOneLine === undefined) {
123248                     this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode);
123249                 }
123250                 return this.contextNodeBlockIsOnOneLine;
123251             };
123252             FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () {
123253                 if (this.nextNodeBlockIsOnOneLine === undefined) {
123254                     this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent);
123255                 }
123256                 return this.nextNodeBlockIsOnOneLine;
123257             };
123258             FormattingContext.prototype.NodeIsOnOneLine = function (node) {
123259                 var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
123260                 var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
123261                 return startLine === endLine;
123262             };
123263             FormattingContext.prototype.BlockIsOnOneLine = function (node) {
123264                 var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile);
123265                 var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile);
123266                 if (openBrace && closeBrace) {
123267                     var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
123268                     var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
123269                     return startLine === endLine;
123270                 }
123271                 return false;
123272             };
123273             return FormattingContext;
123274         }());
123275         formatting.FormattingContext = FormattingContext;
123276     })(formatting = ts.formatting || (ts.formatting = {}));
123277 })(ts || (ts = {}));
123278 /* @internal */
123279 var ts;
123280 (function (ts) {
123281     var formatting;
123282     (function (formatting) {
123283         var standardScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
123284         var jsxScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
123285         var ScanAction;
123286         (function (ScanAction) {
123287             ScanAction[ScanAction["Scan"] = 0] = "Scan";
123288             ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken";
123289             ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
123290             ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
123291             ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
123292             ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
123293             ScanAction[ScanAction["RescanJsxAttributeValue"] = 6] = "RescanJsxAttributeValue";
123294         })(ScanAction || (ScanAction = {}));
123295         function getFormattingScanner(text, languageVariant, startPos, endPos, cb) {
123296             var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
123297             scanner.setText(text);
123298             scanner.setTextPos(startPos);
123299             var wasNewLine = true;
123300             var leadingTrivia;
123301             var trailingTrivia;
123302             var savedPos;
123303             var lastScanAction;
123304             var lastTokenInfo;
123305             var res = cb({
123306                 advance: advance,
123307                 readTokenInfo: readTokenInfo,
123308                 readEOFTokenRange: readEOFTokenRange,
123309                 isOnToken: isOnToken,
123310                 isOnEOF: isOnEOF,
123311                 getCurrentLeadingTrivia: function () { return leadingTrivia; },
123312                 lastTrailingTriviaWasNewLine: function () { return wasNewLine; },
123313                 skipToEndOf: skipToEndOf,
123314             });
123315             lastTokenInfo = undefined;
123316             scanner.setText(undefined);
123317             return res;
123318             function advance() {
123319                 lastTokenInfo = undefined;
123320                 var isStarted = scanner.getStartPos() !== startPos;
123321                 if (isStarted) {
123322                     wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */;
123323                 }
123324                 else {
123325                     scanner.scan();
123326                 }
123327                 leadingTrivia = undefined;
123328                 trailingTrivia = undefined;
123329                 var pos = scanner.getStartPos();
123330                 // Read leading trivia and token
123331                 while (pos < endPos) {
123332                     var t = scanner.getToken();
123333                     if (!ts.isTrivia(t)) {
123334                         break;
123335                     }
123336                     // consume leading trivia
123337                     scanner.scan();
123338                     var item = {
123339                         pos: pos,
123340                         end: scanner.getStartPos(),
123341                         kind: t
123342                     };
123343                     pos = scanner.getStartPos();
123344                     leadingTrivia = ts.append(leadingTrivia, item);
123345                 }
123346                 savedPos = scanner.getStartPos();
123347             }
123348             function shouldRescanGreaterThanToken(node) {
123349                 switch (node.kind) {
123350                     case 33 /* GreaterThanEqualsToken */:
123351                     case 70 /* GreaterThanGreaterThanEqualsToken */:
123352                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
123353                     case 49 /* GreaterThanGreaterThanGreaterThanToken */:
123354                     case 48 /* GreaterThanGreaterThanToken */:
123355                         return true;
123356                 }
123357                 return false;
123358             }
123359             function shouldRescanJsxIdentifier(node) {
123360                 if (node.parent) {
123361                     switch (node.parent.kind) {
123362                         case 273 /* JsxAttribute */:
123363                         case 268 /* JsxOpeningElement */:
123364                         case 269 /* JsxClosingElement */:
123365                         case 267 /* JsxSelfClosingElement */:
123366                             // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier.
123367                             return ts.isKeyword(node.kind) || node.kind === 75 /* Identifier */;
123368                     }
123369                 }
123370                 return false;
123371             }
123372             function shouldRescanJsxText(node) {
123373                 var isJSXText = ts.isJsxText(node);
123374                 if (isJSXText) {
123375                     var containingElement = ts.findAncestor(node.parent, function (p) { return ts.isJsxElement(p); });
123376                     if (!containingElement)
123377                         return false; // should never happen
123378                     return !ts.isParenthesizedExpression(containingElement.parent);
123379                 }
123380                 return false;
123381             }
123382             function shouldRescanSlashToken(container) {
123383                 return container.kind === 13 /* RegularExpressionLiteral */;
123384             }
123385             function shouldRescanTemplateToken(container) {
123386                 return container.kind === 16 /* TemplateMiddle */ ||
123387                     container.kind === 17 /* TemplateTail */;
123388             }
123389             function shouldRescanJsxAttributeValue(node) {
123390                 return node.parent && ts.isJsxAttribute(node.parent) && node.parent.initializer === node;
123391             }
123392             function startsWithSlashToken(t) {
123393                 return t === 43 /* SlashToken */ || t === 67 /* SlashEqualsToken */;
123394             }
123395             function readTokenInfo(n) {
123396                 ts.Debug.assert(isOnToken());
123397                 // normally scanner returns the smallest available token
123398                 // check the kind of context node to determine if scanner should have more greedy behavior and consume more text.
123399                 var expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 /* RescanGreaterThanToken */ :
123400                     shouldRescanSlashToken(n) ? 2 /* RescanSlashToken */ :
123401                         shouldRescanTemplateToken(n) ? 3 /* RescanTemplateToken */ :
123402                             shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ :
123403                                 shouldRescanJsxText(n) ? 5 /* RescanJsxText */ :
123404                                     shouldRescanJsxAttributeValue(n) ? 6 /* RescanJsxAttributeValue */ :
123405                                         0 /* Scan */;
123406                 if (lastTokenInfo && expectedScanAction === lastScanAction) {
123407                     // readTokenInfo was called before with the same expected scan action.
123408                     // No need to re-scan text, return existing 'lastTokenInfo'
123409                     // it is ok to call fixTokenKind here since it does not affect
123410                     // what portion of text is consumed. In contrast rescanning can change it,
123411                     // i.e. for '>=' when originally scanner eats just one character
123412                     // and rescanning forces it to consume more.
123413                     return fixTokenKind(lastTokenInfo, n);
123414                 }
123415                 if (scanner.getStartPos() !== savedPos) {
123416                     ts.Debug.assert(lastTokenInfo !== undefined);
123417                     // readTokenInfo was called before but scan action differs - rescan text
123418                     scanner.setTextPos(savedPos);
123419                     scanner.scan();
123420                 }
123421                 var currentToken = getNextToken(n, expectedScanAction);
123422                 var token = formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), currentToken);
123423                 // consume trailing trivia
123424                 if (trailingTrivia) {
123425                     trailingTrivia = undefined;
123426                 }
123427                 while (scanner.getStartPos() < endPos) {
123428                     currentToken = scanner.scan();
123429                     if (!ts.isTrivia(currentToken)) {
123430                         break;
123431                     }
123432                     var trivia = formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), currentToken);
123433                     if (!trailingTrivia) {
123434                         trailingTrivia = [];
123435                     }
123436                     trailingTrivia.push(trivia);
123437                     if (currentToken === 4 /* NewLineTrivia */) {
123438                         // move past new line
123439                         scanner.scan();
123440                         break;
123441                     }
123442                 }
123443                 lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token };
123444                 return fixTokenKind(lastTokenInfo, n);
123445             }
123446             function getNextToken(n, expectedScanAction) {
123447                 var token = scanner.getToken();
123448                 lastScanAction = 0 /* Scan */;
123449                 switch (expectedScanAction) {
123450                     case 1 /* RescanGreaterThanToken */:
123451                         if (token === 31 /* GreaterThanToken */) {
123452                             lastScanAction = 1 /* RescanGreaterThanToken */;
123453                             var newToken = scanner.reScanGreaterToken();
123454                             ts.Debug.assert(n.kind === newToken);
123455                             return newToken;
123456                         }
123457                         break;
123458                     case 2 /* RescanSlashToken */:
123459                         if (startsWithSlashToken(token)) {
123460                             lastScanAction = 2 /* RescanSlashToken */;
123461                             var newToken = scanner.reScanSlashToken();
123462                             ts.Debug.assert(n.kind === newToken);
123463                             return newToken;
123464                         }
123465                         break;
123466                     case 3 /* RescanTemplateToken */:
123467                         if (token === 19 /* CloseBraceToken */) {
123468                             lastScanAction = 3 /* RescanTemplateToken */;
123469                             return scanner.reScanTemplateToken(/* isTaggedTemplate */ false);
123470                         }
123471                         break;
123472                     case 4 /* RescanJsxIdentifier */:
123473                         lastScanAction = 4 /* RescanJsxIdentifier */;
123474                         return scanner.scanJsxIdentifier();
123475                     case 5 /* RescanJsxText */:
123476                         lastScanAction = 5 /* RescanJsxText */;
123477                         return scanner.reScanJsxToken();
123478                     case 6 /* RescanJsxAttributeValue */:
123479                         lastScanAction = 6 /* RescanJsxAttributeValue */;
123480                         return scanner.reScanJsxAttributeValue();
123481                     case 0 /* Scan */:
123482                         break;
123483                     default:
123484                         ts.Debug.assertNever(expectedScanAction);
123485                 }
123486                 return token;
123487             }
123488             function readEOFTokenRange() {
123489                 ts.Debug.assert(isOnEOF());
123490                 return formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), 1 /* EndOfFileToken */);
123491             }
123492             function isOnToken() {
123493                 var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
123494                 var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos();
123495                 return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current);
123496             }
123497             function isOnEOF() {
123498                 var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
123499                 return current === 1 /* EndOfFileToken */;
123500             }
123501             // when containing node in the tree is token
123502             // but its kind differs from the kind that was returned by the scanner,
123503             // then kind needs to be fixed. This might happen in cases
123504             // when parser interprets token differently, i.e keyword treated as identifier
123505             function fixTokenKind(tokenInfo, container) {
123506                 if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) {
123507                     tokenInfo.token.kind = container.kind;
123508                 }
123509                 return tokenInfo;
123510             }
123511             function skipToEndOf(node) {
123512                 scanner.setTextPos(node.end);
123513                 savedPos = scanner.getStartPos();
123514                 lastScanAction = undefined;
123515                 lastTokenInfo = undefined;
123516                 wasNewLine = false;
123517                 leadingTrivia = undefined;
123518                 trailingTrivia = undefined;
123519             }
123520         }
123521         formatting.getFormattingScanner = getFormattingScanner;
123522     })(formatting = ts.formatting || (ts.formatting = {}));
123523 })(ts || (ts = {}));
123524 /* @internal */
123525 var ts;
123526 (function (ts) {
123527     var formatting;
123528     (function (formatting) {
123529         formatting.anyContext = ts.emptyArray;
123530         var RuleAction;
123531         (function (RuleAction) {
123532             RuleAction[RuleAction["StopProcessingSpaceActions"] = 1] = "StopProcessingSpaceActions";
123533             RuleAction[RuleAction["StopProcessingTokenActions"] = 2] = "StopProcessingTokenActions";
123534             RuleAction[RuleAction["InsertSpace"] = 4] = "InsertSpace";
123535             RuleAction[RuleAction["InsertNewLine"] = 8] = "InsertNewLine";
123536             RuleAction[RuleAction["DeleteSpace"] = 16] = "DeleteSpace";
123537             RuleAction[RuleAction["DeleteToken"] = 32] = "DeleteToken";
123538             RuleAction[RuleAction["InsertTrailingSemicolon"] = 64] = "InsertTrailingSemicolon";
123539             RuleAction[RuleAction["StopAction"] = 3] = "StopAction";
123540             RuleAction[RuleAction["ModifySpaceAction"] = 28] = "ModifySpaceAction";
123541             RuleAction[RuleAction["ModifyTokenAction"] = 96] = "ModifyTokenAction";
123542         })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {}));
123543         var RuleFlags;
123544         (function (RuleFlags) {
123545             RuleFlags[RuleFlags["None"] = 0] = "None";
123546             RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines";
123547         })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {}));
123548     })(formatting = ts.formatting || (ts.formatting = {}));
123549 })(ts || (ts = {}));
123550 /* @internal */
123551 var ts;
123552 (function (ts) {
123553     var formatting;
123554     (function (formatting) {
123555         function getAllRules() {
123556             var allTokens = [];
123557             for (var token = 0 /* FirstToken */; token <= 152 /* LastToken */; token++) {
123558                 if (token !== 1 /* EndOfFileToken */) {
123559                     allTokens.push(token);
123560                 }
123561             }
123562             function anyTokenExcept() {
123563                 var tokens = [];
123564                 for (var _i = 0; _i < arguments.length; _i++) {
123565                     tokens[_i] = arguments[_i];
123566                 }
123567                 return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false };
123568             }
123569             var anyToken = { tokens: allTokens, isSpecific: false };
123570             var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArrays(allTokens, [3 /* MultiLineCommentTrivia */]));
123571             var anyTokenIncludingEOF = tokenRangeFrom(__spreadArrays(allTokens, [1 /* EndOfFileToken */]));
123572             var keywords = tokenRangeFromRange(77 /* FirstKeyword */, 152 /* LastKeyword */);
123573             var binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */, 74 /* LastBinaryOperator */);
123574             var binaryKeywordOperators = [97 /* InKeyword */, 98 /* InstanceOfKeyword */, 152 /* OfKeyword */, 123 /* AsKeyword */, 133 /* IsKeyword */];
123575             var unaryPrefixOperators = [45 /* PlusPlusToken */, 46 /* MinusMinusToken */, 54 /* TildeToken */, 53 /* ExclamationToken */];
123576             var unaryPrefixExpressions = [
123577                 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 75 /* Identifier */, 20 /* OpenParenToken */,
123578                 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */
123579             ];
123580             var unaryPreincrementExpressions = [75 /* Identifier */, 20 /* OpenParenToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */];
123581             var unaryPostincrementExpressions = [75 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 99 /* NewKeyword */];
123582             var unaryPredecrementExpressions = [75 /* Identifier */, 20 /* OpenParenToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */];
123583             var unaryPostdecrementExpressions = [75 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 99 /* NewKeyword */];
123584             var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */];
123585             var typeNames = __spreadArrays([75 /* Identifier */], ts.typeKeywords);
123586             // Place a space before open brace in a function declaration
123587             // TypeScript: Function can have return types, which can be made of tons of different token kinds
123588             var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments;
123589             // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc)
123590             var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([75 /* Identifier */, 3 /* MultiLineCommentTrivia */, 80 /* ClassKeyword */, 89 /* ExportKeyword */, 96 /* ImportKeyword */]);
123591             // Place a space before open brace in a control flow construct
123592             var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 86 /* DoKeyword */, 107 /* TryKeyword */, 92 /* FinallyKeyword */, 87 /* ElseKeyword */]);
123593             // These rules are higher in priority than user-configurable
123594             var highPriorityCommonRules = [
123595                 // Leave comments alone
123596                 rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* StopProcessingSpaceActions */),
123597                 rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* StopProcessingSpaceActions */),
123598                 rule("NotSpaceBeforeColon", anyToken, 58 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */),
123599                 rule("SpaceAfterColon", 58 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 4 /* InsertSpace */),
123600                 rule("NoSpaceBeforeQuestionMark", anyToken, 57 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
123601                 // insert space after '?' only when it is used in conditional operator
123602                 rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */),
123603                 // in other cases there should be no space between '?' and next token
123604                 rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123605                 rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123606                 rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123607                 rule("NoSpaceBetweenImportParenInImportType", 96 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */),
123608                 // Special handling of unary operators.
123609                 // Prefix operators generally shouldn't have a space between
123610                 // them and their target unary expression.
123611                 rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
123612                 rule("NoSpaceAfterUnaryPreincrementOperator", 45 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123613                 rule("NoSpaceAfterUnaryPredecrementOperator", 46 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123614                 rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 45 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
123615                 rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 46 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
123616                 // More unary operator special-casing.
123617                 // DevDiv 181814: Be careful when removing leading whitespace
123618                 // around unary operators.  Examples:
123619                 //      1 - -2  --X--> 1--2
123620                 //      a + ++b --X--> a+++b
123621                 rule("SpaceAfterPostincrementWhenFollowedByAdd", 45 /* PlusPlusToken */, 39 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123622                 rule("SpaceAfterAddWhenFollowedByUnaryPlus", 39 /* PlusToken */, 39 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123623                 rule("SpaceAfterAddWhenFollowedByPreincrement", 39 /* PlusToken */, 45 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123624                 rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 46 /* MinusMinusToken */, 40 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123625                 rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 40 /* MinusToken */, 40 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123626                 rule("SpaceAfterSubtractWhenFollowedByPredecrement", 40 /* MinusToken */, 46 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123627                 rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123628                 // For functions and control block place } on a new line [multi-line rule]
123629                 rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 8 /* InsertNewLine */),
123630                 // Space/new line after }.
123631                 rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 4 /* InsertSpace */),
123632                 // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied
123633                 // Also should not apply to })
123634                 rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 87 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123635                 rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 111 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123636                 rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
123637                 // 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];'
123638                 rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 4 /* InsertSpace */),
123639                 rule("NoSpaceBetweenFunctionKeywordAndStar", 94 /* FunctionKeyword */, 41 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 16 /* DeleteSpace */),
123640                 rule("SpaceAfterStarInGeneratorDeclaration", 41 /* AsteriskToken */, 75 /* Identifier */, [isFunctionDeclarationOrFunctionExpressionContext], 4 /* InsertSpace */),
123641                 rule("SpaceAfterFunctionInFuncDecl", 94 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 4 /* InsertSpace */),
123642                 // Insert new line after { and before } in multi-line contexts.
123643                 rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 8 /* InsertNewLine */),
123644                 // 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.
123645                 // Though, we do extra check on the context to make sure we are dealing with get/set node. Example:
123646                 //      get x() {}
123647                 //      set x(val) {}
123648                 rule("SpaceAfterGetSetInMember", [131 /* GetKeyword */, 142 /* SetKeyword */], 75 /* Identifier */, [isFunctionDeclContext], 4 /* InsertSpace */),
123649                 rule("NoSpaceBetweenYieldKeywordAndStar", 121 /* YieldKeyword */, 41 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 16 /* DeleteSpace */),
123650                 rule("SpaceBetweenYieldOrYieldStarAndOperand", [121 /* YieldKeyword */, 41 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 4 /* InsertSpace */),
123651                 rule("NoSpaceBetweenReturnAndSemicolon", 101 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123652                 rule("SpaceAfterCertainKeywords", [109 /* VarKeyword */, 105 /* ThrowKeyword */, 99 /* NewKeyword */, 85 /* DeleteKeyword */, 101 /* ReturnKeyword */, 108 /* TypeOfKeyword */, 127 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123653                 rule("SpaceAfterLetConstInVariableDeclaration", [115 /* LetKeyword */, 81 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 4 /* InsertSpace */),
123654                 rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 16 /* DeleteSpace */),
123655                 // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options.
123656                 rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123657                 rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123658                 rule("SpaceAfterVoidOperator", 110 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */),
123659                 // Async-await
123660                 rule("SpaceBetweenAsyncAndOpenParen", 126 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123661                 rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, [94 /* FunctionKeyword */, 75 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123662                 // Template string
123663                 rule("NoSpaceBetweenTagAndTemplateString", [75 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123664                 // JSX opening elements
123665                 rule("SpaceBeforeJsxAttribute", anyToken, 75 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123666                 rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 43 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123667                 rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 43 /* SlashToken */, 31 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123668                 rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 62 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123669                 rule("NoSpaceAfterEqualInJsxAttribute", 62 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123670                 // TypeScript-specific rules
123671                 // Use of module as a function call. e.g.: import m2 = module("m2");
123672                 rule("NoSpaceAfterModuleImport", [135 /* ModuleKeyword */, 139 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123673                 // Add a space around certain TypeScript keywords
123674                 rule("SpaceAfterCertainTypeScriptKeywords", [
123675                     122 /* AbstractKeyword */,
123676                     80 /* ClassKeyword */,
123677                     130 /* DeclareKeyword */,
123678                     84 /* DefaultKeyword */,
123679                     88 /* EnumKeyword */,
123680                     89 /* ExportKeyword */,
123681                     90 /* ExtendsKeyword */,
123682                     131 /* GetKeyword */,
123683                     113 /* ImplementsKeyword */,
123684                     96 /* ImportKeyword */,
123685                     114 /* InterfaceKeyword */,
123686                     135 /* ModuleKeyword */,
123687                     136 /* NamespaceKeyword */,
123688                     117 /* PrivateKeyword */,
123689                     119 /* PublicKeyword */,
123690                     118 /* ProtectedKeyword */,
123691                     138 /* ReadonlyKeyword */,
123692                     142 /* SetKeyword */,
123693                     120 /* StaticKeyword */,
123694                     145 /* TypeKeyword */,
123695                     149 /* FromKeyword */,
123696                     134 /* KeyOfKeyword */,
123697                     132 /* InferKeyword */,
123698                 ], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123699                 rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [90 /* ExtendsKeyword */, 113 /* ImplementsKeyword */, 149 /* FromKeyword */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123700                 // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
123701                 rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 4 /* InsertSpace */),
123702                 // Lambda expressions
123703                 rule("SpaceBeforeArrow", anyToken, 38 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123704                 rule("SpaceAfterArrow", 38 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123705                 // Optional parameters and let args
123706                 rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 75 /* Identifier */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123707                 rule("NoSpaceAfterOptionalParameters", 57 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
123708                 // Remove spaces in empty interface literals. e.g.: x: {}
123709                 rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 16 /* DeleteSpace */),
123710                 // generics and type assertions
123711                 rule("NoSpaceBeforeOpenAngularBracket", typeNames, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
123712                 rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
123713                 rule("NoSpaceAfterOpenAngularBracket", 29 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
123714                 rule("NoSpaceBeforeCloseAngularBracket", anyToken, 31 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
123715                 rule("NoSpaceAfterCloseAngularBracket", 31 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 31 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 16 /* DeleteSpace */),
123716                 // decorators
123717                 rule("SpaceBeforeAt", [21 /* CloseParenToken */, 75 /* Identifier */], 59 /* AtToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123718                 rule("NoSpaceAfterAt", 59 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123719                 // Insert space after @ in decorator
123720                 rule("SpaceAfterDecorator", anyToken, [
123721                     122 /* AbstractKeyword */,
123722                     75 /* Identifier */,
123723                     89 /* ExportKeyword */,
123724                     84 /* DefaultKeyword */,
123725                     80 /* ClassKeyword */,
123726                     120 /* StaticKeyword */,
123727                     119 /* PublicKeyword */,
123728                     117 /* PrivateKeyword */,
123729                     118 /* ProtectedKeyword */,
123730                     131 /* GetKeyword */,
123731                     142 /* SetKeyword */,
123732                     22 /* OpenBracketToken */,
123733                     41 /* AsteriskToken */,
123734                 ], [isEndOfDecoratorContextOnSameLine], 4 /* InsertSpace */),
123735                 rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 53 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 16 /* DeleteSpace */),
123736                 rule("NoSpaceAfterNewKeywordOnConstructorSignature", 99 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 16 /* DeleteSpace */),
123737                 rule("SpaceLessThanAndNonJSXTypeAnnotation", 29 /* LessThanToken */, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123738             ];
123739             // These rules are applied after high priority
123740             var userConfigurableRules = [
123741                 // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses
123742                 rule("SpaceAfterConstructor", 129 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123743                 rule("NoSpaceAfterConstructor", 129 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123744                 rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen], 4 /* InsertSpace */),
123745                 rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* DeleteSpace */),
123746                 // Insert space after function keyword for anonymous functions
123747                 rule("SpaceAfterAnonymousFunctionKeyword", [94 /* FunctionKeyword */, 41 /* AsteriskToken */], 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 4 /* InsertSpace */),
123748                 rule("NoSpaceAfterAnonymousFunctionKeyword", [94 /* FunctionKeyword */, 41 /* AsteriskToken */], 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 16 /* DeleteSpace */),
123749                 // Insert space after keywords in control flow statements
123750                 rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 4 /* InsertSpace */),
123751                 rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 16 /* DeleteSpace */),
123752                 // Insert space after opening and before closing nonempty parenthesis
123753                 rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123754                 rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123755                 rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123756                 rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123757                 rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123758                 rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123759                 // Insert space after opening and before closing nonempty brackets
123760                 rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123761                 rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123762                 rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123763                 rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123764                 rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123765                 // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
123766                 rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
123767                 rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
123768                 rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
123769                 rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123770                 rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123771                 // Insert a space after opening and before closing empty brace brackets
123772                 rule("SpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces")], 4 /* InsertSpace */),
123773                 rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123774                 // Insert space after opening and before closing template string braces
123775                 rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123776                 rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123777                 rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123778                 rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123779                 // No space after { and before } in JSX expression
123780                 rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
123781                 rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
123782                 rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
123783                 rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
123784                 // Insert space after semicolon in for statement
123785                 rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 4 /* InsertSpace */),
123786                 rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 16 /* DeleteSpace */),
123787                 // Insert space before and after binary operators
123788                 rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123789                 rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
123790                 rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
123791                 rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
123792                 rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 4 /* InsertSpace */),
123793                 rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 16 /* DeleteSpace */),
123794                 // Open Brace braces after control block
123795                 rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
123796                 // Open Brace braces after function
123797                 // TypeScript: Function can have return types, which can be made of tons of different token kinds
123798                 rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
123799                 // Open Brace braces after TypeScript module/class/interface
123800                 rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
123801                 rule("SpaceAfterTypeAssertion", 31 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 4 /* InsertSpace */),
123802                 rule("NoSpaceAfterTypeAssertion", 31 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 16 /* DeleteSpace */),
123803                 rule("SpaceBeforeTypeAnnotation", anyToken, 58 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 4 /* InsertSpace */),
123804                 rule("NoSpaceBeforeTypeAnnotation", anyToken, 58 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 16 /* DeleteSpace */),
123805                 rule("NoOptionalSemicolon", 26 /* SemicolonToken */, anyTokenIncludingEOF, [optionEquals("semicolons", ts.SemicolonPreference.Remove), isSemicolonDeletionContext], 32 /* DeleteToken */),
123806                 rule("OptionalSemicolon", anyToken, anyTokenIncludingEOF, [optionEquals("semicolons", ts.SemicolonPreference.Insert), isSemicolonInsertionContext], 64 /* InsertTrailingSemicolon */),
123807             ];
123808             // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list.
123809             var lowPriorityCommonRules = [
123810                 // Space after keyword but not before ; or : or ?
123811                 rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123812                 rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
123813                 rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
123814                 rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
123815                 rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123816                 // No space before and after indexer `x[]`
123817                 rule("NoSpaceBeforeOpenBracket", anyTokenExcept(126 /* AsyncKeyword */, 78 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
123818                 rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 16 /* DeleteSpace */),
123819                 rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123820                 // Remove extra space between for and await
123821                 rule("SpaceBetweenForAndAwaitKeyword", 93 /* ForKeyword */, 127 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123822                 // Add a space between statements. All keywords except (do,else,case) has open/close parens after them.
123823                 // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any]
123824                 rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 86 /* DoKeyword */, 87 /* ElseKeyword */, 78 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 4 /* InsertSpace */),
123825                 // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter.
123826                 rule("SpaceAfterTryFinally", [107 /* TryKeyword */, 92 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
123827             ];
123828             return __spreadArrays(highPriorityCommonRules, userConfigurableRules, lowPriorityCommonRules);
123829         }
123830         formatting.getAllRules = getAllRules;
123831         /**
123832          * A rule takes a two tokens (left/right) and a particular context
123833          * for which you're meant to look at them. You then declare what should the
123834          * whitespace annotation be between these tokens via the action param.
123835          *
123836          * @param debugName Name to print
123837          * @param left The left side of the comparison
123838          * @param right The right side of the comparison
123839          * @param context A set of filters to narrow down the space in which this formatter rule applies
123840          * @param action a declaration of the expected whitespace
123841          * @param flags whether the rule deletes a line or not, defaults to no-op
123842          */
123843         function rule(debugName, left, right, context, action, flags) {
123844             if (flags === void 0) { flags = 0 /* None */; }
123845             return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } };
123846         }
123847         function tokenRangeFrom(tokens) {
123848             return { tokens: tokens, isSpecific: true };
123849         }
123850         function toTokenRange(arg) {
123851             return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg;
123852         }
123853         function tokenRangeFromRange(from, to, except) {
123854             if (except === void 0) { except = []; }
123855             var tokens = [];
123856             for (var token = from; token <= to; token++) {
123857                 if (!ts.contains(except, token)) {
123858                     tokens.push(token);
123859                 }
123860             }
123861             return tokenRangeFrom(tokens);
123862         }
123863         ///
123864         /// Contexts
123865         ///
123866         function optionEquals(optionName, optionValue) {
123867             return function (context) { return context.options && context.options[optionName] === optionValue; };
123868         }
123869         function isOptionEnabled(optionName) {
123870             return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; };
123871         }
123872         function isOptionDisabled(optionName) {
123873             return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; };
123874         }
123875         function isOptionDisabledOrUndefined(optionName) {
123876             return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; };
123877         }
123878         function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) {
123879             return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); };
123880         }
123881         function isOptionEnabledOrUndefined(optionName) {
123882             return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; };
123883         }
123884         function isForContext(context) {
123885             return context.contextNode.kind === 230 /* ForStatement */;
123886         }
123887         function isNotForContext(context) {
123888             return !isForContext(context);
123889         }
123890         function isBinaryOpContext(context) {
123891             switch (context.contextNode.kind) {
123892                 case 209 /* BinaryExpression */:
123893                     return context.contextNode.operatorToken.kind !== 27 /* CommaToken */;
123894                 case 210 /* ConditionalExpression */:
123895                 case 180 /* ConditionalType */:
123896                 case 217 /* AsExpression */:
123897                 case 263 /* ExportSpecifier */:
123898                 case 258 /* ImportSpecifier */:
123899                 case 168 /* TypePredicate */:
123900                 case 178 /* UnionType */:
123901                 case 179 /* IntersectionType */:
123902                     return true;
123903                 // equals in binding elements: function foo([[x, y] = [1, 2]])
123904                 case 191 /* BindingElement */:
123905                 // equals in type X = ...
123906                 // falls through
123907                 case 247 /* TypeAliasDeclaration */:
123908                 // equal in import a = module('a');
123909                 // falls through
123910                 case 253 /* ImportEqualsDeclaration */:
123911                 // equal in let a = 0
123912                 // falls through
123913                 case 242 /* VariableDeclaration */:
123914                 // equal in p = 0
123915                 // falls through
123916                 case 156 /* Parameter */:
123917                 case 284 /* EnumMember */:
123918                 case 159 /* PropertyDeclaration */:
123919                 case 158 /* PropertySignature */:
123920                     return context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */;
123921                 // "in" keyword in for (let x in []) { }
123922                 case 231 /* ForInStatement */:
123923                 // "in" keyword in [P in keyof T]: T[P]
123924                 // falls through
123925                 case 155 /* TypeParameter */:
123926                     return context.currentTokenSpan.kind === 97 /* InKeyword */ || context.nextTokenSpan.kind === 97 /* InKeyword */ || context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */;
123927                 // Technically, "of" is not a binary operator, but format it the same way as "in"
123928                 case 232 /* ForOfStatement */:
123929                     return context.currentTokenSpan.kind === 152 /* OfKeyword */ || context.nextTokenSpan.kind === 152 /* OfKeyword */;
123930             }
123931             return false;
123932         }
123933         function isNotBinaryOpContext(context) {
123934             return !isBinaryOpContext(context);
123935         }
123936         function isNotTypeAnnotationContext(context) {
123937             return !isTypeAnnotationContext(context);
123938         }
123939         function isTypeAnnotationContext(context) {
123940             var contextKind = context.contextNode.kind;
123941             return contextKind === 159 /* PropertyDeclaration */ ||
123942                 contextKind === 158 /* PropertySignature */ ||
123943                 contextKind === 156 /* Parameter */ ||
123944                 contextKind === 242 /* VariableDeclaration */ ||
123945                 ts.isFunctionLikeKind(contextKind);
123946         }
123947         function isConditionalOperatorContext(context) {
123948             return context.contextNode.kind === 210 /* ConditionalExpression */ ||
123949                 context.contextNode.kind === 180 /* ConditionalType */;
123950         }
123951         function isSameLineTokenOrBeforeBlockContext(context) {
123952             return context.TokensAreOnSameLine() || isBeforeBlockContext(context);
123953         }
123954         function isBraceWrappedContext(context) {
123955             return context.contextNode.kind === 189 /* ObjectBindingPattern */ ||
123956                 context.contextNode.kind === 186 /* MappedType */ ||
123957                 isSingleLineBlockContext(context);
123958         }
123959         // This check is done before an open brace in a control construct, a function, or a typescript block declaration
123960         function isBeforeMultilineBlockContext(context) {
123961             return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine());
123962         }
123963         function isMultilineBlockContext(context) {
123964             return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
123965         }
123966         function isSingleLineBlockContext(context) {
123967             return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
123968         }
123969         function isBlockContext(context) {
123970             return nodeIsBlockContext(context.contextNode);
123971         }
123972         function isBeforeBlockContext(context) {
123973             return nodeIsBlockContext(context.nextTokenParent);
123974         }
123975         // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children
123976         function nodeIsBlockContext(node) {
123977             if (nodeIsTypeScriptDeclWithBlockContext(node)) {
123978                 // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc).
123979                 return true;
123980             }
123981             switch (node.kind) {
123982                 case 223 /* Block */:
123983                 case 251 /* CaseBlock */:
123984                 case 193 /* ObjectLiteralExpression */:
123985                 case 250 /* ModuleBlock */:
123986                     return true;
123987             }
123988             return false;
123989         }
123990         function isFunctionDeclContext(context) {
123991             switch (context.contextNode.kind) {
123992                 case 244 /* FunctionDeclaration */:
123993                 case 161 /* MethodDeclaration */:
123994                 case 160 /* MethodSignature */:
123995                 // case SyntaxKind.MemberFunctionDeclaration:
123996                 // falls through
123997                 case 163 /* GetAccessor */:
123998                 case 164 /* SetAccessor */:
123999                 // case SyntaxKind.MethodSignature:
124000                 // falls through
124001                 case 165 /* CallSignature */:
124002                 case 201 /* FunctionExpression */:
124003                 case 162 /* Constructor */:
124004                 case 202 /* ArrowFunction */:
124005                 // case SyntaxKind.ConstructorDeclaration:
124006                 // case SyntaxKind.SimpleArrowFunctionExpression:
124007                 // case SyntaxKind.ParenthesizedArrowFunctionExpression:
124008                 // falls through
124009                 case 246 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
124010                     return true;
124011             }
124012             return false;
124013         }
124014         function isNotFunctionDeclContext(context) {
124015             return !isFunctionDeclContext(context);
124016         }
124017         function isFunctionDeclarationOrFunctionExpressionContext(context) {
124018             return context.contextNode.kind === 244 /* FunctionDeclaration */ || context.contextNode.kind === 201 /* FunctionExpression */;
124019         }
124020         function isTypeScriptDeclWithBlockContext(context) {
124021             return nodeIsTypeScriptDeclWithBlockContext(context.contextNode);
124022         }
124023         function nodeIsTypeScriptDeclWithBlockContext(node) {
124024             switch (node.kind) {
124025                 case 245 /* ClassDeclaration */:
124026                 case 214 /* ClassExpression */:
124027                 case 246 /* InterfaceDeclaration */:
124028                 case 248 /* EnumDeclaration */:
124029                 case 173 /* TypeLiteral */:
124030                 case 249 /* ModuleDeclaration */:
124031                 case 260 /* ExportDeclaration */:
124032                 case 261 /* NamedExports */:
124033                 case 254 /* ImportDeclaration */:
124034                 case 257 /* NamedImports */:
124035                     return true;
124036             }
124037             return false;
124038         }
124039         function isAfterCodeBlockContext(context) {
124040             switch (context.currentTokenParent.kind) {
124041                 case 245 /* ClassDeclaration */:
124042                 case 249 /* ModuleDeclaration */:
124043                 case 248 /* EnumDeclaration */:
124044                 case 280 /* CatchClause */:
124045                 case 250 /* ModuleBlock */:
124046                 case 237 /* SwitchStatement */:
124047                     return true;
124048                 case 223 /* Block */: {
124049                     var blockParent = context.currentTokenParent.parent;
124050                     // In a codefix scenario, we can't rely on parents being set. So just always return true.
124051                     if (!blockParent || blockParent.kind !== 202 /* ArrowFunction */ && blockParent.kind !== 201 /* FunctionExpression */) {
124052                         return true;
124053                     }
124054                 }
124055             }
124056             return false;
124057         }
124058         function isControlDeclContext(context) {
124059             switch (context.contextNode.kind) {
124060                 case 227 /* IfStatement */:
124061                 case 237 /* SwitchStatement */:
124062                 case 230 /* ForStatement */:
124063                 case 231 /* ForInStatement */:
124064                 case 232 /* ForOfStatement */:
124065                 case 229 /* WhileStatement */:
124066                 case 240 /* TryStatement */:
124067                 case 228 /* DoStatement */:
124068                 case 236 /* WithStatement */:
124069                 // TODO
124070                 // case SyntaxKind.ElseClause:
124071                 // falls through
124072                 case 280 /* CatchClause */:
124073                     return true;
124074                 default:
124075                     return false;
124076             }
124077         }
124078         function isObjectContext(context) {
124079             return context.contextNode.kind === 193 /* ObjectLiteralExpression */;
124080         }
124081         function isFunctionCallContext(context) {
124082             return context.contextNode.kind === 196 /* CallExpression */;
124083         }
124084         function isNewContext(context) {
124085             return context.contextNode.kind === 197 /* NewExpression */;
124086         }
124087         function isFunctionCallOrNewContext(context) {
124088             return isFunctionCallContext(context) || isNewContext(context);
124089         }
124090         function isPreviousTokenNotComma(context) {
124091             return context.currentTokenSpan.kind !== 27 /* CommaToken */;
124092         }
124093         function isNextTokenNotCloseBracket(context) {
124094             return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */;
124095         }
124096         function isNextTokenNotCloseParen(context) {
124097             return context.nextTokenSpan.kind !== 21 /* CloseParenToken */;
124098         }
124099         function isArrowFunctionContext(context) {
124100             return context.contextNode.kind === 202 /* ArrowFunction */;
124101         }
124102         function isImportTypeContext(context) {
124103             return context.contextNode.kind === 188 /* ImportType */;
124104         }
124105         function isNonJsxSameLineTokenContext(context) {
124106             return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */;
124107         }
124108         function isNonJsxElementOrFragmentContext(context) {
124109             return context.contextNode.kind !== 266 /* JsxElement */ && context.contextNode.kind !== 270 /* JsxFragment */;
124110         }
124111         function isJsxExpressionContext(context) {
124112             return context.contextNode.kind === 276 /* JsxExpression */ || context.contextNode.kind === 275 /* JsxSpreadAttribute */;
124113         }
124114         function isNextTokenParentJsxAttribute(context) {
124115             return context.nextTokenParent.kind === 273 /* JsxAttribute */;
124116         }
124117         function isJsxAttributeContext(context) {
124118             return context.contextNode.kind === 273 /* JsxAttribute */;
124119         }
124120         function isJsxSelfClosingElementContext(context) {
124121             return context.contextNode.kind === 267 /* JsxSelfClosingElement */;
124122         }
124123         function isNotBeforeBlockInFunctionDeclarationContext(context) {
124124             return !isFunctionDeclContext(context) && !isBeforeBlockContext(context);
124125         }
124126         function isEndOfDecoratorContextOnSameLine(context) {
124127             return context.TokensAreOnSameLine() &&
124128                 !!context.contextNode.decorators &&
124129                 nodeIsInDecoratorContext(context.currentTokenParent) &&
124130                 !nodeIsInDecoratorContext(context.nextTokenParent);
124131         }
124132         function nodeIsInDecoratorContext(node) {
124133             while (ts.isExpressionNode(node)) {
124134                 node = node.parent;
124135             }
124136             return node.kind === 157 /* Decorator */;
124137         }
124138         function isStartOfVariableDeclarationList(context) {
124139             return context.currentTokenParent.kind === 243 /* VariableDeclarationList */ &&
124140                 context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
124141         }
124142         function isNotFormatOnEnter(context) {
124143             return context.formattingRequestKind !== 2 /* FormatOnEnter */;
124144         }
124145         function isModuleDeclContext(context) {
124146             return context.contextNode.kind === 249 /* ModuleDeclaration */;
124147         }
124148         function isObjectTypeContext(context) {
124149             return context.contextNode.kind === 173 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
124150         }
124151         function isConstructorSignatureContext(context) {
124152             return context.contextNode.kind === 166 /* ConstructSignature */;
124153         }
124154         function isTypeArgumentOrParameterOrAssertion(token, parent) {
124155             if (token.kind !== 29 /* LessThanToken */ && token.kind !== 31 /* GreaterThanToken */) {
124156                 return false;
124157             }
124158             switch (parent.kind) {
124159                 case 169 /* TypeReference */:
124160                 case 199 /* TypeAssertionExpression */:
124161                 case 247 /* TypeAliasDeclaration */:
124162                 case 245 /* ClassDeclaration */:
124163                 case 214 /* ClassExpression */:
124164                 case 246 /* InterfaceDeclaration */:
124165                 case 244 /* FunctionDeclaration */:
124166                 case 201 /* FunctionExpression */:
124167                 case 202 /* ArrowFunction */:
124168                 case 161 /* MethodDeclaration */:
124169                 case 160 /* MethodSignature */:
124170                 case 165 /* CallSignature */:
124171                 case 166 /* ConstructSignature */:
124172                 case 196 /* CallExpression */:
124173                 case 197 /* NewExpression */:
124174                 case 216 /* ExpressionWithTypeArguments */:
124175                     return true;
124176                 default:
124177                     return false;
124178             }
124179         }
124180         function isTypeArgumentOrParameterOrAssertionContext(context) {
124181             return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) ||
124182                 isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
124183         }
124184         function isTypeAssertionContext(context) {
124185             return context.contextNode.kind === 199 /* TypeAssertionExpression */;
124186         }
124187         function isVoidOpContext(context) {
124188             return context.currentTokenSpan.kind === 110 /* VoidKeyword */ && context.currentTokenParent.kind === 205 /* VoidExpression */;
124189         }
124190         function isYieldOrYieldStarWithOperand(context) {
124191             return context.contextNode.kind === 212 /* YieldExpression */ && context.contextNode.expression !== undefined;
124192         }
124193         function isNonNullAssertionContext(context) {
124194             return context.contextNode.kind === 218 /* NonNullExpression */;
124195         }
124196         function isNotStatementConditionContext(context) {
124197             return !isStatementConditionContext(context);
124198         }
124199         function isStatementConditionContext(context) {
124200             switch (context.contextNode.kind) {
124201                 case 227 /* IfStatement */:
124202                 case 230 /* ForStatement */:
124203                 case 231 /* ForInStatement */:
124204                 case 232 /* ForOfStatement */:
124205                 case 228 /* DoStatement */:
124206                 case 229 /* WhileStatement */:
124207                     return true;
124208                 default:
124209                     return false;
124210             }
124211         }
124212         function isSemicolonDeletionContext(context) {
124213             var nextTokenKind = context.nextTokenSpan.kind;
124214             var nextTokenStart = context.nextTokenSpan.pos;
124215             if (ts.isTrivia(nextTokenKind)) {
124216                 var nextRealToken = context.nextTokenParent === context.currentTokenParent
124217                     ? ts.findNextToken(context.currentTokenParent, ts.findAncestor(context.currentTokenParent, function (a) { return !a.parent; }), context.sourceFile)
124218                     : context.nextTokenParent.getFirstToken(context.sourceFile);
124219                 if (!nextRealToken) {
124220                     return true;
124221                 }
124222                 nextTokenKind = nextRealToken.kind;
124223                 nextTokenStart = nextRealToken.getStart(context.sourceFile);
124224             }
124225             var startLine = context.sourceFile.getLineAndCharacterOfPosition(context.currentTokenSpan.pos).line;
124226             var endLine = context.sourceFile.getLineAndCharacterOfPosition(nextTokenStart).line;
124227             if (startLine === endLine) {
124228                 return nextTokenKind === 19 /* CloseBraceToken */
124229                     || nextTokenKind === 1 /* EndOfFileToken */;
124230             }
124231             if (nextTokenKind === 222 /* SemicolonClassElement */ ||
124232                 nextTokenKind === 26 /* SemicolonToken */) {
124233                 return false;
124234             }
124235             if (context.contextNode.kind === 246 /* InterfaceDeclaration */ ||
124236                 context.contextNode.kind === 247 /* TypeAliasDeclaration */) {
124237                 // Can’t remove semicolon after `foo`; it would parse as a method declaration:
124238                 //
124239                 // interface I {
124240                 //   foo;
124241                 //   (): void
124242                 // }
124243                 return !ts.isPropertySignature(context.currentTokenParent)
124244                     || !!context.currentTokenParent.type
124245                     || nextTokenKind !== 20 /* OpenParenToken */;
124246             }
124247             if (ts.isPropertyDeclaration(context.currentTokenParent)) {
124248                 return !context.currentTokenParent.initializer;
124249             }
124250             return context.currentTokenParent.kind !== 230 /* ForStatement */
124251                 && context.currentTokenParent.kind !== 224 /* EmptyStatement */
124252                 && context.currentTokenParent.kind !== 222 /* SemicolonClassElement */
124253                 && nextTokenKind !== 22 /* OpenBracketToken */
124254                 && nextTokenKind !== 20 /* OpenParenToken */
124255                 && nextTokenKind !== 39 /* PlusToken */
124256                 && nextTokenKind !== 40 /* MinusToken */
124257                 && nextTokenKind !== 43 /* SlashToken */
124258                 && nextTokenKind !== 13 /* RegularExpressionLiteral */
124259                 && nextTokenKind !== 27 /* CommaToken */
124260                 && nextTokenKind !== 211 /* TemplateExpression */
124261                 && nextTokenKind !== 15 /* TemplateHead */
124262                 && nextTokenKind !== 14 /* NoSubstitutionTemplateLiteral */
124263                 && nextTokenKind !== 24 /* DotToken */;
124264         }
124265         function isSemicolonInsertionContext(context) {
124266             return ts.positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile);
124267         }
124268     })(formatting = ts.formatting || (ts.formatting = {}));
124269 })(ts || (ts = {}));
124270 /* @internal */
124271 var ts;
124272 (function (ts) {
124273     var formatting;
124274     (function (formatting) {
124275         function getFormatContext(options, host) {
124276             return { options: options, getRules: getRulesMap(), host: host };
124277         }
124278         formatting.getFormatContext = getFormatContext;
124279         var rulesMapCache;
124280         function getRulesMap() {
124281             if (rulesMapCache === undefined) {
124282                 rulesMapCache = createRulesMap(formatting.getAllRules());
124283             }
124284             return rulesMapCache;
124285         }
124286         /**
124287          * For a given rule action, gets a mask of other rule actions that
124288          * cannot be applied at the same position.
124289          */
124290         function getRuleActionExclusion(ruleAction) {
124291             var mask = 0;
124292             if (ruleAction & 1 /* StopProcessingSpaceActions */) {
124293                 mask |= 28 /* ModifySpaceAction */;
124294             }
124295             if (ruleAction & 2 /* StopProcessingTokenActions */) {
124296                 mask |= 96 /* ModifyTokenAction */;
124297             }
124298             if (ruleAction & 28 /* ModifySpaceAction */) {
124299                 mask |= 28 /* ModifySpaceAction */;
124300             }
124301             if (ruleAction & 96 /* ModifyTokenAction */) {
124302                 mask |= 96 /* ModifyTokenAction */;
124303             }
124304             return mask;
124305         }
124306         function createRulesMap(rules) {
124307             var map = buildMap(rules);
124308             return function (context) {
124309                 var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)];
124310                 if (bucket) {
124311                     var rules_1 = [];
124312                     var ruleActionMask = 0;
124313                     for (var _i = 0, bucket_1 = bucket; _i < bucket_1.length; _i++) {
124314                         var rule = bucket_1[_i];
124315                         var acceptRuleActions = ~getRuleActionExclusion(ruleActionMask);
124316                         if (rule.action & acceptRuleActions && ts.every(rule.context, function (c) { return c(context); })) {
124317                             rules_1.push(rule);
124318                             ruleActionMask |= rule.action;
124319                         }
124320                     }
124321                     if (rules_1.length) {
124322                         return rules_1;
124323                     }
124324                 }
124325             };
124326         }
124327         function buildMap(rules) {
124328             // Map from bucket index to array of rules
124329             var map = new Array(mapRowLength * mapRowLength);
124330             // This array is used only during construction of the rulesbucket in the map
124331             var rulesBucketConstructionStateList = new Array(map.length);
124332             for (var _i = 0, rules_2 = rules; _i < rules_2.length; _i++) {
124333                 var rule = rules_2[_i];
124334                 var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
124335                 for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
124336                     var left = _b[_a];
124337                     for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
124338                         var right = _d[_c];
124339                         var index = getRuleBucketIndex(left, right);
124340                         var rulesBucket = map[index];
124341                         if (rulesBucket === undefined) {
124342                             rulesBucket = map[index] = [];
124343                         }
124344                         addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
124345                     }
124346                 }
124347             }
124348             return map;
124349         }
124350         function getRuleBucketIndex(row, column) {
124351             ts.Debug.assert(row <= 152 /* LastKeyword */ && column <= 152 /* LastKeyword */, "Must compute formatting context from tokens");
124352             return (row * mapRowLength) + column;
124353         }
124354         var maskBitSize = 5;
124355         var mask = 31; // MaskBitSize bits
124356         var mapRowLength = 152 /* LastToken */ + 1;
124357         var RulesPosition;
124358         (function (RulesPosition) {
124359             RulesPosition[RulesPosition["StopRulesSpecific"] = 0] = "StopRulesSpecific";
124360             RulesPosition[RulesPosition["StopRulesAny"] = maskBitSize * 1] = "StopRulesAny";
124361             RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific";
124362             RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny";
124363             RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific";
124364             RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny";
124365         })(RulesPosition || (RulesPosition = {}));
124366         // The Rules list contains all the inserted rules into a rulebucket in the following order:
124367         //    1- Ignore rules with specific token combination
124368         //    2- Ignore rules with any token combination
124369         //    3- Context rules with specific token combination
124370         //    4- Context rules with any token combination
124371         //    5- Non-context rules with specific token combination
124372         //    6- Non-context rules with any token combination
124373         //
124374         // The member rulesInsertionIndexBitmap is used to describe the number of rules
124375         // in each sub-bucket (above) hence can be used to know the index of where to insert
124376         // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits.
124377         //
124378         // Example:
124379         // In order to insert a rule to the end of sub-bucket (3), we get the index by adding
124380         // the values in the bitmap segments 3rd, 2nd, and 1st.
124381         function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) {
124382             var position = rule.action & 3 /* StopAction */ ?
124383                 specificTokens ? RulesPosition.StopRulesSpecific : RulesPosition.StopRulesAny :
124384                 rule.context !== formatting.anyContext ?
124385                     specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny :
124386                     specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny;
124387             var state = constructionState[rulesBucketIndex] || 0;
124388             rules.splice(getInsertionIndex(state, position), 0, rule);
124389             constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position);
124390         }
124391         function getInsertionIndex(indexBitmap, maskPosition) {
124392             var index = 0;
124393             for (var pos = 0; pos <= maskPosition; pos += maskBitSize) {
124394                 index += indexBitmap & mask;
124395                 indexBitmap >>= maskBitSize;
124396             }
124397             return index;
124398         }
124399         function increaseInsertionIndex(indexBitmap, maskPosition) {
124400             var value = ((indexBitmap >> maskPosition) & mask) + 1;
124401             ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
124402             return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition);
124403         }
124404     })(formatting = ts.formatting || (ts.formatting = {}));
124405 })(ts || (ts = {}));
124406 /* @internal */
124407 var ts;
124408 (function (ts) {
124409     var formatting;
124410     (function (formatting) {
124411         function createTextRangeWithKind(pos, end, kind) {
124412             var textRangeWithKind = { pos: pos, end: end, kind: kind };
124413             if (ts.Debug.isDebugging) {
124414                 Object.defineProperty(textRangeWithKind, "__debugKind", {
124415                     get: function () { return ts.Debug.formatSyntaxKind(kind); },
124416                 });
124417             }
124418             return textRangeWithKind;
124419         }
124420         formatting.createTextRangeWithKind = createTextRangeWithKind;
124421         var Constants;
124422         (function (Constants) {
124423             Constants[Constants["Unknown"] = -1] = "Unknown";
124424         })(Constants || (Constants = {}));
124425         function formatOnEnter(position, sourceFile, formatContext) {
124426             var line = sourceFile.getLineAndCharacterOfPosition(position).line;
124427             if (line === 0) {
124428                 return [];
124429             }
124430             // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
124431             // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
124432             // trailing whitespaces. So the end of the formatting span should be the later one between:
124433             //  1. the end of the previous line
124434             //  2. the last non-whitespace character in the current line
124435             var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile);
124436             while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) {
124437                 endOfFormatSpan--;
124438             }
124439             // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to
124440             // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the
124441             // previous character before the end of format span is line break character as well.
124442             if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
124443                 endOfFormatSpan--;
124444             }
124445             var span = {
124446                 // get start position for the previous line
124447                 pos: ts.getStartPositionOfLine(line - 1, sourceFile),
124448                 // end value is exclusive so add 1 to the result
124449                 end: endOfFormatSpan + 1
124450             };
124451             return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */);
124452         }
124453         formatting.formatOnEnter = formatOnEnter;
124454         function formatOnSemicolon(position, sourceFile, formatContext) {
124455             var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile);
124456             return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */);
124457         }
124458         formatting.formatOnSemicolon = formatOnSemicolon;
124459         function formatOnOpeningCurly(position, sourceFile, formatContext) {
124460             var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile);
124461             if (!openingCurly) {
124462                 return [];
124463             }
124464             var curlyBraceRange = openingCurly.parent;
124465             var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange);
124466             /**
124467              * We limit the span to end at the opening curly to handle the case where
124468              * the brace matched to that just typed will be incorrect after further edits.
124469              * For example, we could type the opening curly for the following method
124470              * body without brace-matching activated:
124471              * ```
124472              * class C {
124473              *     foo()
124474              * }
124475              * ```
124476              * and we wouldn't want to move the closing brace.
124477              */
124478             var textRange = {
124479                 pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile),
124480                 end: position
124481             };
124482             return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */);
124483         }
124484         formatting.formatOnOpeningCurly = formatOnOpeningCurly;
124485         function formatOnClosingCurly(position, sourceFile, formatContext) {
124486             var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile);
124487             return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */);
124488         }
124489         formatting.formatOnClosingCurly = formatOnClosingCurly;
124490         function formatDocument(sourceFile, formatContext) {
124491             var span = {
124492                 pos: 0,
124493                 end: sourceFile.text.length
124494             };
124495             return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */);
124496         }
124497         formatting.formatDocument = formatDocument;
124498         function formatSelection(start, end, sourceFile, formatContext) {
124499             // format from the beginning of the line
124500             var span = {
124501                 pos: ts.getLineStartPositionForPosition(start, sourceFile),
124502                 end: end,
124503             };
124504             return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */);
124505         }
124506         formatting.formatSelection = formatSelection;
124507         /**
124508          * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment).
124509          * @param expectedTokenKind The kind of the last token constituting the desired parent node.
124510          */
124511         function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) {
124512             var precedingToken = ts.findPrecedingToken(end, sourceFile);
124513             return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ?
124514                 precedingToken :
124515                 undefined;
124516         }
124517         /**
124518          * Finds the highest node enclosing `node` at the same list level as `node`
124519          * and whose end does not exceed `node.end`.
124520          *
124521          * Consider typing the following
124522          * ```
124523          * let x = 1;
124524          * while (true) {
124525          * }
124526          * ```
124527          * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding
124528          * variable declaration.
124529          */
124530         function findOutermostNodeWithinListLevel(node) {
124531             var current = node;
124532             while (current &&
124533                 current.parent &&
124534                 current.parent.end === node.end &&
124535                 !isListElement(current.parent, current)) {
124536                 current = current.parent;
124537             }
124538             return current;
124539         }
124540         // Returns true if node is a element in some list in parent
124541         // i.e. parent is class declaration with the list of members and node is one of members.
124542         function isListElement(parent, node) {
124543             switch (parent.kind) {
124544                 case 245 /* ClassDeclaration */:
124545                 case 246 /* InterfaceDeclaration */:
124546                     return ts.rangeContainsRange(parent.members, node);
124547                 case 249 /* ModuleDeclaration */:
124548                     var body = parent.body;
124549                     return !!body && body.kind === 250 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
124550                 case 290 /* SourceFile */:
124551                 case 223 /* Block */:
124552                 case 250 /* ModuleBlock */:
124553                     return ts.rangeContainsRange(parent.statements, node);
124554                 case 280 /* CatchClause */:
124555                     return ts.rangeContainsRange(parent.block.statements, node);
124556             }
124557             return false;
124558         }
124559         /** find node that fully contains given text range */
124560         function findEnclosingNode(range, sourceFile) {
124561             return find(sourceFile);
124562             function find(n) {
124563                 var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; });
124564                 if (candidate) {
124565                     var result = find(candidate);
124566                     if (result) {
124567                         return result;
124568                     }
124569                 }
124570                 return n;
124571             }
124572         }
124573         /** formatting is not applied to ranges that contain parse errors.
124574          * This function will return a predicate that for a given text range will tell
124575          * if there are any parse errors that overlap with the range.
124576          */
124577         function prepareRangeContainsErrorFunction(errors, originalRange) {
124578             if (!errors.length) {
124579                 return rangeHasNoErrors;
124580             }
124581             // pick only errors that fall in range
124582             var sorted = errors
124583                 .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217
124584                 .sort(function (e1, e2) { return e1.start - e2.start; });
124585             if (!sorted.length) {
124586                 return rangeHasNoErrors;
124587             }
124588             var index = 0;
124589             return function (r) {
124590                 // in current implementation sequence of arguments [r1, r2...] is monotonically increasing.
124591                 // 'index' tracks the index of the most recent error that was checked.
124592                 while (true) {
124593                     if (index >= sorted.length) {
124594                         // all errors in the range were already checked -> no error in specified range
124595                         return false;
124596                     }
124597                     var error = sorted[index];
124598                     if (r.end <= error.start) {
124599                         // specified range ends before the error referred by 'index' - no error in range
124600                         return false;
124601                     }
124602                     if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) {
124603                         // specified range overlaps with error range
124604                         return true;
124605                     }
124606                     index++;
124607                 }
124608             };
124609             function rangeHasNoErrors() {
124610                 return false;
124611             }
124612         }
124613         /**
124614          * Start of the original range might fall inside the comment - scanner will not yield appropriate results
124615          * This function will look for token that is located before the start of target range
124616          * and return its end as start position for the scanner.
124617          */
124618         function getScanStartPosition(enclosingNode, originalRange, sourceFile) {
124619             var start = enclosingNode.getStart(sourceFile);
124620             if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
124621                 return start;
124622             }
124623             var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile);
124624             if (!precedingToken) {
124625                 // no preceding token found - start from the beginning of enclosing node
124626                 return enclosingNode.pos;
124627             }
124628             // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal)
124629             // start from the beginning of enclosingNode to handle the entire 'originalRange'
124630             if (precedingToken.end >= originalRange.pos) {
124631                 return enclosingNode.pos;
124632             }
124633             return precedingToken.end;
124634         }
124635         /*
124636          * For cases like
124637          * if (a ||
124638          *     b ||$
124639          *     c) {...}
124640          * If we hit Enter at $ we want line '    b ||' to be indented.
124641          * Formatting will be applied to the last two lines.
124642          * Node that fully encloses these lines is binary expression 'a ||...'.
124643          * Initial indentation for this node will be 0.
124644          * Binary expressions don't introduce new indentation scopes, however it is possible
124645          * that some parent node on the same line does - like if statement in this case.
124646          * Note that we are considering parents only from the same line with initial node -
124647          * if parent is on the different line - its delta was already contributed
124648          * to the initial indentation.
124649          */
124650         function getOwnOrInheritedDelta(n, options, sourceFile) {
124651             var previousLine = -1 /* Unknown */;
124652             var child;
124653             while (n) {
124654                 var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
124655                 if (previousLine !== -1 /* Unknown */ && line !== previousLine) {
124656                     break;
124657                 }
124658                 if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) {
124659                     return options.indentSize;
124660                 }
124661                 previousLine = line;
124662                 child = n;
124663                 n = n.parent;
124664             }
124665             return 0;
124666         }
124667         function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) {
124668             var range = { pos: 0, end: sourceFileLike.text.length };
124669             return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors
124670             sourceFileLike); });
124671         }
124672         formatting.formatNodeGivenIndentation = formatNodeGivenIndentation;
124673         function formatNodeLines(node, sourceFile, formatContext, requestKind) {
124674             if (!node) {
124675                 return [];
124676             }
124677             var span = {
124678                 pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile),
124679                 end: node.end
124680             };
124681             return formatSpan(span, sourceFile, formatContext, requestKind);
124682         }
124683         function formatSpan(originalRange, sourceFile, formatContext, requestKind) {
124684             // find the smallest node that fully wraps the range and compute the initial indentation for the node
124685             var enclosingNode = findEnclosingNode(originalRange, sourceFile);
124686             return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); });
124687         }
124688         function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) {
124689             var options = _a.options, getRules = _a.getRules, host = _a.host;
124690             // formatting context is used by rules provider
124691             var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options);
124692             var previousRange;
124693             var previousParent;
124694             var previousRangeStartLine;
124695             var lastIndentedLine;
124696             var indentationOnLastIndentedLine = -1 /* Unknown */;
124697             var edits = [];
124698             formattingScanner.advance();
124699             if (formattingScanner.isOnToken()) {
124700                 var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
124701                 var undecoratedStartLine = startLine;
124702                 if (enclosingNode.decorators) {
124703                     undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
124704                 }
124705                 processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
124706             }
124707             if (!formattingScanner.isOnToken()) {
124708                 var leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
124709                 if (leadingTrivia) {
124710                     indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); });
124711                     if (options.trimTrailingWhitespace !== false) {
124712                         trimTrailingWhitespacesForRemainingRange();
124713                     }
124714                 }
124715             }
124716             return edits;
124717             // local functions
124718             /** Tries to compute the indentation for a list element.
124719              * If list element is not in range then
124720              * function will pick its actual indentation
124721              * so it can be pushed downstream as inherited indentation.
124722              * If list element is in the range - its indentation will be equal
124723              * to inherited indentation from its predecessors.
124724              */
124725             function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) {
124726                 if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) ||
124727                     ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
124728                     if (inheritedIndentation !== -1 /* Unknown */) {
124729                         return inheritedIndentation;
124730                     }
124731                 }
124732                 else {
124733                     var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
124734                     var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile);
124735                     var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
124736                     if (startLine !== parentStartLine || startPos === column) {
124737                         // Use the base indent size if it is greater than
124738                         // the indentation of the inherited predecessor.
124739                         var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options);
124740                         return baseIndentSize > column ? baseIndentSize : column;
124741                     }
124742                 }
124743                 return -1 /* Unknown */;
124744             }
124745             function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) {
124746                 var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
124747                 if (effectiveParentStartLine === startLine) {
124748                     // if node is located on the same line with the parent
124749                     // - inherit indentation from the parent
124750                     // - push children if either parent of node itself has non-zero delta
124751                     return {
124752                         indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(),
124753                         delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta)
124754                     };
124755                 }
124756                 else if (inheritedIndentation === -1 /* Unknown */) {
124757                     if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) {
124758                         // the is used for chaining methods formatting
124759                         // - we need to get the indentation on last line and the delta of parent
124760                         return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) };
124761                     }
124762                     else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
124763                         return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
124764                     }
124765                     else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) {
124766                         return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
124767                     }
124768                     else {
124769                         return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta };
124770                     }
124771                 }
124772                 else {
124773                     return { indentation: inheritedIndentation, delta: delta };
124774                 }
124775             }
124776             function getFirstNonDecoratorTokenOfNode(node) {
124777                 if (node.modifiers && node.modifiers.length) {
124778                     return node.modifiers[0].kind;
124779                 }
124780                 switch (node.kind) {
124781                     case 245 /* ClassDeclaration */: return 80 /* ClassKeyword */;
124782                     case 246 /* InterfaceDeclaration */: return 114 /* InterfaceKeyword */;
124783                     case 244 /* FunctionDeclaration */: return 94 /* FunctionKeyword */;
124784                     case 248 /* EnumDeclaration */: return 248 /* EnumDeclaration */;
124785                     case 163 /* GetAccessor */: return 131 /* GetKeyword */;
124786                     case 164 /* SetAccessor */: return 142 /* SetKeyword */;
124787                     case 161 /* MethodDeclaration */:
124788                         if (node.asteriskToken) {
124789                             return 41 /* AsteriskToken */;
124790                         }
124791                     // falls through
124792                     case 159 /* PropertyDeclaration */:
124793                     case 156 /* Parameter */:
124794                         var name = ts.getNameOfDeclaration(node);
124795                         if (name) {
124796                             return name.kind;
124797                         }
124798                 }
124799             }
124800             function getDynamicIndentation(node, nodeStartLine, indentation, delta) {
124801                 return {
124802                     getIndentationForComment: function (kind, tokenIndentation, container) {
124803                         switch (kind) {
124804                             // preceding comment to the token that closes the indentation scope inherits the indentation from the scope
124805                             // ..  {
124806                             //     // comment
124807                             // }
124808                             case 19 /* CloseBraceToken */:
124809                             case 23 /* CloseBracketToken */:
124810                             case 21 /* CloseParenToken */:
124811                                 return indentation + getDelta(container);
124812                         }
124813                         return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation;
124814                     },
124815                     // if list end token is LessThanToken '>' then its delta should be explicitly suppressed
124816                     // so that LessThanToken as a binary operator can still be indented.
124817                     // foo.then
124818                     //     <
124819                     //         number,
124820                     //         string,
124821                     //     >();
124822                     // vs
124823                     // var a = xValue
124824                     //     > yValue;
124825                     getIndentationForToken: function (line, kind, container, suppressDelta) {
124826                         return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation;
124827                     },
124828                     getIndentation: function () { return indentation; },
124829                     getDelta: getDelta,
124830                     recomputeIndentation: function (lineAdded, parent) {
124831                         if (formatting.SmartIndenter.shouldIndentChildNode(options, parent, node, sourceFile)) {
124832                             indentation += lineAdded ? options.indentSize : -options.indentSize;
124833                             delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
124834                         }
124835                     }
124836                 };
124837                 function shouldAddDelta(line, kind, container) {
124838                     switch (kind) {
124839                         // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent
124840                         case 18 /* OpenBraceToken */:
124841                         case 19 /* CloseBraceToken */:
124842                         case 21 /* CloseParenToken */:
124843                         case 87 /* ElseKeyword */:
124844                         case 111 /* WhileKeyword */:
124845                         case 59 /* AtToken */:
124846                             return false;
124847                         case 43 /* SlashToken */:
124848                         case 31 /* GreaterThanToken */:
124849                             switch (container.kind) {
124850                                 case 268 /* JsxOpeningElement */:
124851                                 case 269 /* JsxClosingElement */:
124852                                 case 267 /* JsxSelfClosingElement */:
124853                                     return false;
124854                             }
124855                             break;
124856                         case 22 /* OpenBracketToken */:
124857                         case 23 /* CloseBracketToken */:
124858                             if (container.kind !== 186 /* MappedType */) {
124859                                 return false;
124860                             }
124861                             break;
124862                     }
124863                     // if token line equals to the line of containing node (this is a first token in the node) - use node indentation
124864                     return nodeStartLine !== line
124865                         // if this token is the first token following the list of decorators, we do not need to indent
124866                         && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node));
124867                 }
124868                 function getDelta(child) {
124869                     // Delta value should be zero when the node explicitly prevents indentation of the child node
124870                     return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0;
124871                 }
124872             }
124873             function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) {
124874                 if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) {
124875                     return;
124876                 }
124877                 var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta);
124878                 // a useful observations when tracking context node
124879                 //        /
124880                 //      [a]
124881                 //   /   |   \
124882                 //  [b] [c] [d]
124883                 // node 'a' is a context node for nodes 'b', 'c', 'd'
124884                 // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a'
124885                 // this rule can be applied recursively to child nodes of 'a'.
124886                 //
124887                 // context node is set to parent node value after processing every child node
124888                 // context node is set to parent of the token after processing every token
124889                 var childContextNode = contextNode;
124890                 // if there are any tokens that logically belong to node and interleave child nodes
124891                 // such tokens will be consumed in processChildNode for the child that follows them
124892                 ts.forEachChild(node, function (child) {
124893                     processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false);
124894                 }, function (nodes) {
124895                     processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
124896                 });
124897                 // proceed any tokens in the node that are located after child nodes
124898                 while (formattingScanner.isOnToken()) {
124899                     var tokenInfo = formattingScanner.readTokenInfo(node);
124900                     if (tokenInfo.token.end > node.end) {
124901                         break;
124902                     }
124903                     if (node.kind === 11 /* JsxText */) {
124904                         // Intentation rules for jsx text are handled by `indentMultilineCommentOrJsxText` inside `processChildNode`; just fastforward past it here
124905                         formattingScanner.advance();
124906                         continue;
124907                     }
124908                     consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node);
124909                 }
124910                 if (!node.parent && formattingScanner.isOnEOF()) {
124911                     var token = formattingScanner.readEOFTokenRange();
124912                     if (token.end <= node.end && previousRange) {
124913                         processPair(token, sourceFile.getLineAndCharacterOfPosition(token.pos).line, node, previousRange, previousRangeStartLine, previousParent, contextNode, nodeDynamicIndentation);
124914                     }
124915                 }
124916                 function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) {
124917                     var childStartPos = child.getStart(sourceFile);
124918                     var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
124919                     var undecoratedChildStartLine = childStartLine;
124920                     if (child.decorators) {
124921                         undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line;
124922                     }
124923                     // if child is a list item - try to get its indentation, only if parent is within the original range.
124924                     var childIndentationAmount = -1 /* Unknown */;
124925                     if (isListItem && ts.rangeContainsRange(originalRange, parent)) {
124926                         childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation);
124927                         if (childIndentationAmount !== -1 /* Unknown */) {
124928                             inheritedIndentation = childIndentationAmount;
124929                         }
124930                     }
124931                     // child node is outside the target range - do not dive inside
124932                     if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) {
124933                         if (child.end < originalRange.pos) {
124934                             formattingScanner.skipToEndOf(child);
124935                         }
124936                         return inheritedIndentation;
124937                     }
124938                     if (child.getFullWidth() === 0) {
124939                         return inheritedIndentation;
124940                     }
124941                     while (formattingScanner.isOnToken()) {
124942                         // proceed any parent tokens that are located prior to child.getStart()
124943                         var tokenInfo = formattingScanner.readTokenInfo(node);
124944                         if (tokenInfo.token.end > childStartPos) {
124945                             // stop when formatting scanner advances past the beginning of the child
124946                             break;
124947                         }
124948                         consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node);
124949                     }
124950                     if (!formattingScanner.isOnToken()) {
124951                         return inheritedIndentation;
124952                     }
124953                     // JSX text shouldn't affect indenting
124954                     if (ts.isToken(child) && child.kind !== 11 /* JsxText */) {
124955                         // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
124956                         var tokenInfo = formattingScanner.readTokenInfo(child);
124957                         ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end");
124958                         consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
124959                         return inheritedIndentation;
124960                     }
124961                     var effectiveParentStartLine = child.kind === 157 /* Decorator */ ? childStartLine : undecoratedParentStartLine;
124962                     var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
124963                     processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
124964                     if (child.kind === 11 /* JsxText */) {
124965                         var range = { pos: child.getStart(), end: child.getEnd() };
124966                         if (range.pos !== range.end) { // don't indent zero-width jsx text
124967                             var siblings = parent.getChildren(sourceFile);
124968                             var currentIndex = ts.findIndex(siblings, function (arg) { return arg.pos === child.pos; });
124969                             var previousNode = siblings[currentIndex - 1];
124970                             if (previousNode) {
124971                                 // The jsx text needs no indentation whatsoever if it ends on the same line the previous sibling ends on
124972                                 if (sourceFile.getLineAndCharacterOfPosition(range.end).line !== sourceFile.getLineAndCharacterOfPosition(previousNode.end).line) {
124973                                     // The first line is (already) "indented" if the text starts on the same line as the previous sibling element ends on
124974                                     var firstLineIsIndented = sourceFile.getLineAndCharacterOfPosition(range.pos).line === sourceFile.getLineAndCharacterOfPosition(previousNode.end).line;
124975                                     indentMultilineCommentOrJsxText(range, childIndentation.indentation, firstLineIsIndented, /*indentFinalLine*/ false, /*jsxStyle*/ true);
124976                                 }
124977                             }
124978                         }
124979                     }
124980                     childContextNode = node;
124981                     if (isFirstListItem && parent.kind === 192 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
124982                         inheritedIndentation = childIndentation.indentation;
124983                     }
124984                     return inheritedIndentation;
124985                 }
124986                 function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) {
124987                     ts.Debug.assert(ts.isNodeArray(nodes));
124988                     var listStartToken = getOpenTokenForList(parent, nodes);
124989                     var listDynamicIndentation = parentDynamicIndentation;
124990                     var startLine = parentStartLine;
124991                     if (listStartToken !== 0 /* Unknown */) {
124992                         // introduce a new indentation scope for lists (including list start and end tokens)
124993                         while (formattingScanner.isOnToken()) {
124994                             var tokenInfo = formattingScanner.readTokenInfo(parent);
124995                             if (tokenInfo.token.end > nodes.pos) {
124996                                 // stop when formatting scanner moves past the beginning of node list
124997                                 break;
124998                             }
124999                             else if (tokenInfo.token.kind === listStartToken) {
125000                                 // consume list start token
125001                                 startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
125002                                 consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
125003                                 var indentationOnListStartToken = void 0;
125004                                 if (indentationOnLastIndentedLine !== -1 /* Unknown */) {
125005                                     // scanner just processed list start token so consider last indentation as list indentation
125006                                     // function foo(): { // last indentation was 0, list item will be indented based on this value
125007                                     //   foo: number;
125008                                     // }: {};
125009                                     indentationOnListStartToken = indentationOnLastIndentedLine;
125010                                 }
125011                                 else {
125012                                     var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile);
125013                                     indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options);
125014                                 }
125015                                 listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217
125016                             }
125017                             else {
125018                                 // consume any tokens that precede the list as child elements of 'node' using its indentation scope
125019                                 consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
125020                             }
125021                         }
125022                     }
125023                     var inheritedIndentation = -1 /* Unknown */;
125024                     for (var i = 0; i < nodes.length; i++) {
125025                         var child = nodes[i];
125026                         inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0);
125027                     }
125028                     var listEndToken = getCloseTokenForOpenToken(listStartToken);
125029                     if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) {
125030                         var tokenInfo = formattingScanner.readTokenInfo(parent);
125031                         if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) {
125032                             var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
125033                             if (startLine !== commaTokenLine) {
125034                                 formattingScanner.advance();
125035                                 tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined;
125036                             }
125037                         }
125038                         // consume the list end token only if it is still belong to the parent
125039                         // there might be the case when current token matches end token but does not considered as one
125040                         // function (x: function) <--
125041                         // without this check close paren will be interpreted as list end token for function expression which is wrong
125042                         if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) {
125043                             // consume list end token
125044                             consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true);
125045                         }
125046                     }
125047                 }
125048                 function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) {
125049                     ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token));
125050                     var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
125051                     var indentToken = false;
125052                     if (currentTokenInfo.leadingTrivia) {
125053                         processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation);
125054                     }
125055                     var lineAction = 0 /* None */;
125056                     var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token);
125057                     var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
125058                     if (isTokenInRange) {
125059                         var rangeHasError = rangeContainsError(currentTokenInfo.token);
125060                         // save previousRange since processRange will overwrite this value with current one
125061                         var savePreviousRange = previousRange;
125062                         lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation);
125063                         // do not indent comments\token if token range overlaps with some error
125064                         if (!rangeHasError) {
125065                             if (lineAction === 0 /* None */) {
125066                                 // indent token only if end line of previous range does not match start line of the token
125067                                 var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line;
125068                                 indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine;
125069                             }
125070                             else {
125071                                 indentToken = lineAction === 1 /* LineAdded */;
125072                             }
125073                         }
125074                     }
125075                     if (currentTokenInfo.trailingTrivia) {
125076                         processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation);
125077                     }
125078                     if (indentToken) {
125079                         var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
125080                             dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) :
125081                             -1 /* Unknown */;
125082                         var indentNextTokenOrTrivia = true;
125083                         if (currentTokenInfo.leadingTrivia) {
125084                             var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
125085                             indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); });
125086                         }
125087                         // indent token only if is it is in target range and does not overlap with any error ranges
125088                         if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) {
125089                             insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */);
125090                             lastIndentedLine = tokenStart.line;
125091                             indentationOnLastIndentedLine = tokenIndentation;
125092                         }
125093                     }
125094                     formattingScanner.advance();
125095                     childContextNode = parent;
125096                 }
125097             }
125098             function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) {
125099                 for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) {
125100                     var triviaItem = trivia_1[_i];
125101                     var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem);
125102                     switch (triviaItem.kind) {
125103                         case 3 /* MultiLineCommentTrivia */:
125104                             if (triviaInRange) {
125105                                 indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
125106                             }
125107                             indentNextTokenOrTrivia = false;
125108                             break;
125109                         case 2 /* SingleLineCommentTrivia */:
125110                             if (indentNextTokenOrTrivia && triviaInRange) {
125111                                 indentSingleLine(triviaItem);
125112                             }
125113                             indentNextTokenOrTrivia = false;
125114                             break;
125115                         case 4 /* NewLineTrivia */:
125116                             indentNextTokenOrTrivia = true;
125117                             break;
125118                     }
125119                 }
125120                 return indentNextTokenOrTrivia;
125121             }
125122             function processTrivia(trivia, parent, contextNode, dynamicIndentation) {
125123                 for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) {
125124                     var triviaItem = trivia_2[_i];
125125                     if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) {
125126                         var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
125127                         processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation);
125128                     }
125129                 }
125130             }
125131             function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) {
125132                 var rangeHasError = rangeContainsError(range);
125133                 var lineAction = 0 /* None */;
125134                 if (!rangeHasError) {
125135                     if (!previousRange) {
125136                         // trim whitespaces starting from the beginning of the span up to the current line
125137                         var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
125138                         trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
125139                     }
125140                     else {
125141                         lineAction =
125142                             processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation);
125143                     }
125144                 }
125145                 previousRange = range;
125146                 previousParent = parent;
125147                 previousRangeStartLine = rangeStart.line;
125148                 return lineAction;
125149             }
125150             function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) {
125151                 formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode);
125152                 var rules = getRules(formattingContext);
125153                 var trimTrailingWhitespaces = formattingContext.options.trimTrailingWhitespace !== false;
125154                 var lineAction = 0 /* None */;
125155                 if (rules) {
125156                     // Apply rules in reverse order so that higher priority rules (which are first in the array)
125157                     // win in a conflict with lower priority rules.
125158                     ts.forEachRight(rules, function (rule) {
125159                         lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine);
125160                         switch (lineAction) {
125161                             case 2 /* LineRemoved */:
125162                                 // Handle the case where the next line is moved to be the end of this line.
125163                                 // In this case we don't indent the next line in the next pass.
125164                                 if (currentParent.getStart(sourceFile) === currentItem.pos) {
125165                                     dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false, contextNode);
125166                                 }
125167                                 break;
125168                             case 1 /* LineAdded */:
125169                                 // Handle the case where token2 is moved to the new line.
125170                                 // In this case we indent token2 in the next pass but we set
125171                                 // sameLineIndent flag to notify the indenter that the indentation is within the line.
125172                                 if (currentParent.getStart(sourceFile) === currentItem.pos) {
125173                                     dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true, contextNode);
125174                                 }
125175                                 break;
125176                             default:
125177                                 ts.Debug.assert(lineAction === 0 /* None */);
125178                         }
125179                         // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
125180                         trimTrailingWhitespaces = trimTrailingWhitespaces && !(rule.action & 16 /* DeleteSpace */) && rule.flags !== 1 /* CanDeleteNewLines */;
125181                     });
125182                 }
125183                 else {
125184                     trimTrailingWhitespaces = trimTrailingWhitespaces && currentItem.kind !== 1 /* EndOfFileToken */;
125185                 }
125186                 if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) {
125187                     // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
125188                     trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem);
125189                 }
125190                 return lineAction;
125191             }
125192             function insertIndentation(pos, indentation, lineAdded) {
125193                 var indentationString = getIndentationString(indentation, options);
125194                 if (lineAdded) {
125195                     // new line is added before the token by the formatting rules
125196                     // insert indentation string at the very beginning of the token
125197                     recordReplace(pos, 0, indentationString);
125198                 }
125199                 else {
125200                     var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
125201                     var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile);
125202                     if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) {
125203                         recordReplace(startLinePosition, tokenStart.character, indentationString);
125204                     }
125205                 }
125206             }
125207             function characterToColumn(startLinePosition, characterInLine) {
125208                 var column = 0;
125209                 for (var i = 0; i < characterInLine; i++) {
125210                     if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) {
125211                         column += options.tabSize - column % options.tabSize;
125212                     }
125213                     else {
125214                         column++;
125215                     }
125216                 }
125217                 return column;
125218             }
125219             function indentationIsDifferent(indentationString, startLinePosition) {
125220                 return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length);
125221             }
125222             function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine, jsxTextStyleIndent) {
125223                 if (indentFinalLine === void 0) { indentFinalLine = true; }
125224                 // split comment in lines
125225                 var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line;
125226                 var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line;
125227                 if (startLine === endLine) {
125228                     if (!firstLineIsIndented) {
125229                         // treat as single line comment
125230                         insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false);
125231                     }
125232                     return;
125233                 }
125234                 var parts = [];
125235                 var startPos = commentRange.pos;
125236                 for (var line = startLine; line < endLine; line++) {
125237                     var endOfLine = ts.getEndLinePosition(line, sourceFile);
125238                     parts.push({ pos: startPos, end: endOfLine });
125239                     startPos = ts.getStartPositionOfLine(line + 1, sourceFile);
125240                 }
125241                 if (indentFinalLine) {
125242                     parts.push({ pos: startPos, end: commentRange.end });
125243                 }
125244                 if (parts.length === 0)
125245                     return;
125246                 var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile);
125247                 var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options);
125248                 if (indentation === nonWhitespaceColumnInFirstPart.column && !jsxTextStyleIndent) {
125249                     return;
125250                 }
125251                 var startIndex = 0;
125252                 if (firstLineIsIndented) {
125253                     startIndex = 1;
125254                     startLine++;
125255                 }
125256                 // shift all parts on the delta size
125257                 var delta = indentation - nonWhitespaceColumnInFirstPart.column;
125258                 for (var i = startIndex; i < parts.length; i++, startLine++) {
125259                     var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile);
125260                     var nonWhitespaceCharacterAndColumn = i === 0
125261                         ? nonWhitespaceColumnInFirstPart
125262                         : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options);
125263                     if (jsxTextStyleIndent) {
125264                         // skip adding indentation to blank lines
125265                         if (ts.isLineBreak(sourceFile.text.charCodeAt(ts.getStartPositionOfLine(startLine, sourceFile))))
125266                             continue;
125267                         // reset delta on every line
125268                         delta = indentation - nonWhitespaceCharacterAndColumn.column;
125269                     }
125270                     var newIndentation = nonWhitespaceCharacterAndColumn.column + delta;
125271                     if (newIndentation > 0) {
125272                         var indentationString = getIndentationString(newIndentation, options);
125273                         recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString);
125274                     }
125275                     else {
125276                         recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character);
125277                     }
125278                 }
125279             }
125280             function trimTrailingWhitespacesForLines(line1, line2, range) {
125281                 for (var line = line1; line < line2; line++) {
125282                     var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile);
125283                     var lineEndPosition = ts.getEndLinePosition(line, sourceFile);
125284                     // do not trim whitespaces in comments or template expression
125285                     if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
125286                         continue;
125287                     }
125288                     var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
125289                     if (whitespaceStart !== -1) {
125290                         ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1)));
125291                         recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart);
125292                     }
125293                 }
125294             }
125295             /**
125296              * @param start The position of the first character in range
125297              * @param end The position of the last character in range
125298              */
125299             function getTrailingWhitespaceStartPosition(start, end) {
125300                 var pos = end;
125301                 while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) {
125302                     pos--;
125303                 }
125304                 if (pos !== end) {
125305                     return pos + 1;
125306                 }
125307                 return -1;
125308             }
125309             /**
125310              * Trimming will be done for lines after the previous range
125311              */
125312             function trimTrailingWhitespacesForRemainingRange() {
125313                 var startPosition = previousRange ? previousRange.end : originalRange.pos;
125314                 var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line;
125315                 var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line;
125316                 trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange);
125317             }
125318             function recordDelete(start, len) {
125319                 if (len) {
125320                     edits.push(ts.createTextChangeFromStartLength(start, len, ""));
125321                 }
125322             }
125323             function recordReplace(start, len, newText) {
125324                 if (len || newText) {
125325                     edits.push(ts.createTextChangeFromStartLength(start, len, newText));
125326                 }
125327             }
125328             function recordInsert(start, text) {
125329                 if (text) {
125330                     edits.push(ts.createTextChangeFromStartLength(start, 0, text));
125331                 }
125332             }
125333             function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) {
125334                 var onLaterLine = currentStartLine !== previousStartLine;
125335                 switch (rule.action) {
125336                     case 1 /* StopProcessingSpaceActions */:
125337                         // no action required
125338                         return 0 /* None */;
125339                     case 16 /* DeleteSpace */:
125340                         if (previousRange.end !== currentRange.pos) {
125341                             // delete characters starting from t1.end up to t2.pos exclusive
125342                             recordDelete(previousRange.end, currentRange.pos - previousRange.end);
125343                             return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
125344                         }
125345                         break;
125346                     case 32 /* DeleteToken */:
125347                         recordDelete(previousRange.pos, previousRange.end - previousRange.pos);
125348                         break;
125349                     case 8 /* InsertNewLine */:
125350                         // exit early if we on different lines and rule cannot change number of newlines
125351                         // if line1 and line2 are on subsequent lines then no edits are required - ok to exit
125352                         // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines
125353                         if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
125354                             return 0 /* None */;
125355                         }
125356                         // edit should not be applied if we have one line feed between elements
125357                         var lineDelta = currentStartLine - previousStartLine;
125358                         if (lineDelta !== 1) {
125359                             recordReplace(previousRange.end, currentRange.pos - previousRange.end, ts.getNewLineOrDefaultFromHost(host, options));
125360                             return onLaterLine ? 0 /* None */ : 1 /* LineAdded */;
125361                         }
125362                         break;
125363                     case 4 /* InsertSpace */:
125364                         // exit early if we on different lines and rule cannot change number of newlines
125365                         if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
125366                             return 0 /* None */;
125367                         }
125368                         var posDelta = currentRange.pos - previousRange.end;
125369                         if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) {
125370                             recordReplace(previousRange.end, currentRange.pos - previousRange.end, " ");
125371                             return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
125372                         }
125373                         break;
125374                     case 64 /* InsertTrailingSemicolon */:
125375                         recordInsert(previousRange.end, ";");
125376                 }
125377                 return 0 /* None */;
125378             }
125379         }
125380         var LineAction;
125381         (function (LineAction) {
125382             LineAction[LineAction["None"] = 0] = "None";
125383             LineAction[LineAction["LineAdded"] = 1] = "LineAdded";
125384             LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved";
125385         })(LineAction || (LineAction = {}));
125386         /**
125387          * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`.
125388          */
125389         function getRangeOfEnclosingComment(sourceFile, position, precedingToken, tokenAtPosition) {
125390             if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); }
125391             var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc);
125392             if (jsdoc)
125393                 tokenAtPosition = jsdoc.parent;
125394             var tokenStart = tokenAtPosition.getStart(sourceFile);
125395             if (tokenStart <= position && position < tokenAtPosition.getEnd()) {
125396                 return undefined;
125397             }
125398             // eslint-disable-next-line no-null/no-null
125399             precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken;
125400             // Between two consecutive tokens, all comments are either trailing on the former
125401             // or leading on the latter (and none are in both lists).
125402             var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end);
125403             var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile);
125404             var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken);
125405             return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) ||
125406                 // The end marker of a single-line comment does not include the newline character.
125407                 // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position):
125408                 //
125409                 //    // asdf   ^\n
125410                 //
125411                 // But for closed multi-line comments, we don't want to be inside the comment in the following case:
125412                 //
125413                 //    /* asdf */^
125414                 //
125415                 // However, unterminated multi-line comments *do* contain their end.
125416                 //
125417                 // Internally, we represent the end of the comment at the newline and closing '/', respectively.
125418                 //
125419                 position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); });
125420         }
125421         formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment;
125422         function getOpenTokenForList(node, list) {
125423             switch (node.kind) {
125424                 case 162 /* Constructor */:
125425                 case 244 /* FunctionDeclaration */:
125426                 case 201 /* FunctionExpression */:
125427                 case 161 /* MethodDeclaration */:
125428                 case 160 /* MethodSignature */:
125429                 case 202 /* ArrowFunction */:
125430                     if (node.typeParameters === list) {
125431                         return 29 /* LessThanToken */;
125432                     }
125433                     else if (node.parameters === list) {
125434                         return 20 /* OpenParenToken */;
125435                     }
125436                     break;
125437                 case 196 /* CallExpression */:
125438                 case 197 /* NewExpression */:
125439                     if (node.typeArguments === list) {
125440                         return 29 /* LessThanToken */;
125441                     }
125442                     else if (node.arguments === list) {
125443                         return 20 /* OpenParenToken */;
125444                     }
125445                     break;
125446                 case 169 /* TypeReference */:
125447                     if (node.typeArguments === list) {
125448                         return 29 /* LessThanToken */;
125449                     }
125450                     break;
125451                 case 173 /* TypeLiteral */:
125452                     return 18 /* OpenBraceToken */;
125453             }
125454             return 0 /* Unknown */;
125455         }
125456         function getCloseTokenForOpenToken(kind) {
125457             switch (kind) {
125458                 case 20 /* OpenParenToken */:
125459                     return 21 /* CloseParenToken */;
125460                 case 29 /* LessThanToken */:
125461                     return 31 /* GreaterThanToken */;
125462                 case 18 /* OpenBraceToken */:
125463                     return 19 /* CloseBraceToken */;
125464             }
125465             return 0 /* Unknown */;
125466         }
125467         var internedSizes;
125468         var internedTabsIndentation;
125469         var internedSpacesIndentation;
125470         function getIndentationString(indentation, options) {
125471             // reset interned strings if FormatCodeOptions were changed
125472             var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
125473             if (resetInternedStrings) {
125474                 internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
125475                 internedTabsIndentation = internedSpacesIndentation = undefined;
125476             }
125477             if (!options.convertTabsToSpaces) {
125478                 var tabs = Math.floor(indentation / options.tabSize);
125479                 var spaces = indentation - tabs * options.tabSize;
125480                 var tabString = void 0;
125481                 if (!internedTabsIndentation) {
125482                     internedTabsIndentation = [];
125483                 }
125484                 if (internedTabsIndentation[tabs] === undefined) {
125485                     internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs);
125486                 }
125487                 else {
125488                     tabString = internedTabsIndentation[tabs];
125489                 }
125490                 return spaces ? tabString + ts.repeatString(" ", spaces) : tabString;
125491             }
125492             else {
125493                 var spacesString = void 0;
125494                 var quotient = Math.floor(indentation / options.indentSize);
125495                 var remainder = indentation % options.indentSize;
125496                 if (!internedSpacesIndentation) {
125497                     internedSpacesIndentation = [];
125498                 }
125499                 if (internedSpacesIndentation[quotient] === undefined) {
125500                     spacesString = ts.repeatString(" ", options.indentSize * quotient);
125501                     internedSpacesIndentation[quotient] = spacesString;
125502                 }
125503                 else {
125504                     spacesString = internedSpacesIndentation[quotient];
125505                 }
125506                 return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString;
125507             }
125508         }
125509         formatting.getIndentationString = getIndentationString;
125510     })(formatting = ts.formatting || (ts.formatting = {}));
125511 })(ts || (ts = {}));
125512 /* @internal */
125513 var ts;
125514 (function (ts) {
125515     var formatting;
125516     (function (formatting) {
125517         var SmartIndenter;
125518         (function (SmartIndenter) {
125519             var Value;
125520             (function (Value) {
125521                 Value[Value["Unknown"] = -1] = "Unknown";
125522             })(Value || (Value = {}));
125523             /**
125524              * @param assumeNewLineBeforeCloseBrace
125525              * `false` when called on text from a real source file.
125526              * `true` when we need to assume `position` is on a newline.
125527              *
125528              * This is useful for codefixes. Consider
125529              * ```
125530              * function f() {
125531              * |}
125532              * ```
125533              * with `position` at `|`.
125534              *
125535              * When inserting some text after an open brace, we would like to get indentation as if a newline was already there.
125536              * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior.
125537              */
125538             function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) {
125539                 if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; }
125540                 if (position > sourceFile.text.length) {
125541                     return getBaseIndentation(options); // past EOF
125542                 }
125543                 // no indentation when the indent style is set to none,
125544                 // so we can return fast
125545                 if (options.indentStyle === ts.IndentStyle.None) {
125546                     return 0;
125547                 }
125548                 var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true);
125549                 // eslint-disable-next-line no-null/no-null
125550                 var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null);
125551                 if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) {
125552                     return getCommentIndent(sourceFile, position, options, enclosingCommentRange);
125553                 }
125554                 if (!precedingToken) {
125555                     return getBaseIndentation(options);
125556                 }
125557                 // no indentation in string \regex\template literals
125558                 var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
125559                 if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) {
125560                     return 0;
125561                 }
125562                 var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
125563                 // indentation is first non-whitespace character in a previous line
125564                 // for block indentation, we should look for a line which contains something that's not
125565                 // whitespace.
125566                 if (options.indentStyle === ts.IndentStyle.Block) {
125567                     return getBlockIndent(sourceFile, position, options);
125568                 }
125569                 if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 209 /* BinaryExpression */) {
125570                     // previous token is comma that separates items in list - find the previous item and try to derive indentation from it
125571                     var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
125572                     if (actualIndentation !== -1 /* Unknown */) {
125573                         return actualIndentation;
125574                     }
125575                 }
125576                 var containerList = getListByPosition(position, precedingToken.parent, sourceFile);
125577                 // use list position if the preceding token is before any list items
125578                 if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) {
125579                     return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217
125580                 }
125581                 return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options);
125582             }
125583             SmartIndenter.getIndentation = getIndentation;
125584             function getCommentIndent(sourceFile, position, options, enclosingCommentRange) {
125585                 var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1;
125586                 var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line;
125587                 ts.Debug.assert(commentStartLine >= 0);
125588                 if (previousLine <= commentStartLine) {
125589                     return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options);
125590                 }
125591                 var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile);
125592                 var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character;
125593                 if (column === 0) {
125594                     return column;
125595                 }
125596                 var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character);
125597                 return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column;
125598             }
125599             function getBlockIndent(sourceFile, position, options) {
125600                 // move backwards until we find a line with a non-whitespace character,
125601                 // then find the first non-whitespace character for that line.
125602                 var current = position;
125603                 while (current > 0) {
125604                     var char = sourceFile.text.charCodeAt(current);
125605                     if (!ts.isWhiteSpaceLike(char)) {
125606                         break;
125607                     }
125608                     current--;
125609                 }
125610                 var lineStart = ts.getLineStartPositionForPosition(current, sourceFile);
125611                 return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options);
125612             }
125613             function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) {
125614                 // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken'
125615                 // if such node is found - compute initial indentation for 'position' inside this node
125616                 var previous;
125617                 var current = precedingToken;
125618                 while (current) {
125619                     if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) {
125620                         var currentStart = getStartLineAndCharacterForNode(current, sourceFile);
125621                         var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile);
125622                         var indentationDelta = nextTokenKind !== 0 /* Unknown */
125623                             // handle cases when codefix is about to be inserted before the close brace
125624                             ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0
125625                             : lineAtPosition !== currentStart.line ? options.indentSize : 0;
125626                         return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217
125627                     }
125628                     // check if current node is a list item - if yes, take indentation from it
125629                     // do not consider parent-child line sharing yet:
125630                     // function foo(a
125631                     //    | preceding node 'a' does share line with its parent but indentation is expected
125632                     var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true);
125633                     if (actualIndentation !== -1 /* Unknown */) {
125634                         return actualIndentation;
125635                     }
125636                     previous = current;
125637                     current = current.parent;
125638                 }
125639                 // no parent was found - return the base indentation of the SourceFile
125640                 return getBaseIndentation(options);
125641             }
125642             function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
125643                 var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
125644                 return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options);
125645             }
125646             SmartIndenter.getIndentationForNode = getIndentationForNode;
125647             function getBaseIndentation(options) {
125648                 return options.baseIndentSize || 0;
125649             }
125650             SmartIndenter.getBaseIndentation = getBaseIndentation;
125651             function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) {
125652                 var parent = current.parent;
125653                 // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if
125654                 // * parent and child nodes start on the same line, or
125655                 // * parent is an IfStatement and child starts on the same line as an 'else clause'.
125656                 while (parent) {
125657                     var useActualIndentation = true;
125658                     if (ignoreActualIndentationRange) {
125659                         var start = current.getStart(sourceFile);
125660                         useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end;
125661                     }
125662                     var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile);
125663                     var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line ||
125664                         childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile);
125665                     if (useActualIndentation) {
125666                         // check if current node is a list item - if yes, take indentation from it
125667                         var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine);
125668                         if (actualIndentation !== -1 /* Unknown */) {
125669                             return actualIndentation + indentationDelta;
125670                         }
125671                         // try to fetch actual indentation for current node from source text
125672                         actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options);
125673                         if (actualIndentation !== -1 /* Unknown */) {
125674                             return actualIndentation + indentationDelta;
125675                         }
125676                     }
125677                     // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
125678                     if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) {
125679                         indentationDelta += options.indentSize;
125680                     }
125681                     // In our AST, a call argument's `parent` is the call-expression, not the argument list.
125682                     // We would like to increase indentation based on the relationship between an argument and its argument-list,
125683                     // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list.
125684                     // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression
125685                     // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation.
125686                     //
125687                     // Instead, when at an argument, we unspoof the starting position of the enclosing call expression
125688                     // *after* applying indentation for the argument.
125689                     var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile);
125690                     current = parent;
125691                     parent = current.parent;
125692                     currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart;
125693                 }
125694                 return indentationDelta + getBaseIndentation(options);
125695             }
125696             function getContainingListOrParentStart(parent, child, sourceFile) {
125697                 var containingList = getContainingList(child, sourceFile);
125698                 var startPos = containingList ? containingList.pos : parent.getStart(sourceFile);
125699                 return sourceFile.getLineAndCharacterOfPosition(startPos);
125700             }
125701             /*
125702              * Function returns Value.Unknown if indentation cannot be determined
125703              */
125704             function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) {
125705                 // previous token is comma that separates items in list - find the previous item and try to derive indentation from it
125706                 var commaItemInfo = ts.findListItemInfo(commaToken);
125707                 if (commaItemInfo && commaItemInfo.listItemIndex > 0) {
125708                     return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options);
125709                 }
125710                 else {
125711                     // handle broken code gracefully
125712                     return -1 /* Unknown */;
125713                 }
125714             }
125715             /*
125716              * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression)
125717              */
125718             function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) {
125719                 // actual indentation is used for statements\declarations if one of cases below is true:
125720                 // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
125721                 // - parent and child are not on the same line
125722                 var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
125723                     (parent.kind === 290 /* SourceFile */ || !parentAndChildShareLine);
125724                 if (!useActualIndentation) {
125725                     return -1 /* Unknown */;
125726                 }
125727                 return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options);
125728             }
125729             var NextTokenKind;
125730             (function (NextTokenKind) {
125731                 NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown";
125732                 NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace";
125733                 NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
125734             })(NextTokenKind || (NextTokenKind = {}));
125735             function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
125736                 var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
125737                 if (!nextToken) {
125738                     return 0 /* Unknown */;
125739                 }
125740                 if (nextToken.kind === 18 /* OpenBraceToken */) {
125741                     // open braces are always indented at the parent level
125742                     return 1 /* OpenBrace */;
125743                 }
125744                 else if (nextToken.kind === 19 /* CloseBraceToken */) {
125745                     // close braces are indented at the parent level if they are located on the same line with cursor
125746                     // this means that if new line will be added at $ position, this case will be indented
125747                     // class A {
125748                     //    $
125749                     // }
125750                     /// and this one - not
125751                     // class A {
125752                     // $}
125753                     var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
125754                     return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */;
125755                 }
125756                 return 0 /* Unknown */;
125757             }
125758             function getStartLineAndCharacterForNode(n, sourceFile) {
125759                 return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
125760             }
125761             function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) {
125762                 if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) {
125763                     return false;
125764                 }
125765                 var expressionOfCallExpressionEnd = parent.expression.getEnd();
125766                 var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line;
125767                 return expressionOfCallExpressionEndLine === childStartLine;
125768             }
125769             SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled;
125770             function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) {
125771                 if (parent.kind === 227 /* IfStatement */ && parent.elseStatement === child) {
125772                     var elseKeyword = ts.findChildOfKind(parent, 87 /* ElseKeyword */, sourceFile);
125773                     ts.Debug.assert(elseKeyword !== undefined);
125774                     var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
125775                     return elseKeywordStartLine === childStartLine;
125776                 }
125777                 return false;
125778             }
125779             SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement;
125780             function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) {
125781                 if (ts.isCallOrNewExpression(parent)) {
125782                     if (!parent.arguments)
125783                         return false;
125784                     var currentNode = ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; });
125785                     // If it's not one of the arguments, don't look past this
125786                     if (!currentNode)
125787                         return false;
125788                     var currentIndex = parent.arguments.indexOf(currentNode);
125789                     if (currentIndex === 0)
125790                         return false; // Can't look at previous node if first
125791                     var previousNode = parent.arguments[currentIndex - 1];
125792                     var lineOfPreviousNode = ts.getLineAndCharacterOfPosition(sourceFile, previousNode.getEnd()).line;
125793                     if (childStartLine === lineOfPreviousNode) {
125794                         return true;
125795                     }
125796                 }
125797                 return false;
125798             }
125799             SmartIndenter.argumentStartsOnSameLineAsPreviousArgument = argumentStartsOnSameLineAsPreviousArgument;
125800             function getContainingList(node, sourceFile) {
125801                 return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile);
125802             }
125803             SmartIndenter.getContainingList = getContainingList;
125804             function getListByPosition(pos, node, sourceFile) {
125805                 return node && getListByRange(pos, pos, node, sourceFile);
125806             }
125807             function getListByRange(start, end, node, sourceFile) {
125808                 switch (node.kind) {
125809                     case 169 /* TypeReference */:
125810                         return getList(node.typeArguments);
125811                     case 193 /* ObjectLiteralExpression */:
125812                         return getList(node.properties);
125813                     case 192 /* ArrayLiteralExpression */:
125814                         return getList(node.elements);
125815                     case 173 /* TypeLiteral */:
125816                         return getList(node.members);
125817                     case 244 /* FunctionDeclaration */:
125818                     case 201 /* FunctionExpression */:
125819                     case 202 /* ArrowFunction */:
125820                     case 161 /* MethodDeclaration */:
125821                     case 160 /* MethodSignature */:
125822                     case 165 /* CallSignature */:
125823                     case 162 /* Constructor */:
125824                     case 171 /* ConstructorType */:
125825                     case 166 /* ConstructSignature */:
125826                         return getList(node.typeParameters) || getList(node.parameters);
125827                     case 245 /* ClassDeclaration */:
125828                     case 214 /* ClassExpression */:
125829                     case 246 /* InterfaceDeclaration */:
125830                     case 247 /* TypeAliasDeclaration */:
125831                     case 321 /* JSDocTemplateTag */:
125832                         return getList(node.typeParameters);
125833                     case 197 /* NewExpression */:
125834                     case 196 /* CallExpression */:
125835                         return getList(node.typeArguments) || getList(node.arguments);
125836                     case 243 /* VariableDeclarationList */:
125837                         return getList(node.declarations);
125838                     case 257 /* NamedImports */:
125839                     case 261 /* NamedExports */:
125840                         return getList(node.elements);
125841                     case 189 /* ObjectBindingPattern */:
125842                     case 190 /* ArrayBindingPattern */:
125843                         return getList(node.elements);
125844                 }
125845                 function getList(list) {
125846                     return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined;
125847                 }
125848             }
125849             function getVisualListRange(node, list, sourceFile) {
125850                 var children = node.getChildren(sourceFile);
125851                 for (var i = 1; i < children.length - 1; i++) {
125852                     if (children[i].pos === list.pos && children[i].end === list.end) {
125853                         return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) };
125854                     }
125855                 }
125856                 return list;
125857             }
125858             function getActualIndentationForListStartLine(list, sourceFile, options) {
125859                 if (!list) {
125860                     return -1 /* Unknown */;
125861                 }
125862                 return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options);
125863             }
125864             function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) {
125865                 if (node.parent && node.parent.kind === 243 /* VariableDeclarationList */) {
125866                     // VariableDeclarationList has no wrapping tokens
125867                     return -1 /* Unknown */;
125868                 }
125869                 var containingList = getContainingList(node, sourceFile);
125870                 if (containingList) {
125871                     var index = containingList.indexOf(node);
125872                     if (index !== -1) {
125873                         var result = deriveActualIndentationFromList(containingList, index, sourceFile, options);
125874                         if (result !== -1 /* Unknown */) {
125875                             return result;
125876                         }
125877                     }
125878                     return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217
125879                 }
125880                 return -1 /* Unknown */;
125881             }
125882             function deriveActualIndentationFromList(list, index, sourceFile, options) {
125883                 ts.Debug.assert(index >= 0 && index < list.length);
125884                 var node = list[index];
125885                 // walk toward the start of the list starting from current node and check if the line is the same for all items.
125886                 // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i]
125887                 var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile);
125888                 for (var i = index - 1; i >= 0; i--) {
125889                     if (list[i].kind === 27 /* CommaToken */) {
125890                         continue;
125891                     }
125892                     // skip list items that ends on the same line with the current list element
125893                     var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line;
125894                     if (prevEndLine !== lineAndCharacter.line) {
125895                         return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options);
125896                     }
125897                     lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile);
125898                 }
125899                 return -1 /* Unknown */;
125900             }
125901             function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) {
125902                 var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0);
125903                 return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options);
125904             }
125905             /**
125906              * Character is the actual index of the character since the beginning of the line.
125907              * Column - position of the character after expanding tabs to spaces.
125908              * "0\t2$"
125909              * value of 'character' for '$' is 3
125910              * value of 'column' for '$' is 6 (assuming that tab size is 4)
125911              */
125912             function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) {
125913                 var character = 0;
125914                 var column = 0;
125915                 for (var pos = startPos; pos < endPos; pos++) {
125916                     var ch = sourceFile.text.charCodeAt(pos);
125917                     if (!ts.isWhiteSpaceSingleLine(ch)) {
125918                         break;
125919                     }
125920                     if (ch === 9 /* tab */) {
125921                         column += options.tabSize + (column % options.tabSize);
125922                     }
125923                     else {
125924                         column++;
125925                     }
125926                     character++;
125927                 }
125928                 return { column: column, character: character };
125929             }
125930             SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn;
125931             function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) {
125932                 return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column;
125933             }
125934             SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn;
125935             function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) {
125936                 var childKind = child ? child.kind : 0 /* Unknown */;
125937                 switch (parent.kind) {
125938                     case 226 /* ExpressionStatement */:
125939                     case 245 /* ClassDeclaration */:
125940                     case 214 /* ClassExpression */:
125941                     case 246 /* InterfaceDeclaration */:
125942                     case 248 /* EnumDeclaration */:
125943                     case 247 /* TypeAliasDeclaration */:
125944                     case 192 /* ArrayLiteralExpression */:
125945                     case 223 /* Block */:
125946                     case 250 /* ModuleBlock */:
125947                     case 193 /* ObjectLiteralExpression */:
125948                     case 173 /* TypeLiteral */:
125949                     case 186 /* MappedType */:
125950                     case 175 /* TupleType */:
125951                     case 251 /* CaseBlock */:
125952                     case 278 /* DefaultClause */:
125953                     case 277 /* CaseClause */:
125954                     case 200 /* ParenthesizedExpression */:
125955                     case 194 /* PropertyAccessExpression */:
125956                     case 196 /* CallExpression */:
125957                     case 197 /* NewExpression */:
125958                     case 225 /* VariableStatement */:
125959                     case 259 /* ExportAssignment */:
125960                     case 235 /* ReturnStatement */:
125961                     case 210 /* ConditionalExpression */:
125962                     case 190 /* ArrayBindingPattern */:
125963                     case 189 /* ObjectBindingPattern */:
125964                     case 268 /* JsxOpeningElement */:
125965                     case 271 /* JsxOpeningFragment */:
125966                     case 267 /* JsxSelfClosingElement */:
125967                     case 276 /* JsxExpression */:
125968                     case 160 /* MethodSignature */:
125969                     case 165 /* CallSignature */:
125970                     case 166 /* ConstructSignature */:
125971                     case 156 /* Parameter */:
125972                     case 170 /* FunctionType */:
125973                     case 171 /* ConstructorType */:
125974                     case 182 /* ParenthesizedType */:
125975                     case 198 /* TaggedTemplateExpression */:
125976                     case 206 /* AwaitExpression */:
125977                     case 261 /* NamedExports */:
125978                     case 257 /* NamedImports */:
125979                     case 263 /* ExportSpecifier */:
125980                     case 258 /* ImportSpecifier */:
125981                     case 159 /* PropertyDeclaration */:
125982                         return true;
125983                     case 242 /* VariableDeclaration */:
125984                     case 281 /* PropertyAssignment */:
125985                     case 209 /* BinaryExpression */:
125986                         if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 193 /* ObjectLiteralExpression */) { // TODO: GH#18217
125987                             return rangeIsOnOneLine(sourceFile, child);
125988                         }
125989                         if (parent.kind !== 209 /* BinaryExpression */) {
125990                             return true;
125991                         }
125992                         break;
125993                     case 228 /* DoStatement */:
125994                     case 229 /* WhileStatement */:
125995                     case 231 /* ForInStatement */:
125996                     case 232 /* ForOfStatement */:
125997                     case 230 /* ForStatement */:
125998                     case 227 /* IfStatement */:
125999                     case 244 /* FunctionDeclaration */:
126000                     case 201 /* FunctionExpression */:
126001                     case 161 /* MethodDeclaration */:
126002                     case 202 /* ArrowFunction */:
126003                     case 162 /* Constructor */:
126004                     case 163 /* GetAccessor */:
126005                     case 164 /* SetAccessor */:
126006                         return childKind !== 223 /* Block */;
126007                     case 260 /* ExportDeclaration */:
126008                         return childKind !== 261 /* NamedExports */;
126009                     case 254 /* ImportDeclaration */:
126010                         return childKind !== 255 /* ImportClause */ ||
126011                             (!!child.namedBindings && child.namedBindings.kind !== 257 /* NamedImports */);
126012                     case 266 /* JsxElement */:
126013                         return childKind !== 269 /* JsxClosingElement */;
126014                     case 270 /* JsxFragment */:
126015                         return childKind !== 272 /* JsxClosingFragment */;
126016                     case 179 /* IntersectionType */:
126017                     case 178 /* UnionType */:
126018                         if (childKind === 173 /* TypeLiteral */) {
126019                             return false;
126020                         }
126021                     // falls through
126022                 }
126023                 // No explicit rule for given nodes so the result will follow the default value argument
126024                 return indentByDefault;
126025             }
126026             SmartIndenter.nodeWillIndentChild = nodeWillIndentChild;
126027             function isControlFlowEndingStatement(kind, parent) {
126028                 switch (kind) {
126029                     case 235 /* ReturnStatement */:
126030                     case 239 /* ThrowStatement */:
126031                     case 233 /* ContinueStatement */:
126032                     case 234 /* BreakStatement */:
126033                         return parent.kind !== 223 /* Block */;
126034                     default:
126035                         return false;
126036                 }
126037             }
126038             /**
126039              * True when the parent node should indent the given child by an explicit rule.
126040              * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child.
126041              */
126042             function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) {
126043                 if (isNextChild === void 0) { isNextChild = false; }
126044                 return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)
126045                     && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent));
126046             }
126047             SmartIndenter.shouldIndentChildNode = shouldIndentChildNode;
126048             function rangeIsOnOneLine(sourceFile, range) {
126049                 var rangeStart = ts.skipTrivia(sourceFile.text, range.pos);
126050                 var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line;
126051                 var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
126052                 return startLine === endLine;
126053             }
126054         })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {}));
126055     })(formatting = ts.formatting || (ts.formatting = {}));
126056 })(ts || (ts = {}));
126057 /* @internal */
126058 var ts;
126059 (function (ts) {
126060     var textChanges;
126061     (function (textChanges_3) {
126062         /**
126063          * Currently for simplicity we store recovered positions on the node itself.
126064          * It can be changed to side-table later if we decide that current design is too invasive.
126065          */
126066         function getPos(n) {
126067             var result = n.__pos;
126068             ts.Debug.assert(typeof result === "number");
126069             return result;
126070         }
126071         function setPos(n, pos) {
126072             ts.Debug.assert(typeof pos === "number");
126073             n.__pos = pos;
126074         }
126075         function getEnd(n) {
126076             var result = n.__end;
126077             ts.Debug.assert(typeof result === "number");
126078             return result;
126079         }
126080         function setEnd(n, end) {
126081             ts.Debug.assert(typeof end === "number");
126082             n.__end = end;
126083         }
126084         var LeadingTriviaOption;
126085         (function (LeadingTriviaOption) {
126086             /** Exclude all leading trivia (use getStart()) */
126087             LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
126088             /** Include leading trivia and,
126089              * if there are no line breaks between the node and the previous token,
126090              * include all trivia between the node and the previous token
126091              */
126092             LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
126093             /**
126094              * Include attached JSDoc comments
126095              */
126096             LeadingTriviaOption[LeadingTriviaOption["JSDoc"] = 2] = "JSDoc";
126097             /**
126098              * Only delete trivia on the same line as getStart().
126099              * Used to avoid deleting leading comments
126100              */
126101             LeadingTriviaOption[LeadingTriviaOption["StartLine"] = 3] = "StartLine";
126102         })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
126103         var TrailingTriviaOption;
126104         (function (TrailingTriviaOption) {
126105             /** Exclude all trailing trivia (use getEnd()) */
126106             TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
126107             /** Include trailing trivia */
126108             TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
126109         })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
126110         function skipWhitespacesAndLineBreaks(text, start) {
126111             return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
126112         }
126113         function hasCommentsBeforeLineBreak(text, start) {
126114             var i = start;
126115             while (i < text.length) {
126116                 var ch = text.charCodeAt(i);
126117                 if (ts.isWhiteSpaceSingleLine(ch)) {
126118                     i++;
126119                     continue;
126120                 }
126121                 return ch === 47 /* slash */;
126122             }
126123             return false;
126124         }
126125         var useNonAdjustedPositions = {
126126             leadingTriviaOption: LeadingTriviaOption.Exclude,
126127             trailingTriviaOption: TrailingTriviaOption.Exclude,
126128         };
126129         var ChangeKind;
126130         (function (ChangeKind) {
126131             ChangeKind[ChangeKind["Remove"] = 0] = "Remove";
126132             ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode";
126133             ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes";
126134             ChangeKind[ChangeKind["Text"] = 3] = "Text";
126135         })(ChangeKind || (ChangeKind = {}));
126136         function getAdjustedRange(sourceFile, startNode, endNode, options) {
126137             return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
126138         }
126139         function getAdjustedStartPosition(sourceFile, node, options) {
126140             var leadingTriviaOption = options.leadingTriviaOption;
126141             if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
126142                 return node.getStart(sourceFile);
126143             }
126144             if (leadingTriviaOption === LeadingTriviaOption.StartLine) {
126145                 return ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile);
126146             }
126147             if (leadingTriviaOption === LeadingTriviaOption.JSDoc) {
126148                 var JSDocComments = ts.getJSDocCommentRanges(node, sourceFile.text);
126149                 if (JSDocComments === null || JSDocComments === void 0 ? void 0 : JSDocComments.length) {
126150                     return ts.getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile);
126151                 }
126152             }
126153             var fullStart = node.getFullStart();
126154             var start = node.getStart(sourceFile);
126155             if (fullStart === start) {
126156                 return start;
126157             }
126158             var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile);
126159             var startLine = ts.getLineStartPositionForPosition(start, sourceFile);
126160             if (startLine === fullStartLine) {
126161                 // full start and start of the node are on the same line
126162                 //   a,     b;
126163                 //    ^     ^
126164                 //    |   start
126165                 // fullstart
126166                 // when b is replaced - we usually want to keep the leading trvia
126167                 // when b is deleted - we delete it
126168                 return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
126169             }
126170             // get start position of the line following the line that contains fullstart position
126171             // (but only if the fullstart isn't the very beginning of the file)
126172             var nextLineStart = fullStart > 0 ? 1 : 0;
126173             var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile);
126174             // skip whitespaces/newlines
126175             adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition);
126176             return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
126177         }
126178         function getAdjustedEndPosition(sourceFile, node, options) {
126179             var end = node.end;
126180             var trailingTriviaOption = options.trailingTriviaOption;
126181             if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
126182                 return end;
126183             }
126184             var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
126185             return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
126186                 ? newEnd
126187                 : end;
126188         }
126189         /**
126190          * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element
126191          */
126192         function isSeparator(node, candidate) {
126193             return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 193 /* ObjectLiteralExpression */));
126194         }
126195         function spaces(count) {
126196             var s = "";
126197             for (var i = 0; i < count; i++) {
126198                 s += " ";
126199             }
126200             return s;
126201         }
126202         function isThisTypeAnnotatable(containingFunction) {
126203             return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction);
126204         }
126205         textChanges_3.isThisTypeAnnotatable = isThisTypeAnnotatable;
126206         var ChangeTracker = /** @class */ (function () {
126207             /** Public for tests only. Other callers should use `ChangeTracker.with`. */
126208             function ChangeTracker(newLineCharacter, formatContext) {
126209                 this.newLineCharacter = newLineCharacter;
126210                 this.formatContext = formatContext;
126211                 this.changes = [];
126212                 this.newFiles = [];
126213                 this.classesWithNodesInsertedAtStart = ts.createMap(); // Set<ClassDeclaration> implemented as Map<node id, ClassDeclaration>
126214                 this.deletedNodes = [];
126215             }
126216             ChangeTracker.fromContext = function (context) {
126217                 return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext);
126218             };
126219             ChangeTracker.with = function (context, cb) {
126220                 var tracker = ChangeTracker.fromContext(context);
126221                 cb(tracker);
126222                 return tracker.getChanges();
126223             };
126224             ChangeTracker.prototype.pushRaw = function (sourceFile, change) {
126225                 ts.Debug.assertEqual(sourceFile.fileName, change.fileName);
126226                 for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) {
126227                     var c = _a[_i];
126228                     this.changes.push({
126229                         kind: ChangeKind.Text,
126230                         sourceFile: sourceFile,
126231                         text: c.newText,
126232                         range: ts.createTextRangeFromSpan(c.span),
126233                     });
126234                 }
126235             };
126236             ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
126237                 this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
126238             };
126239             ChangeTracker.prototype.delete = function (sourceFile, node) {
126240                 this.deletedNodes.push({ sourceFile: sourceFile, node: node });
126241             };
126242             ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) {
126243                 if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
126244                 this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options));
126245             };
126246             ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) {
126247                 this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
126248             };
126249             ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
126250                 if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
126251                 var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
126252                 var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
126253                 this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
126254             };
126255             ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
126256                 if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
126257                 var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
126258                 var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
126259                 this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
126260             };
126261             ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
126262                 if (options === void 0) { options = {}; }
126263                 this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
126264             };
126265             ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
126266                 if (options === void 0) { options = useNonAdjustedPositions; }
126267                 this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
126268             };
126269             ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
126270                 if (options === void 0) { options = useNonAdjustedPositions; }
126271                 this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
126272             };
126273             ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
126274                 if (options === void 0) { options = {}; }
126275                 this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
126276             };
126277             ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
126278                 if (options === void 0) { options = useNonAdjustedPositions; }
126279                 this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
126280             };
126281             ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
126282                 this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
126283             };
126284             ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
126285                 if (options === void 0) { options = useNonAdjustedPositions; }
126286                 this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
126287             };
126288             ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
126289                 var next = ts.findNextToken(node, node.parent, sourceFile);
126290                 return next && next.kind === 27 /* CommaToken */ ? next : undefined;
126291             };
126292             ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
126293                 var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
126294                 this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
126295             };
126296             ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
126297                 if (options === void 0) { options = {}; }
126298                 this.replaceRange(sourceFile, ts.createRange(pos), newNode, options);
126299             };
126300             ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) {
126301                 if (options === void 0) { options = {}; }
126302                 this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options);
126303             };
126304             ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) {
126305                 this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween);
126306             };
126307             ChangeTracker.prototype.insertNodesAtTopOfFile = function (sourceFile, newNodes, blankLineBetween) {
126308                 this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween);
126309             };
126310             ChangeTracker.prototype.insertAtTopOfFile = function (sourceFile, insert, blankLineBetween) {
126311                 var pos = getInsertionPositionAtSourceFileTop(sourceFile);
126312                 var options = {
126313                     prefix: pos === 0 ? undefined : this.newLineCharacter,
126314                     suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""),
126315                 };
126316                 if (ts.isArray(insert)) {
126317                     this.insertNodesAt(sourceFile, pos, insert, options);
126318                 }
126319                 else {
126320                     this.insertNodeAt(sourceFile, pos, insert, options);
126321                 }
126322             };
126323             ChangeTracker.prototype.insertFirstParameter = function (sourceFile, parameters, newParam) {
126324                 var p0 = ts.firstOrUndefined(parameters);
126325                 if (p0) {
126326                     this.insertNodeBefore(sourceFile, p0, newParam);
126327                 }
126328                 else {
126329                     this.insertNodeAt(sourceFile, parameters.pos, newParam);
126330                 }
126331             };
126332             ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
126333                 if (blankLineBetween === void 0) { blankLineBetween = false; }
126334                 this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween));
126335             };
126336             ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
126337                 var pos = before.getStart(sourceFile);
126338                 this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " });
126339             };
126340             ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) {
126341                 if (!before.modifiers) {
126342                     this.insertModifierBefore(sourceFile, modifier, before);
126343                     return;
126344                 }
126345                 var pos = before.modifiers.end;
126346                 this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " });
126347             };
126348             ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) {
126349                 var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile);
126350                 var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
126351                 // First try to see if we can put the comment on the previous line.
126352                 // We need to make sure that we are not in the middle of a string literal or a comment.
126353                 // If so, we do not want to separate the node from its comment if we can.
126354                 // Otherwise, add an extra new line immediately before the error span.
126355                 var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition);
126356                 var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position);
126357                 var indent = sourceFile.text.slice(lineStartPosition, startPosition);
126358                 var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent;
126359                 this.insertText(sourceFile, token.getStart(sourceFile), text);
126360             };
126361             ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) {
126362                 var fnStart = node.getStart(sourceFile);
126363                 if (node.jsDoc) {
126364                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
126365                         var jsdoc = _a[_i];
126366                         this.deleteRange(sourceFile, {
126367                             pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile),
126368                             end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {})
126369                         });
126370                     }
126371                 }
126372                 var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1);
126373                 var indent = sourceFile.text.slice(startPosition, fnStart);
126374                 this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent });
126375             };
126376             ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) {
126377                 this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text });
126378             };
126379             ChangeTracker.prototype.insertText = function (sourceFile, pos, text) {
126380                 this.replaceRangeWithText(sourceFile, ts.createRange(pos), text);
126381             };
126382             /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
126383             ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) {
126384                 var _a;
126385                 var endNode;
126386                 if (ts.isFunctionLike(node)) {
126387                     endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile);
126388                     if (!endNode) {
126389                         if (!ts.isArrowFunction(node))
126390                             return false; // Function missing parentheses, give up
126391                         // If no `)`, is an arrow function `x => x`, so use the end of the first parameter
126392                         endNode = ts.first(node.parameters);
126393                     }
126394                 }
126395                 else {
126396                     endNode = (_a = (node.kind === 242 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name;
126397                 }
126398                 this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " });
126399                 return true;
126400             };
126401             ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) {
126402                 var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1;
126403                 var suffix = node.parameters.length ? ", " : "";
126404                 this.insertNodeAt(sourceFile, start, type, { prefix: "this: ", suffix: suffix });
126405             };
126406             ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) {
126407                 // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter
126408                 var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile);
126409                 this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" });
126410             };
126411             ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, inserted, doubleNewlines) {
126412                 if (ts.isStatement(before) || ts.isClassElement(before)) {
126413                     return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
126414                 }
126415                 else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2;
126416                     return { suffix: ", " };
126417                 }
126418                 else if (ts.isParameter(before)) {
126419                     return ts.isParameter(inserted) ? { suffix: ", " } : {};
126420                 }
126421                 else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) {
126422                     return { suffix: ", " };
126423                 }
126424                 return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
126425             };
126426             ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
126427                 var firstStatement = ts.firstOrUndefined(ctr.body.statements);
126428                 if (!firstStatement || !ctr.body.multiLine) {
126429                     this.replaceConstructorBody(sourceFile, ctr, __spreadArrays([newStatement], ctr.body.statements));
126430                 }
126431                 else {
126432                     this.insertNodeBefore(sourceFile, firstStatement, newStatement);
126433                 }
126434             };
126435             ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) {
126436                 var lastStatement = ts.lastOrUndefined(ctr.body.statements);
126437                 if (!lastStatement || !ctr.body.multiLine) {
126438                     this.replaceConstructorBody(sourceFile, ctr, __spreadArrays(ctr.body.statements, [newStatement]));
126439                 }
126440                 else {
126441                     this.insertNodeAfter(sourceFile, lastStatement, newStatement);
126442                 }
126443             };
126444             ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) {
126445                 this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
126446             };
126447             ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
126448                 var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
126449                 this.insertNodeAt(sourceFile, pos, newNode, {
126450                     prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
126451                     suffix: this.newLineCharacter
126452                 });
126453             };
126454             ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
126455                 this.insertNodeAtStartWorker(sourceFile, cls, newElement);
126456             };
126457             ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) {
126458                 this.insertNodeAtStartWorker(sourceFile, obj, newElement);
126459             };
126460             ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) {
126461                 var _a;
126462                 var indentation = (_a = this.guessIndentationFromExistingMembers(sourceFile, cls)) !== null && _a !== void 0 ? _a : this.computeIndentationForNewMember(sourceFile, cls);
126463                 this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, cls, indentation));
126464             };
126465             /**
126466              * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on
126467              * new lines and must share the same indentation.
126468              */
126469             ChangeTracker.prototype.guessIndentationFromExistingMembers = function (sourceFile, cls) {
126470                 var indentation;
126471                 var lastRange = cls;
126472                 for (var _i = 0, _a = getMembersOrProperties(cls); _i < _a.length; _i++) {
126473                     var member = _a[_i];
126474                     if (ts.rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) {
126475                         // each indented member must be on a new line
126476                         return undefined;
126477                     }
126478                     var memberStart = member.getStart(sourceFile);
126479                     var memberIndentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options);
126480                     if (indentation === undefined) {
126481                         indentation = memberIndentation;
126482                     }
126483                     else if (memberIndentation !== indentation) {
126484                         // indentation of multiple members is not consistent
126485                         return undefined;
126486                     }
126487                     lastRange = member;
126488                 }
126489                 return indentation;
126490             };
126491             ChangeTracker.prototype.computeIndentationForNewMember = function (sourceFile, cls) {
126492                 var _a;
126493                 var clsStart = cls.getStart(sourceFile);
126494                 return ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
126495                     + ((_a = this.formatContext.options.indentSize) !== null && _a !== void 0 ? _a : 4);
126496             };
126497             ChangeTracker.prototype.getInsertNodeAtStartInsertOptions = function (sourceFile, cls, indentation) {
126498                 // Rules:
126499                 // - Always insert leading newline.
126500                 // - For object literals:
126501                 //   - Add a trailing comma if there are existing members in the node, or the source file is not a JSON file
126502                 //     (because trailing commas are generally illegal in a JSON file).
126503                 //   - Add a leading comma if the source file is not a JSON file, there are existing insertions,
126504                 //     and the node is empty (because we didn't add a trailing comma per the previous rule).
126505                 // - Only insert a trailing newline if body is single-line and there are no other insertions for the node.
126506                 //   NOTE: This is handled in `finishClassesWithNodesInsertedAtStart`.
126507                 var members = getMembersOrProperties(cls);
126508                 var isEmpty = members.length === 0;
126509                 var isFirstInsertion = ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile });
126510                 var insertTrailingComma = ts.isObjectLiteralExpression(cls) && (!ts.isJsonSourceFile(sourceFile) || !isEmpty);
126511                 var insertLeadingComma = ts.isObjectLiteralExpression(cls) && ts.isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion;
126512                 return {
126513                     indentation: indentation,
126514                     prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter,
126515                     suffix: insertTrailingComma ? "," : ""
126516                 };
126517             };
126518             ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) {
126519                 var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
126520                 this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
126521             };
126522             ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
126523                 var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
126524                 this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
126525             };
126526             ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) {
126527                 this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " });
126528             };
126529             ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) {
126530                 var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes));
126531                 this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
126532             };
126533             ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
126534                 if (needSemicolonBetween(after, newNode)) {
126535                     // check if previous statement ends with semicolon
126536                     // if not - insert semicolon to preserve the code from changing the meaning due to ASI
126537                     if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) {
126538                         this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */));
126539                     }
126540                 }
126541                 var endPosition = getAdjustedEndPosition(sourceFile, after, {});
126542                 return endPosition;
126543             };
126544             ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
126545                 var options = this.getInsertNodeAfterOptionsWorker(after);
126546                 return __assign(__assign({}, options), { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix });
126547             };
126548             ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) {
126549                 switch (node.kind) {
126550                     case 245 /* ClassDeclaration */:
126551                     case 249 /* ModuleDeclaration */:
126552                         return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
126553                     case 242 /* VariableDeclaration */:
126554                     case 10 /* StringLiteral */:
126555                     case 75 /* Identifier */:
126556                         return { prefix: ", " };
126557                     case 281 /* PropertyAssignment */:
126558                         return { suffix: "," + this.newLineCharacter };
126559                     case 89 /* ExportKeyword */:
126560                         return { prefix: " " };
126561                     case 156 /* Parameter */:
126562                         return {};
126563                     default:
126564                         ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it
126565                         return { suffix: this.newLineCharacter };
126566                 }
126567             };
126568             ChangeTracker.prototype.insertName = function (sourceFile, node, name) {
126569                 ts.Debug.assert(!node.name);
126570                 if (node.kind === 202 /* ArrowFunction */) {
126571                     var arrow = ts.findChildOfKind(node, 38 /* EqualsGreaterThanToken */, sourceFile);
126572                     var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile);
126573                     if (lparen) {
126574                         // `() => {}` --> `function f() {}`
126575                         this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(94 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " });
126576                         deleteNode(this, sourceFile, arrow);
126577                     }
126578                     else {
126579                         // `x => {}` -> `function f(x) {}`
126580                         this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "(");
126581                         // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)`
126582                         this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */));
126583                     }
126584                     if (node.body.kind !== 223 /* Block */) {
126585                         // `() => 0` => `function f() { return 0; }`
126586                         this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(101 /* ReturnKeyword */)], { joiner: " ", suffix: " " });
126587                         this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " });
126588                     }
126589                 }
126590                 else {
126591                     var pos = ts.findChildOfKind(node, node.kind === 201 /* FunctionExpression */ ? 94 /* FunctionKeyword */ : 80 /* ClassKeyword */, sourceFile).end;
126592                     this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
126593                 }
126594             };
126595             ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
126596                 this.insertText(sourceFile, node.getStart(sourceFile), "export ");
126597             };
126598             /**
126599              * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
126600              * i.e. arguments in arguments lists, parameters in parameter lists etc.
126601              * Note that separators are part of the node in statements and class elements.
126602              */
126603             ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
126604                 if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
126605                 if (!containingList) {
126606                     ts.Debug.fail("node is not a list element");
126607                     return;
126608                 }
126609                 var index = ts.indexOfNode(containingList, after);
126610                 if (index < 0) {
126611                     return;
126612                 }
126613                 var end = after.getEnd();
126614                 if (index !== containingList.length - 1) {
126615                     // any element except the last one
126616                     // use next sibling as an anchor
126617                     var nextToken = ts.getTokenAtPosition(sourceFile, after.end);
126618                     if (nextToken && isSeparator(after, nextToken)) {
126619                         // for list
126620                         // a, b, c
126621                         // create change for adding 'e' after 'a' as
126622                         // - find start of next element after a (it is b)
126623                         // - use this start as start and end position in final change
126624                         // - build text of change by formatting the text of node + separator + whitespace trivia of b
126625                         // in multiline case it will work as
126626                         //   a,
126627                         //   b,
126628                         //   c,
126629                         // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#')
126630                         //   a,*
126631                         // ***insertedtext<separator>#
126632                         // ###b,
126633                         //   c,
126634                         // find line and character of the next element
126635                         var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart()));
126636                         // find line and character of the token that precedes next element (usually it is separator)
126637                         var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end);
126638                         var prefix = void 0;
126639                         var startPos = void 0;
126640                         if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) {
126641                             // next element is located on the same line with separator:
126642                             // a,$$$$b
126643                             //  ^    ^
126644                             //  |    |-next element
126645                             //  |-separator
126646                             // where $$$ is some leading trivia
126647                             // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces
126648                             // a,    x,$$$$b
126649                             //  ^    ^     ^
126650                             //  |    |     |-next element
126651                             //  |    |-new inserted node padded with spaces
126652                             //  |-separator
126653                             startPos = nextToken.end;
126654                             prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character);
126655                         }
126656                         else {
126657                             // next element is located on different line that separator
126658                             // let insert position be the beginning of the line that contains next element
126659                             startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile);
126660                         }
126661                         // write separator and leading trivia of the next element as suffix
126662                         var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile));
126663                         this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix });
126664                     }
126665                 }
126666                 else {
126667                     var afterStart = after.getStart(sourceFile);
126668                     var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile);
126669                     var separator = void 0;
126670                     var multilineList = false;
126671                     // insert element after the last element in the list that has more than one item
126672                     // pick the element preceding the after element to:
126673                     // - pick the separator
126674                     // - determine if list is a multiline
126675                     if (containingList.length === 1) {
126676                         // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise
126677                         // i.e. var x = 1 // this is x
126678                         //     | new element will be inserted at this position
126679                         separator = 27 /* CommaToken */;
126680                     }
126681                     else {
126682                         // element has more than one element, pick separator from the list
126683                         var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile);
126684                         separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */;
126685                         // determine if list is multiline by checking lines of after element and element that precedes it.
126686                         var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile);
126687                         multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition;
126688                     }
126689                     if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) {
126690                         // in this case we'll always treat containing list as multiline
126691                         multilineList = true;
126692                     }
126693                     if (multilineList) {
126694                         // insert separator immediately following the 'after' node to preserve comments in trailing trivia
126695                         this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator));
126696                         // use the same indentation as 'after' item
126697                         var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options);
126698                         // insert element before the line break on the line that contains 'after' element
126699                         var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false);
126700                         if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) {
126701                             insertPos--;
126702                         }
126703                         this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter });
126704                     }
126705                     else {
126706                         this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
126707                     }
126708                 }
126709             };
126710             ChangeTracker.prototype.parenthesizeExpression = function (sourceFile, expression) {
126711                 this.replaceRange(sourceFile, ts.rangeOfNode(expression), ts.createParen(expression));
126712             };
126713             ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () {
126714                 var _this = this;
126715                 this.classesWithNodesInsertedAtStart.forEach(function (_a) {
126716                     var node = _a.node, sourceFile = _a.sourceFile;
126717                     var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1];
126718                     if (openBraceEnd !== undefined && closeBraceEnd !== undefined) {
126719                         var isEmpty = getMembersOrProperties(node).length === 0;
126720                         var isSingleLine = ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile);
126721                         if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) {
126722                             // For `class C { }` remove the whitespace inside the braces.
126723                             _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1));
126724                         }
126725                         if (isSingleLine) {
126726                             _this.insertText(sourceFile, closeBraceEnd - 1, _this.newLineCharacter);
126727                         }
126728                     }
126729                 });
126730             };
126731             ChangeTracker.prototype.finishDeleteDeclarations = function () {
126732                 var _this = this;
126733                 var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
126734                 var _loop_9 = function (sourceFile, node) {
126735                     if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
126736                         if (ts.isArray(node)) {
126737                             this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
126738                         }
126739                         else {
126740                             deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node);
126741                         }
126742                     }
126743                 };
126744                 var this_1 = this;
126745                 for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
126746                     var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
126747                     _loop_9(sourceFile, node);
126748                 }
126749                 deletedNodesInLists.forEach(function (node) {
126750                     var sourceFile = node.getSourceFile();
126751                     var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile);
126752                     if (node !== ts.last(list))
126753                         return;
126754                     var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2);
126755                     if (lastNonDeletedIndex !== -1) {
126756                         _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
126757                     }
126758                 });
126759             };
126760             /**
126761              * Note: after calling this, the TextChanges object must be discarded!
126762              * @param validate only for tests
126763              *    The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
126764              *    so we can only call this once and can't get the non-formatted text separately.
126765              */
126766             ChangeTracker.prototype.getChanges = function (validate) {
126767                 this.finishDeleteDeclarations();
126768                 this.finishClassesWithNodesInsertedAtStart();
126769                 var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
126770                 for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) {
126771                     var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements;
126772                     changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext));
126773                 }
126774                 return changes;
126775             };
126776             ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
126777                 this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
126778             };
126779             return ChangeTracker;
126780         }());
126781         textChanges_3.ChangeTracker = ChangeTracker;
126782         // find first non-whitespace position in the leading trivia of the node
126783         function startPositionToDeleteNodeInList(sourceFile, node) {
126784             return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
126785         }
126786         function getClassOrObjectBraceEnds(cls, sourceFile) {
126787             var open = ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile);
126788             var close = ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile);
126789             return [open === null || open === void 0 ? void 0 : open.end, close === null || close === void 0 ? void 0 : close.end];
126790         }
126791         function getMembersOrProperties(cls) {
126792             return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members;
126793         }
126794         function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) {
126795             return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext);
126796         }
126797         textChanges_3.getNewFileText = getNewFileText;
126798         var changesToText;
126799         (function (changesToText) {
126800             function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
126801                 return ts.mapDefined(ts.group(changes, function (c) { return c.sourceFile.path; }), function (changesInFile) {
126802                     var sourceFile = changesInFile[0].sourceFile;
126803                     // order changes by start position
126804                     // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa.
126805                     var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
126806                     var _loop_10 = function (i) {
126807                         ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
126808                             return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
126809                         });
126810                     };
126811                     // verify that change intervals do not overlap, except possibly at end points.
126812                     for (var i = 0; i < normalized.length - 1; i++) {
126813                         _loop_10(i);
126814                     }
126815                     var textChanges = ts.mapDefined(normalized, function (c) {
126816                         var span = ts.createTextSpanFromRange(c.range);
126817                         var newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate);
126818                         // Filter out redundant changes.
126819                         if (span.length === newText.length && ts.stringContainsAt(sourceFile.text, newText, span.start)) {
126820                             return undefined;
126821                         }
126822                         return ts.createTextChange(span, newText);
126823                     });
126824                     return textChanges.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges } : undefined;
126825                 });
126826             }
126827             changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
126828             function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) {
126829                 var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext);
126830                 return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true };
126831             }
126832             changesToText.newFileChanges = newFileChanges;
126833             function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
126834                 // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
126835                 var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
126836                 var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 99 /* ESNext */, /*setParentNodes*/ true, scriptKind);
126837                 var changes = ts.formatting.formatDocument(sourceFile, formatContext);
126838                 return applyChanges(nonFormattedText, changes) + newLineCharacter;
126839             }
126840             changesToText.newFileChangesWorker = newFileChangesWorker;
126841             function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
126842                 if (change.kind === ChangeKind.Remove) {
126843                     return "";
126844                 }
126845                 if (change.kind === ChangeKind.Text) {
126846                     return change.text;
126847                 }
126848                 var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos;
126849                 var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); };
126850                 var text = change.kind === ChangeKind.ReplaceWithMultipleNodes
126851                     ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217
126852                     : format(change.node);
126853                 // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
126854                 var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, "");
126855                 return (options.prefix || "") + noIndent
126856                     + ((!options.suffix || ts.endsWith(noIndent, options.suffix))
126857                         ? "" : options.suffix);
126858             }
126859             function getFormatCodeSettingsForWriting(_a, sourceFile) {
126860                 var options = _a.options;
126861                 var shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === ts.SemicolonPreference.Ignore;
126862                 var shouldRemoveSemicolons = options.semicolons === ts.SemicolonPreference.Remove || shouldAutoDetectSemicolonPreference && !ts.probablyUsesSemicolons(sourceFile);
126863                 return __assign(__assign({}, options), { semicolons: shouldRemoveSemicolons ? ts.SemicolonPreference.Remove : ts.SemicolonPreference.Ignore });
126864             }
126865             /** Note: this may mutate `nodeIn`. */
126866             function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) {
126867                 var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta;
126868                 var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text;
126869                 if (validate)
126870                     validate(node, text);
126871                 var formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile);
126872                 var initialIndentation = indentation !== undefined
126873                     ? indentation
126874                     : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos);
126875                 if (delta === undefined) {
126876                     delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? (formatOptions.indentSize || 0) : 0;
126877                 }
126878                 var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } };
126879                 var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, __assign(__assign({}, formatContext), { options: formatOptions }));
126880                 return applyChanges(text, changes);
126881             }
126882             /** Note: output node may be mutated input node. */
126883             function getNonformattedText(node, sourceFile, newLineCharacter) {
126884                 var writer = createWriter(newLineCharacter);
126885                 var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
126886                 ts.createPrinter({ newLine: newLine, neverAsciiEscape: true, preserveSourceNewlines: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
126887                 return { text: writer.getText(), node: assignPositionsToNode(node) };
126888             }
126889             changesToText.getNonformattedText = getNonformattedText;
126890         })(changesToText || (changesToText = {}));
126891         function applyChanges(text, changes) {
126892             for (var i = changes.length - 1; i >= 0; i--) {
126893                 var _a = changes[i], span = _a.span, newText = _a.newText;
126894                 text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span));
126895             }
126896             return text;
126897         }
126898         textChanges_3.applyChanges = applyChanges;
126899         function isTrivia(s) {
126900             return ts.skipTrivia(s, 0) === s.length;
126901         }
126902         function assignPositionsToNode(node) {
126903             var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217
126904             // create proxy node for non synthesized nodes
126905             var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited);
126906             newNode.pos = getPos(node);
126907             newNode.end = getEnd(node);
126908             return newNode;
126909         }
126910         function assignPositionsToNodeArray(nodes, visitor, test, start, count) {
126911             var visited = ts.visitNodes(nodes, visitor, test, start, count);
126912             if (!visited) {
126913                 return visited;
126914             }
126915             // clone nodearray if necessary
126916             var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited;
126917             nodeArray.pos = getPos(nodes);
126918             nodeArray.end = getEnd(nodes);
126919             return nodeArray;
126920         }
126921         function createWriter(newLine) {
126922             var lastNonTriviaPosition = 0;
126923             var writer = ts.createTextWriter(newLine);
126924             var onEmitNode = function (hint, node, printCallback) {
126925                 if (node) {
126926                     setPos(node, lastNonTriviaPosition);
126927                 }
126928                 printCallback(hint, node);
126929                 if (node) {
126930                     setEnd(node, lastNonTriviaPosition);
126931                 }
126932             };
126933             var onBeforeEmitNodeArray = function (nodes) {
126934                 if (nodes) {
126935                     setPos(nodes, lastNonTriviaPosition);
126936                 }
126937             };
126938             var onAfterEmitNodeArray = function (nodes) {
126939                 if (nodes) {
126940                     setEnd(nodes, lastNonTriviaPosition);
126941                 }
126942             };
126943             var onBeforeEmitToken = function (node) {
126944                 if (node) {
126945                     setPos(node, lastNonTriviaPosition);
126946                 }
126947             };
126948             var onAfterEmitToken = function (node) {
126949                 if (node) {
126950                     setEnd(node, lastNonTriviaPosition);
126951                 }
126952             };
126953             function setLastNonTriviaPosition(s, force) {
126954                 if (force || !isTrivia(s)) {
126955                     lastNonTriviaPosition = writer.getTextPos();
126956                     var i = 0;
126957                     while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) {
126958                         i++;
126959                     }
126960                     // trim trailing whitespaces
126961                     lastNonTriviaPosition -= i;
126962                 }
126963             }
126964             function write(s) {
126965                 writer.write(s);
126966                 setLastNonTriviaPosition(s, /*force*/ false);
126967             }
126968             function writeComment(s) {
126969                 writer.writeComment(s);
126970             }
126971             function writeKeyword(s) {
126972                 writer.writeKeyword(s);
126973                 setLastNonTriviaPosition(s, /*force*/ false);
126974             }
126975             function writeOperator(s) {
126976                 writer.writeOperator(s);
126977                 setLastNonTriviaPosition(s, /*force*/ false);
126978             }
126979             function writePunctuation(s) {
126980                 writer.writePunctuation(s);
126981                 setLastNonTriviaPosition(s, /*force*/ false);
126982             }
126983             function writeTrailingSemicolon(s) {
126984                 writer.writeTrailingSemicolon(s);
126985                 setLastNonTriviaPosition(s, /*force*/ false);
126986             }
126987             function writeParameter(s) {
126988                 writer.writeParameter(s);
126989                 setLastNonTriviaPosition(s, /*force*/ false);
126990             }
126991             function writeProperty(s) {
126992                 writer.writeProperty(s);
126993                 setLastNonTriviaPosition(s, /*force*/ false);
126994             }
126995             function writeSpace(s) {
126996                 writer.writeSpace(s);
126997                 setLastNonTriviaPosition(s, /*force*/ false);
126998             }
126999             function writeStringLiteral(s) {
127000                 writer.writeStringLiteral(s);
127001                 setLastNonTriviaPosition(s, /*force*/ false);
127002             }
127003             function writeSymbol(s, sym) {
127004                 writer.writeSymbol(s, sym);
127005                 setLastNonTriviaPosition(s, /*force*/ false);
127006             }
127007             function writeLine(force) {
127008                 writer.writeLine(force);
127009             }
127010             function increaseIndent() {
127011                 writer.increaseIndent();
127012             }
127013             function decreaseIndent() {
127014                 writer.decreaseIndent();
127015             }
127016             function getText() {
127017                 return writer.getText();
127018             }
127019             function rawWrite(s) {
127020                 writer.rawWrite(s);
127021                 setLastNonTriviaPosition(s, /*force*/ false);
127022             }
127023             function writeLiteral(s) {
127024                 writer.writeLiteral(s);
127025                 setLastNonTriviaPosition(s, /*force*/ true);
127026             }
127027             function getTextPos() {
127028                 return writer.getTextPos();
127029             }
127030             function getLine() {
127031                 return writer.getLine();
127032             }
127033             function getColumn() {
127034                 return writer.getColumn();
127035             }
127036             function getIndent() {
127037                 return writer.getIndent();
127038             }
127039             function isAtStartOfLine() {
127040                 return writer.isAtStartOfLine();
127041             }
127042             function clear() {
127043                 writer.clear();
127044                 lastNonTriviaPosition = 0;
127045             }
127046             return {
127047                 onEmitNode: onEmitNode,
127048                 onBeforeEmitNodeArray: onBeforeEmitNodeArray,
127049                 onAfterEmitNodeArray: onAfterEmitNodeArray,
127050                 onBeforeEmitToken: onBeforeEmitToken,
127051                 onAfterEmitToken: onAfterEmitToken,
127052                 write: write,
127053                 writeComment: writeComment,
127054                 writeKeyword: writeKeyword,
127055                 writeOperator: writeOperator,
127056                 writePunctuation: writePunctuation,
127057                 writeTrailingSemicolon: writeTrailingSemicolon,
127058                 writeParameter: writeParameter,
127059                 writeProperty: writeProperty,
127060                 writeSpace: writeSpace,
127061                 writeStringLiteral: writeStringLiteral,
127062                 writeSymbol: writeSymbol,
127063                 writeLine: writeLine,
127064                 increaseIndent: increaseIndent,
127065                 decreaseIndent: decreaseIndent,
127066                 getText: getText,
127067                 rawWrite: rawWrite,
127068                 writeLiteral: writeLiteral,
127069                 getTextPos: getTextPos,
127070                 getLine: getLine,
127071                 getColumn: getColumn,
127072                 getIndent: getIndent,
127073                 isAtStartOfLine: isAtStartOfLine,
127074                 hasTrailingComment: function () { return writer.hasTrailingComment(); },
127075                 hasTrailingWhitespace: function () { return writer.hasTrailingWhitespace(); },
127076                 clear: clear
127077             };
127078         }
127079         function getInsertionPositionAtSourceFileTop(sourceFile) {
127080             var lastPrologue;
127081             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
127082                 var node = _a[_i];
127083                 if (ts.isPrologueDirective(node)) {
127084                     lastPrologue = node;
127085                 }
127086                 else {
127087                     break;
127088                 }
127089             }
127090             var position = 0;
127091             var text = sourceFile.text;
127092             if (lastPrologue) {
127093                 position = lastPrologue.end;
127094                 advancePastLineBreak();
127095                 return position;
127096             }
127097             var shebang = ts.getShebang(text);
127098             if (shebang !== undefined) {
127099                 position = shebang.length;
127100                 advancePastLineBreak();
127101             }
127102             var ranges = ts.getLeadingCommentRanges(text, position);
127103             if (!ranges)
127104                 return position;
127105             // Find the first attached comment to the first node and add before it
127106             var lastComment;
127107             var firstNodeLine;
127108             for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) {
127109                 var range = ranges_1[_b];
127110                 if (range.kind === 3 /* MultiLineCommentTrivia */) {
127111                     if (ts.isPinnedComment(text, range.pos)) {
127112                         lastComment = { range: range, pinnedOrTripleSlash: true };
127113                         continue;
127114                     }
127115                 }
127116                 else if (ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) {
127117                     lastComment = { range: range, pinnedOrTripleSlash: true };
127118                     continue;
127119                 }
127120                 if (lastComment) {
127121                     // Always insert after pinned or triple slash comments
127122                     if (lastComment.pinnedOrTripleSlash)
127123                         break;
127124                     // There was a blank line between the last comment and this comment.
127125                     // This comment is not part of the copyright comments
127126                     var commentLine = sourceFile.getLineAndCharacterOfPosition(range.pos).line;
127127                     var lastCommentEndLine = sourceFile.getLineAndCharacterOfPosition(lastComment.range.end).line;
127128                     if (commentLine >= lastCommentEndLine + 2)
127129                         break;
127130                 }
127131                 if (sourceFile.statements.length) {
127132                     if (firstNodeLine === undefined)
127133                         firstNodeLine = sourceFile.getLineAndCharacterOfPosition(sourceFile.statements[0].getStart()).line;
127134                     var commentEndLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
127135                     if (firstNodeLine < commentEndLine + 2)
127136                         break;
127137                 }
127138                 lastComment = { range: range, pinnedOrTripleSlash: false };
127139             }
127140             if (lastComment) {
127141                 position = lastComment.range.end;
127142                 advancePastLineBreak();
127143             }
127144             return position;
127145             function advancePastLineBreak() {
127146                 if (position < text.length) {
127147                     var charCode = text.charCodeAt(position);
127148                     if (ts.isLineBreak(charCode)) {
127149                         position++;
127150                         if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) {
127151                             position++;
127152                         }
127153                     }
127154                 }
127155             }
127156         }
127157         function isValidLocationToAddComment(sourceFile, position) {
127158             return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position);
127159         }
127160         textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment;
127161         function needSemicolonBetween(a, b) {
127162             return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 154 /* ComputedPropertyName */
127163                 || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[`
127164         }
127165         var deleteDeclaration;
127166         (function (deleteDeclaration_1) {
127167             function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) {
127168                 switch (node.kind) {
127169                     case 156 /* Parameter */: {
127170                         var oldFunction = node.parent;
127171                         if (ts.isArrowFunction(oldFunction) &&
127172                             oldFunction.parameters.length === 1 &&
127173                             !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) {
127174                             // Lambdas with exactly one parameter are special because, after removal, there
127175                             // must be an empty parameter list (i.e. `()`) and this won't necessarily be the
127176                             // case if the parameter is simply removed (e.g. in `x => 1`).
127177                             changes.replaceNodeWithText(sourceFile, node, "()");
127178                         }
127179                         else {
127180                             deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127181                         }
127182                         break;
127183                     }
127184                     case 254 /* ImportDeclaration */:
127185                     case 253 /* ImportEqualsDeclaration */:
127186                         var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax);
127187                         // For first import, leave header comment in place, otherwise only delete JSDoc comments
127188                         deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine });
127189                         break;
127190                     case 191 /* BindingElement */:
127191                         var pattern = node.parent;
127192                         var preserveComma = pattern.kind === 190 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements);
127193                         if (preserveComma) {
127194                             deleteNode(changes, sourceFile, node);
127195                         }
127196                         else {
127197                             deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127198                         }
127199                         break;
127200                     case 242 /* VariableDeclaration */:
127201                         deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node);
127202                         break;
127203                     case 155 /* TypeParameter */:
127204                         deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127205                         break;
127206                     case 258 /* ImportSpecifier */:
127207                         var namedImports = node.parent;
127208                         if (namedImports.elements.length === 1) {
127209                             deleteImportBinding(changes, sourceFile, namedImports);
127210                         }
127211                         else {
127212                             deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127213                         }
127214                         break;
127215                     case 256 /* NamespaceImport */:
127216                         deleteImportBinding(changes, sourceFile, node);
127217                         break;
127218                     case 26 /* SemicolonToken */:
127219                         deleteNode(changes, sourceFile, node, { trailingTriviaOption: TrailingTriviaOption.Exclude });
127220                         break;
127221                     case 94 /* FunctionKeyword */:
127222                         deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude });
127223                         break;
127224                     case 245 /* ClassDeclaration */:
127225                     case 244 /* FunctionDeclaration */:
127226                         deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine });
127227                         break;
127228                     default:
127229                         if (ts.isImportClause(node.parent) && node.parent.name === node) {
127230                             deleteDefaultImport(changes, sourceFile, node.parent);
127231                         }
127232                         else if (ts.isCallExpression(node.parent) && ts.contains(node.parent.arguments, node)) {
127233                             deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127234                         }
127235                         else {
127236                             deleteNode(changes, sourceFile, node);
127237                         }
127238                 }
127239             }
127240             deleteDeclaration_1.deleteDeclaration = deleteDeclaration;
127241             function deleteDefaultImport(changes, sourceFile, importClause) {
127242                 if (!importClause.namedBindings) {
127243                     // Delete the whole import
127244                     deleteNode(changes, sourceFile, importClause.parent);
127245                 }
127246                 else {
127247                     // import |d,| * as ns from './file'
127248                     var start = importClause.name.getStart(sourceFile);
127249                     var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end);
127250                     if (nextToken && nextToken.kind === 27 /* CommaToken */) {
127251                         // shift first non-whitespace position after comma to the start position of the node
127252                         var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true);
127253                         changes.deleteRange(sourceFile, { pos: start, end: end });
127254                     }
127255                     else {
127256                         deleteNode(changes, sourceFile, importClause.name);
127257                     }
127258                 }
127259             }
127260             function deleteImportBinding(changes, sourceFile, node) {
127261                 if (node.parent.name) {
127262                     // Delete named imports while preserving the default import
127263                     // import d|, * as ns| from './file'
127264                     // import d|, { a }| from './file'
127265                     var previousToken = ts.Debug.checkDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1));
127266                     changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end });
127267                 }
127268                 else {
127269                     // Delete the entire import declaration
127270                     // |import * as ns from './file'|
127271                     // |import { a } from './file'|
127272                     var importDecl = ts.getAncestor(node, 254 /* ImportDeclaration */);
127273                     deleteNode(changes, sourceFile, importDecl);
127274                 }
127275             }
127276             function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) {
127277                 var parent = node.parent;
127278                 if (parent.kind === 280 /* CatchClause */) {
127279                     // TODO: There's currently no unused diagnostic for this, could be a suggestion
127280                     changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile));
127281                     return;
127282                 }
127283                 if (parent.declarations.length !== 1) {
127284                     deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127285                     return;
127286                 }
127287                 var gp = parent.parent;
127288                 switch (gp.kind) {
127289                     case 232 /* ForOfStatement */:
127290                     case 231 /* ForInStatement */:
127291                         changes.replaceNode(sourceFile, node, ts.createObjectLiteral());
127292                         break;
127293                     case 230 /* ForStatement */:
127294                         deleteNode(changes, sourceFile, parent);
127295                         break;
127296                     case 225 /* VariableStatement */:
127297                         deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine });
127298                         break;
127299                     default:
127300                         ts.Debug.assertNever(gp);
127301                 }
127302             }
127303         })(deleteDeclaration || (deleteDeclaration = {}));
127304         /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
127305         // Exported for tests only! (TODO: improve tests to not need this)
127306         function deleteNode(changes, sourceFile, node, options) {
127307             if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
127308             var startPosition = getAdjustedStartPosition(sourceFile, node, options);
127309             var endPosition = getAdjustedEndPosition(sourceFile, node, options);
127310             changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
127311         }
127312         textChanges_3.deleteNode = deleteNode;
127313         function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) {
127314             var containingList = ts.Debug.checkDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile));
127315             var index = ts.indexOfNode(containingList, node);
127316             ts.Debug.assert(index !== -1);
127317             if (containingList.length === 1) {
127318                 deleteNode(changes, sourceFile, node);
127319                 return;
127320             }
127321             // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node.
127322             // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`.
127323             ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice");
127324             deletedNodesInLists.add(node);
127325             changes.deleteRange(sourceFile, {
127326                 pos: startPositionToDeleteNodeInList(sourceFile, node),
127327                 end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]),
127328             });
127329         }
127330     })(textChanges = ts.textChanges || (ts.textChanges = {}));
127331 })(ts || (ts = {}));
127332 /* @internal */
127333 var ts;
127334 (function (ts) {
127335     var codefix;
127336     (function (codefix) {
127337         var errorCodeToFixes = ts.createMultiMap();
127338         var fixIdToRegistration = ts.createMap();
127339         function diagnosticToString(diag) {
127340             return ts.isArray(diag)
127341                 ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1))
127342                 : ts.getLocaleSpecificMessage(diag);
127343         }
127344         function createCodeFixActionWithoutFixAll(fixName, changes, description) {
127345             return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined);
127346         }
127347         codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll;
127348         function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) {
127349             return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command);
127350         }
127351         codefix.createCodeFixAction = createCodeFixAction;
127352         function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) {
127353             return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined };
127354         }
127355         function registerCodeFix(reg) {
127356             for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) {
127357                 var error = _a[_i];
127358                 errorCodeToFixes.add(String(error), reg);
127359             }
127360             if (reg.fixIds) {
127361                 for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) {
127362                     var fixId = _c[_b];
127363                     ts.Debug.assert(!fixIdToRegistration.has(fixId));
127364                     fixIdToRegistration.set(fixId, reg);
127365                 }
127366             }
127367         }
127368         codefix.registerCodeFix = registerCodeFix;
127369         function getSupportedErrorCodes() {
127370             return ts.arrayFrom(errorCodeToFixes.keys());
127371         }
127372         codefix.getSupportedErrorCodes = getSupportedErrorCodes;
127373         function removeFixIdIfFixAllUnavailable(registration, diagnostics) {
127374             var errorCodes = registration.errorCodes;
127375             var maybeFixableDiagnostics = 0;
127376             for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
127377                 var diag = diagnostics_1[_i];
127378                 if (ts.contains(errorCodes, diag.code))
127379                     maybeFixableDiagnostics++;
127380                 if (maybeFixableDiagnostics > 1)
127381                     break;
127382             }
127383             var fixAllUnavailable = maybeFixableDiagnostics < 2;
127384             return function (_a) {
127385                 var fixId = _a.fixId, fixAllDescription = _a.fixAllDescription, action = __rest(_a, ["fixId", "fixAllDescription"]);
127386                 return fixAllUnavailable ? action : __assign(__assign({}, action), { fixId: fixId, fixAllDescription: fixAllDescription });
127387             };
127388         }
127389         function getFixes(context) {
127390             var diagnostics = getDiagnostics(context);
127391             var registrations = errorCodeToFixes.get(String(context.errorCode));
127392             return ts.flatMap(registrations, function (f) { return ts.map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)); });
127393         }
127394         codefix.getFixes = getFixes;
127395         function getAllFixes(context) {
127396             // Currently fixId is always a string.
127397             return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context);
127398         }
127399         codefix.getAllFixes = getAllFixes;
127400         function createCombinedCodeActions(changes, commands) {
127401             return { changes: changes, commands: commands };
127402         }
127403         codefix.createCombinedCodeActions = createCombinedCodeActions;
127404         function createFileTextChanges(fileName, textChanges) {
127405             return { fileName: fileName, textChanges: textChanges };
127406         }
127407         codefix.createFileTextChanges = createFileTextChanges;
127408         function codeFixAll(context, errorCodes, use) {
127409             var commands = [];
127410             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); });
127411             return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands);
127412         }
127413         codefix.codeFixAll = codeFixAll;
127414         function eachDiagnostic(context, errorCodes, cb) {
127415             for (var _i = 0, _a = getDiagnostics(context); _i < _a.length; _i++) {
127416                 var diag = _a[_i];
127417                 if (ts.contains(errorCodes, diag.code)) {
127418                     cb(diag);
127419                 }
127420             }
127421         }
127422         codefix.eachDiagnostic = eachDiagnostic;
127423         function getDiagnostics(_a) {
127424             var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken;
127425             return __spreadArrays(program.getSemanticDiagnostics(sourceFile, cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken));
127426         }
127427     })(codefix = ts.codefix || (ts.codefix = {}));
127428 })(ts || (ts = {}));
127429 /* @internal */
127430 var ts;
127431 (function (ts) {
127432     var refactor;
127433     (function (refactor_1) {
127434         // A map with the refactor code as key, the refactor itself as value
127435         // e.g.  nonSuggestableRefactors[refactorCode] -> the refactor you want
127436         var refactors = ts.createMap();
127437         /** @param name An unique code associated with each refactor. Does not have to be human-readable. */
127438         function registerRefactor(name, refactor) {
127439             refactors.set(name, refactor);
127440         }
127441         refactor_1.registerRefactor = registerRefactor;
127442         function getApplicableRefactors(context) {
127443             return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) {
127444                 return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context);
127445             }));
127446         }
127447         refactor_1.getApplicableRefactors = getApplicableRefactors;
127448         function getEditsForRefactor(context, refactorName, actionName) {
127449             var refactor = refactors.get(refactorName);
127450             return refactor && refactor.getEditsForAction(context, actionName);
127451         }
127452         refactor_1.getEditsForRefactor = getEditsForRefactor;
127453     })(refactor = ts.refactor || (ts.refactor = {}));
127454 })(ts || (ts = {}));
127455 /* @internal */
127456 var ts;
127457 (function (ts) {
127458     var codefix;
127459     (function (codefix) {
127460         var fixId = "addConvertToUnknownForNonOverlappingTypes";
127461         var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code];
127462         codefix.registerCodeFix({
127463             errorCodes: errorCodes,
127464             getCodeActions: function (context) {
127465                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
127466                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)];
127467             },
127468             fixIds: [fixId],
127469             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
127470         });
127471         function makeChange(changeTracker, sourceFile, pos) {
127472             var token = ts.getTokenAtPosition(sourceFile, pos);
127473             var assertion = ts.Debug.checkDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); }), "Expected to find an assertion expression");
127474             var replacement = ts.isAsExpression(assertion)
127475                 ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(148 /* UnknownKeyword */))
127476                 : ts.createTypeAssertion(ts.createKeywordTypeNode(148 /* UnknownKeyword */), assertion.expression);
127477             changeTracker.replaceNode(sourceFile, assertion.expression, replacement);
127478         }
127479     })(codefix = ts.codefix || (ts.codefix = {}));
127480 })(ts || (ts = {}));
127481 /* @internal */
127482 var ts;
127483 (function (ts) {
127484     var codefix;
127485     (function (codefix) {
127486         codefix.registerCodeFix({
127487             errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code],
127488             getCodeActions: function (context) {
127489                 var sourceFile = context.sourceFile;
127490                 var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
127491                     var exportDeclaration = ts.createExportDeclaration(
127492                     /*decorators*/ undefined, 
127493                     /*modifiers*/ undefined, ts.createNamedExports([]), 
127494                     /*moduleSpecifier*/ undefined, 
127495                     /*isTypeOnly*/ false);
127496                     changes.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration);
127497                 });
127498                 return [codefix.createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, ts.Diagnostics.Add_export_to_make_this_file_into_a_module)];
127499             },
127500         });
127501     })(codefix = ts.codefix || (ts.codefix = {}));
127502 })(ts || (ts = {}));
127503 /* @internal */
127504 var ts;
127505 (function (ts) {
127506     var codefix;
127507     (function (codefix) {
127508         var fixId = "addMissingAsync";
127509         var errorCodes = [
127510             ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
127511             ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code,
127512             ts.Diagnostics.Type_0_is_not_comparable_to_type_1.code
127513         ];
127514         codefix.registerCodeFix({
127515             fixIds: [fixId],
127516             errorCodes: errorCodes,
127517             getCodeActions: function (context) {
127518                 var sourceFile = context.sourceFile, errorCode = context.errorCode, cancellationToken = context.cancellationToken, program = context.program, span = context.span;
127519                 var diagnostic = ts.find(program.getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode));
127520                 var directSpan = diagnostic && diagnostic.relatedInformation && ts.find(diagnostic.relatedInformation, function (r) { return r.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; });
127521                 var decl = getFixableErrorSpanDeclaration(sourceFile, directSpan);
127522                 if (!decl) {
127523                     return;
127524                 }
127525                 var trackChanges = function (cb) { return ts.textChanges.ChangeTracker.with(context, cb); };
127526                 return [getFix(context, decl, trackChanges)];
127527             },
127528             getAllCodeActions: function (context) {
127529                 var sourceFile = context.sourceFile;
127530                 var fixedDeclarations = ts.createMap();
127531                 return codefix.codeFixAll(context, errorCodes, function (t, diagnostic) {
127532                     var span = diagnostic.relatedInformation && ts.find(diagnostic.relatedInformation, function (r) { return r.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; });
127533                     var decl = getFixableErrorSpanDeclaration(sourceFile, span);
127534                     if (!decl) {
127535                         return;
127536                     }
127537                     var trackChanges = function (cb) { return (cb(t), []); };
127538                     return getFix(context, decl, trackChanges, fixedDeclarations);
127539                 });
127540             },
127541         });
127542         function getFix(context, decl, trackChanges, fixedDeclarations) {
127543             var changes = trackChanges(function (t) { return makeChange(t, context.sourceFile, decl, fixedDeclarations); });
127544             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers);
127545         }
127546         function makeChange(changeTracker, sourceFile, insertionSite, fixedDeclarations) {
127547             if (fixedDeclarations) {
127548                 if (fixedDeclarations.has(ts.getNodeId(insertionSite).toString())) {
127549                     return;
127550                 }
127551             }
127552             fixedDeclarations === null || fixedDeclarations === void 0 ? void 0 : fixedDeclarations.set(ts.getNodeId(insertionSite).toString(), true);
127553             var cloneWithModifier = ts.getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ true);
127554             cloneWithModifier.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(ts.getModifierFlags(insertionSite) | 256 /* Async */));
127555             cloneWithModifier.modifierFlagsCache = 0;
127556             changeTracker.replaceNode(sourceFile, insertionSite, cloneWithModifier);
127557         }
127558         function getFixableErrorSpanDeclaration(sourceFile, span) {
127559             if (!span)
127560                 return undefined;
127561             var token = ts.getTokenAtPosition(sourceFile, span.start);
127562             // Checker has already done work to determine that async might be possible, and has attached
127563             // related info to the node, so start by finding the signature that exactly matches up
127564             // with the diagnostic range.
127565             var decl = ts.findAncestor(token, function (node) {
127566                 if (node.getStart(sourceFile) < span.start || node.getEnd() > ts.textSpanEnd(span)) {
127567                     return "quit";
127568                 }
127569                 return (ts.isArrowFunction(node) || ts.isMethodDeclaration(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node)) && ts.textSpansEqual(span, ts.createTextSpanFromNode(node, sourceFile));
127570             });
127571             return decl;
127572         }
127573         function getIsMatchingAsyncError(span, errorCode) {
127574             return function (_a) {
127575                 var start = _a.start, length = _a.length, relatedInformation = _a.relatedInformation, code = _a.code;
127576                 return ts.isNumber(start) && ts.isNumber(length) && ts.textSpansEqual({ start: start, length: length }, span) &&
127577                     code === errorCode &&
127578                     !!relatedInformation &&
127579                     ts.some(relatedInformation, function (related) { return related.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; });
127580             };
127581         }
127582     })(codefix = ts.codefix || (ts.codefix = {}));
127583 })(ts || (ts = {}));
127584 /* @internal */
127585 var ts;
127586 (function (ts) {
127587     var codefix;
127588     (function (codefix) {
127589         var fixId = "addMissingAwait";
127590         var propertyAccessCode = ts.Diagnostics.Property_0_does_not_exist_on_type_1.code;
127591         var callableConstructableErrorCodes = [
127592             ts.Diagnostics.This_expression_is_not_callable.code,
127593             ts.Diagnostics.This_expression_is_not_constructable.code,
127594         ];
127595         var errorCodes = __spreadArrays([
127596             ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code,
127597             ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
127598             ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
127599             ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code,
127600             ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code,
127601             ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code,
127602             ts.Diagnostics.Type_0_is_not_an_array_type.code,
127603             ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code,
127604             ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code,
127605             ts.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,
127606             ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
127607             ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
127608             ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code,
127609             ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
127610             propertyAccessCode
127611         ], callableConstructableErrorCodes);
127612         codefix.registerCodeFix({
127613             fixIds: [fixId],
127614             errorCodes: errorCodes,
127615             getCodeActions: function (context) {
127616                 var sourceFile = context.sourceFile, errorCode = context.errorCode, span = context.span, cancellationToken = context.cancellationToken, program = context.program;
127617                 var expression = getFixableErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program);
127618                 if (!expression) {
127619                     return;
127620                 }
127621                 var checker = context.program.getTypeChecker();
127622                 var trackChanges = function (cb) { return ts.textChanges.ChangeTracker.with(context, cb); };
127623                 return ts.compact([
127624                     getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges),
127625                     getUseSiteFix(context, expression, errorCode, checker, trackChanges)
127626                 ]);
127627             },
127628             getAllCodeActions: function (context) {
127629                 var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
127630                 var checker = context.program.getTypeChecker();
127631                 var fixedDeclarations = ts.createMap();
127632                 return codefix.codeFixAll(context, errorCodes, function (t, diagnostic) {
127633                     var expression = getFixableErrorSpanExpression(sourceFile, diagnostic.code, diagnostic, cancellationToken, program);
127634                     if (!expression) {
127635                         return;
127636                     }
127637                     var trackChanges = function (cb) { return (cb(t), []); };
127638                     return getDeclarationSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations)
127639                         || getUseSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations);
127640                 });
127641             },
127642         });
127643         function getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
127644             var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
127645             var awaitableInitializers = findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker);
127646             if (awaitableInitializers) {
127647                 var initializerChanges = trackChanges(function (t) {
127648                     ts.forEach(awaitableInitializers.initializers, function (_a) {
127649                         var expression = _a.expression;
127650                         return makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations);
127651                     });
127652                     if (fixedDeclarations && awaitableInitializers.needsSecondPassForFixAll) {
127653                         makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations);
127654                     }
127655                 });
127656                 // No fix-all because it will already be included once with the use site fix,
127657                 // and for simplicity the fix-all doesn‘t let the user choose between use-site and declaration-site fixes.
127658                 return codefix.createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1
127659                     ? [ts.Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name]
127660                     : ts.Diagnostics.Add_await_to_initializers);
127661             }
127662         }
127663         function getUseSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
127664             var changes = trackChanges(function (t) { return makeChange(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations); });
127665             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_await, fixId, ts.Diagnostics.Fix_all_expressions_possibly_missing_await);
127666         }
127667         function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) {
127668             var checker = program.getDiagnosticsProducingTypeChecker();
127669             var diagnostics = checker.getDiagnostics(sourceFile, cancellationToken);
127670             return ts.some(diagnostics, function (_a) {
127671                 var start = _a.start, length = _a.length, relatedInformation = _a.relatedInformation, code = _a.code;
127672                 return ts.isNumber(start) && ts.isNumber(length) && ts.textSpansEqual({ start: start, length: length }, span) &&
127673                     code === errorCode &&
127674                     !!relatedInformation &&
127675                     ts.some(relatedInformation, function (related) { return related.code === ts.Diagnostics.Did_you_forget_to_use_await.code; });
127676             });
127677         }
127678         function getFixableErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program) {
127679             var token = ts.getTokenAtPosition(sourceFile, span.start);
127680             // Checker has already done work to determine that await might be possible, and has attached
127681             // related info to the node, so start by finding the expression that exactly matches up
127682             // with the diagnostic range.
127683             var expression = ts.findAncestor(token, function (node) {
127684                 if (node.getStart(sourceFile) < span.start || node.getEnd() > ts.textSpanEnd(span)) {
127685                     return "quit";
127686                 }
127687                 return ts.isExpression(node) && ts.textSpansEqual(span, ts.createTextSpanFromNode(node, sourceFile));
127688             });
127689             return expression
127690                 && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program)
127691                 && isInsideAwaitableBody(expression) ? expression : undefined;
127692         }
127693         function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) {
127694             var identifiers = getIdentifiersFromErrorSpanExpression(expression, checker);
127695             if (!identifiers) {
127696                 return;
127697             }
127698             var isCompleteFix = identifiers.isCompleteFix;
127699             var initializers;
127700             var _loop_11 = function (identifier) {
127701                 var symbol = checker.getSymbolAtLocation(identifier);
127702                 if (!symbol) {
127703                     return "continue";
127704                 }
127705                 var declaration = ts.tryCast(symbol.valueDeclaration, ts.isVariableDeclaration);
127706                 var variableName = declaration && ts.tryCast(declaration.name, ts.isIdentifier);
127707                 var variableStatement = ts.getAncestor(declaration, 225 /* VariableStatement */);
127708                 if (!declaration || !variableStatement ||
127709                     declaration.type ||
127710                     !declaration.initializer ||
127711                     variableStatement.getSourceFile() !== sourceFile ||
127712                     ts.hasModifier(variableStatement, 1 /* Export */) ||
127713                     !variableName ||
127714                     !isInsideAwaitableBody(declaration.initializer)) {
127715                     isCompleteFix = false;
127716                     return "continue";
127717                 }
127718                 var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken);
127719                 var isUsedElsewhere = ts.FindAllReferences.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, function (reference) {
127720                     return identifier !== reference && !symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker);
127721                 });
127722                 if (isUsedElsewhere) {
127723                     isCompleteFix = false;
127724                     return "continue";
127725                 }
127726                 (initializers || (initializers = [])).push({
127727                     expression: declaration.initializer,
127728                     declarationSymbol: symbol,
127729                 });
127730             };
127731             for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) {
127732                 var identifier = _a[_i];
127733                 _loop_11(identifier);
127734             }
127735             return initializers && {
127736                 initializers: initializers,
127737                 needsSecondPassForFixAll: !isCompleteFix,
127738             };
127739         }
127740         function getIdentifiersFromErrorSpanExpression(expression, checker) {
127741             if (ts.isPropertyAccessExpression(expression.parent) && ts.isIdentifier(expression.parent.expression)) {
127742                 return { identifiers: [expression.parent.expression], isCompleteFix: true };
127743             }
127744             if (ts.isIdentifier(expression)) {
127745                 return { identifiers: [expression], isCompleteFix: true };
127746             }
127747             if (ts.isBinaryExpression(expression)) {
127748                 var sides = void 0;
127749                 var isCompleteFix = true;
127750                 for (var _i = 0, _a = [expression.left, expression.right]; _i < _a.length; _i++) {
127751                     var side = _a[_i];
127752                     var type = checker.getTypeAtLocation(side);
127753                     if (checker.getPromisedTypeOfPromise(type)) {
127754                         if (!ts.isIdentifier(side)) {
127755                             isCompleteFix = false;
127756                             continue;
127757                         }
127758                         (sides || (sides = [])).push(side);
127759                     }
127760                 }
127761                 return sides && { identifiers: sides, isCompleteFix: isCompleteFix };
127762             }
127763         }
127764         function symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker) {
127765             var errorNode = ts.isPropertyAccessExpression(reference.parent) ? reference.parent.name :
127766                 ts.isBinaryExpression(reference.parent) ? reference.parent :
127767                     reference;
127768             var diagnostic = ts.find(diagnostics, function (diagnostic) {
127769                 return diagnostic.start === errorNode.getStart(sourceFile) &&
127770                     (diagnostic.start + diagnostic.length) === errorNode.getEnd();
127771             });
127772             return diagnostic && ts.contains(errorCodes, diagnostic.code) ||
127773                 // A Promise is usually not correct in a binary expression (it’s not valid
127774                 // in an arithmetic expression and an equality comparison seems unusual),
127775                 // but if the other side of the binary expression has an error, the side
127776                 // is typed `any` which will squash the error that would identify this
127777                 // Promise as an invalid operand. So if the whole binary expression is
127778                 // typed `any` as a result, there is a strong likelihood that this Promise
127779                 // is accidentally missing `await`.
127780                 checker.getTypeAtLocation(errorNode).flags & 1 /* Any */;
127781         }
127782         function isInsideAwaitableBody(node) {
127783             return node.kind & 32768 /* AwaitContext */ || !!ts.findAncestor(node, function (ancestor) {
127784                 return ancestor.parent && ts.isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor ||
127785                     ts.isBlock(ancestor) && (ancestor.parent.kind === 244 /* FunctionDeclaration */ ||
127786                         ancestor.parent.kind === 201 /* FunctionExpression */ ||
127787                         ancestor.parent.kind === 202 /* ArrowFunction */ ||
127788                         ancestor.parent.kind === 161 /* MethodDeclaration */);
127789             });
127790         }
127791         function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) {
127792             if (ts.isBinaryExpression(insertionSite)) {
127793                 for (var _i = 0, _a = [insertionSite.left, insertionSite.right]; _i < _a.length; _i++) {
127794                     var side = _a[_i];
127795                     if (fixedDeclarations && ts.isIdentifier(side)) {
127796                         var symbol = checker.getSymbolAtLocation(side);
127797                         if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
127798                             continue;
127799                         }
127800                     }
127801                     var type = checker.getTypeAtLocation(side);
127802                     var newNode = checker.getPromisedTypeOfPromise(type) ? ts.createAwait(side) : side;
127803                     changeTracker.replaceNode(sourceFile, side, newNode);
127804                 }
127805             }
127806             else if (errorCode === propertyAccessCode && ts.isPropertyAccessExpression(insertionSite.parent)) {
127807                 if (fixedDeclarations && ts.isIdentifier(insertionSite.parent.expression)) {
127808                     var symbol = checker.getSymbolAtLocation(insertionSite.parent.expression);
127809                     if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
127810                         return;
127811                     }
127812                 }
127813                 changeTracker.replaceNode(sourceFile, insertionSite.parent.expression, ts.createParen(ts.createAwait(insertionSite.parent.expression)));
127814                 insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile);
127815             }
127816             else if (ts.contains(callableConstructableErrorCodes, errorCode) && ts.isCallOrNewExpression(insertionSite.parent)) {
127817                 if (fixedDeclarations && ts.isIdentifier(insertionSite)) {
127818                     var symbol = checker.getSymbolAtLocation(insertionSite);
127819                     if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
127820                         return;
127821                     }
127822                 }
127823                 changeTracker.replaceNode(sourceFile, insertionSite, ts.createParen(ts.createAwait(insertionSite)));
127824                 insertLeadingSemicolonIfNeeded(changeTracker, insertionSite, sourceFile);
127825             }
127826             else {
127827                 if (fixedDeclarations && ts.isVariableDeclaration(insertionSite.parent) && ts.isIdentifier(insertionSite.parent.name)) {
127828                     var symbol = checker.getSymbolAtLocation(insertionSite.parent.name);
127829                     if (symbol && !ts.addToSeen(fixedDeclarations, ts.getSymbolId(symbol))) {
127830                         return;
127831                     }
127832                 }
127833                 changeTracker.replaceNode(sourceFile, insertionSite, ts.createAwait(insertionSite));
127834             }
127835         }
127836         function insertLeadingSemicolonIfNeeded(changeTracker, beforeNode, sourceFile) {
127837             var precedingToken = ts.findPrecedingToken(beforeNode.pos, sourceFile);
127838             if (precedingToken && ts.positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
127839                 changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";");
127840             }
127841         }
127842     })(codefix = ts.codefix || (ts.codefix = {}));
127843 })(ts || (ts = {}));
127844 /* @internal */
127845 var ts;
127846 (function (ts) {
127847     var codefix;
127848     (function (codefix) {
127849         var fixId = "addMissingConst";
127850         var errorCodes = [
127851             ts.Diagnostics.Cannot_find_name_0.code,
127852             ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code
127853         ];
127854         codefix.registerCodeFix({
127855             errorCodes: errorCodes,
127856             getCodeActions: function (context) {
127857                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start, context.program); });
127858                 if (changes.length > 0) {
127859                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_const_to_unresolved_variable, fixId, ts.Diagnostics.Add_const_to_all_unresolved_variables)];
127860                 }
127861             },
127862             fixIds: [fixId],
127863             getAllCodeActions: function (context) {
127864                 var fixedNodes = new ts.NodeSet();
127865                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start, context.program, fixedNodes); });
127866             },
127867         });
127868         function makeChange(changeTracker, sourceFile, pos, program, fixedNodes) {
127869             var token = ts.getTokenAtPosition(sourceFile, pos);
127870             var forInitializer = ts.findAncestor(token, function (node) {
127871                 return ts.isForInOrOfStatement(node.parent) ? node.parent.initializer === node :
127872                     isPossiblyPartOfDestructuring(node) ? false : "quit";
127873             });
127874             if (forInitializer)
127875                 return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes);
127876             var parent = token.parent;
127877             if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isExpressionStatement(parent.parent)) {
127878                 return applyChange(changeTracker, token, sourceFile, fixedNodes);
127879             }
127880             if (ts.isArrayLiteralExpression(parent)) {
127881                 var checker_1 = program.getTypeChecker();
127882                 if (!ts.every(parent.elements, function (element) { return arrayElementCouldBeVariableDeclaration(element, checker_1); })) {
127883                     return;
127884                 }
127885                 return applyChange(changeTracker, parent, sourceFile, fixedNodes);
127886             }
127887             var commaExpression = ts.findAncestor(token, function (node) {
127888                 return ts.isExpressionStatement(node.parent) ? true :
127889                     isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit";
127890             });
127891             if (commaExpression) {
127892                 var checker = program.getTypeChecker();
127893                 if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) {
127894                     return;
127895                 }
127896                 return applyChange(changeTracker, commaExpression, sourceFile, fixedNodes);
127897             }
127898         }
127899         function applyChange(changeTracker, initializer, sourceFile, fixedNodes) {
127900             if (!fixedNodes || fixedNodes.tryAdd(initializer)) {
127901                 changeTracker.insertModifierBefore(sourceFile, 81 /* ConstKeyword */, initializer);
127902             }
127903         }
127904         function isPossiblyPartOfDestructuring(node) {
127905             switch (node.kind) {
127906                 case 75 /* Identifier */:
127907                 case 192 /* ArrayLiteralExpression */:
127908                 case 193 /* ObjectLiteralExpression */:
127909                 case 281 /* PropertyAssignment */:
127910                 case 282 /* ShorthandPropertyAssignment */:
127911                     return true;
127912                 default:
127913                     return false;
127914             }
127915         }
127916         function arrayElementCouldBeVariableDeclaration(expression, checker) {
127917             var identifier = ts.isIdentifier(expression) ? expression :
127918                 ts.isAssignmentExpression(expression, /*excludeCompoundAssignment*/ true) && ts.isIdentifier(expression.left) ? expression.left :
127919                     undefined;
127920             return !!identifier && !checker.getSymbolAtLocation(identifier);
127921         }
127922         function isPossiblyPartOfCommaSeperatedInitializer(node) {
127923             switch (node.kind) {
127924                 case 75 /* Identifier */:
127925                 case 209 /* BinaryExpression */:
127926                 case 27 /* CommaToken */:
127927                     return true;
127928                 default:
127929                     return false;
127930             }
127931         }
127932         function expressionCouldBeVariableDeclaration(expression, checker) {
127933             if (!ts.isBinaryExpression(expression)) {
127934                 return false;
127935             }
127936             if (expression.operatorToken.kind === 27 /* CommaToken */) {
127937                 return ts.every([expression.left, expression.right], function (expression) { return expressionCouldBeVariableDeclaration(expression, checker); });
127938             }
127939             return expression.operatorToken.kind === 62 /* EqualsToken */
127940                 && ts.isIdentifier(expression.left)
127941                 && !checker.getSymbolAtLocation(expression.left);
127942         }
127943     })(codefix = ts.codefix || (ts.codefix = {}));
127944 })(ts || (ts = {}));
127945 /* @internal */
127946 var ts;
127947 (function (ts) {
127948     var codefix;
127949     (function (codefix) {
127950         var fixId = "addMissingDeclareProperty";
127951         var errorCodes = [
127952             ts.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,
127953         ];
127954         codefix.registerCodeFix({
127955             errorCodes: errorCodes,
127956             getCodeActions: function (context) {
127957                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
127958                 if (changes.length > 0) {
127959                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Prefix_with_declare, fixId, ts.Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)];
127960                 }
127961             },
127962             fixIds: [fixId],
127963             getAllCodeActions: function (context) {
127964                 var fixedNodes = new ts.NodeSet();
127965                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start, fixedNodes); });
127966             },
127967         });
127968         function makeChange(changeTracker, sourceFile, pos, fixedNodes) {
127969             var token = ts.getTokenAtPosition(sourceFile, pos);
127970             if (!ts.isIdentifier(token)) {
127971                 return;
127972             }
127973             var declaration = token.parent;
127974             if (declaration.kind === 159 /* PropertyDeclaration */ &&
127975                 (!fixedNodes || fixedNodes.tryAdd(declaration))) {
127976                 changeTracker.insertModifierBefore(sourceFile, 130 /* DeclareKeyword */, declaration);
127977             }
127978         }
127979     })(codefix = ts.codefix || (ts.codefix = {}));
127980 })(ts || (ts = {}));
127981 /* @internal */
127982 var ts;
127983 (function (ts) {
127984     var codefix;
127985     (function (codefix) {
127986         var fixId = "addMissingInvocationForDecorator";
127987         var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code];
127988         codefix.registerCodeFix({
127989             errorCodes: errorCodes,
127990             getCodeActions: function (context) {
127991                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
127992                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)];
127993             },
127994             fixIds: [fixId],
127995             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
127996         });
127997         function makeChange(changeTracker, sourceFile, pos) {
127998             var token = ts.getTokenAtPosition(sourceFile, pos);
127999             var decorator = ts.findAncestor(token, ts.isDecorator);
128000             ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator.");
128001             var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
128002             changeTracker.replaceNode(sourceFile, decorator.expression, replacement);
128003         }
128004     })(codefix = ts.codefix || (ts.codefix = {}));
128005 })(ts || (ts = {}));
128006 /* @internal */
128007 var ts;
128008 (function (ts) {
128009     var codefix;
128010     (function (codefix) {
128011         var fixId = "addNameToNamelessParameter";
128012         var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
128013         codefix.registerCodeFix({
128014             errorCodes: errorCodes,
128015             getCodeActions: function (context) {
128016                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
128017                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)];
128018             },
128019             fixIds: [fixId],
128020             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
128021         });
128022         function makeChange(changeTracker, sourceFile, pos) {
128023             var token = ts.getTokenAtPosition(sourceFile, pos);
128024             if (!ts.isIdentifier(token)) {
128025                 return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.Debug.formatSyntaxKind(token.kind));
128026             }
128027             var param = token.parent;
128028             if (!ts.isParameter(param)) {
128029                 return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.Debug.formatSyntaxKind(token.kind));
128030             }
128031             var i = param.parent.parameters.indexOf(param);
128032             ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
128033             ts.Debug.assert(i > -1, "Parameter not found in parent parameter list.");
128034             var replacement = ts.createParameter(
128035             /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer);
128036             changeTracker.replaceNode(sourceFile, token, replacement);
128037         }
128038     })(codefix = ts.codefix || (ts.codefix = {}));
128039 })(ts || (ts = {}));
128040 /* @internal */
128041 var ts;
128042 (function (ts) {
128043     var codefix;
128044     (function (codefix) {
128045         var fixId = "annotateWithTypeFromJSDoc";
128046         var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
128047         codefix.registerCodeFix({
128048             errorCodes: errorCodes,
128049             getCodeActions: function (context) {
128050                 var decl = getDeclaration(context.sourceFile, context.span.start);
128051                 if (!decl)
128052                     return;
128053                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); });
128054                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)];
128055             },
128056             fixIds: [fixId],
128057             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
128058                 var decl = getDeclaration(diag.file, diag.start);
128059                 if (decl)
128060                     doChange(changes, diag.file, decl);
128061             }); },
128062         });
128063         function getDeclaration(file, pos) {
128064             var name = ts.getTokenAtPosition(file, pos);
128065             // For an arrow function with no name, 'name' lands on the first parameter.
128066             return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
128067         }
128068         function parameterShouldGetTypeFromJSDoc(node) {
128069             return isDeclarationWithType(node) && hasUsableJSDoc(node);
128070         }
128071         codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc;
128072         function hasUsableJSDoc(decl) {
128073             return ts.isFunctionLikeDeclaration(decl)
128074                 ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl))
128075                 : !decl.type && !!ts.getJSDocType(decl);
128076         }
128077         function doChange(changes, sourceFile, decl) {
128078             if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
128079                 if (!decl.typeParameters) {
128080                     var typeParameters = ts.getJSDocTypeParameterDeclarations(decl);
128081                     if (typeParameters.length)
128082                         changes.insertTypeParameters(sourceFile, decl, typeParameters);
128083                 }
128084                 var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile);
128085                 if (needParens)
128086                     changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */));
128087                 for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) {
128088                     var param = _a[_i];
128089                     if (!param.type) {
128090                         var paramType = ts.getJSDocType(param);
128091                         if (paramType)
128092                             changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType));
128093                     }
128094                 }
128095                 if (needParens)
128096                     changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */));
128097                 if (!decl.type) {
128098                     var returnType = ts.getJSDocReturnType(decl);
128099                     if (returnType)
128100                         changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType));
128101                 }
128102             }
128103             else {
128104                 var jsdocType = ts.Debug.checkDefined(ts.getJSDocType(decl), "A JSDocType for this declaration should exist"); // If not defined, shouldn't have been an error to fix
128105                 ts.Debug.assert(!decl.type, "The JSDocType decl should have a type"); // If defined, shouldn't have been an error to fix.
128106                 changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType));
128107             }
128108         }
128109         function isDeclarationWithType(node) {
128110             return ts.isFunctionLikeDeclaration(node) ||
128111                 node.kind === 242 /* VariableDeclaration */ ||
128112                 node.kind === 158 /* PropertySignature */ ||
128113                 node.kind === 159 /* PropertyDeclaration */;
128114         }
128115         function transformJSDocType(node) {
128116             switch (node.kind) {
128117                 case 295 /* JSDocAllType */:
128118                 case 296 /* JSDocUnknownType */:
128119                     return ts.createTypeReferenceNode("any", ts.emptyArray);
128120                 case 299 /* JSDocOptionalType */:
128121                     return transformJSDocOptionalType(node);
128122                 case 298 /* JSDocNonNullableType */:
128123                     return transformJSDocType(node.type);
128124                 case 297 /* JSDocNullableType */:
128125                     return transformJSDocNullableType(node);
128126                 case 301 /* JSDocVariadicType */:
128127                     return transformJSDocVariadicType(node);
128128                 case 300 /* JSDocFunctionType */:
128129                     return transformJSDocFunctionType(node);
128130                 case 169 /* TypeReference */:
128131                     return transformJSDocTypeReference(node);
128132                 default:
128133                     var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217
128134                     ts.setEmitFlags(visited, 1 /* SingleLine */);
128135                     return visited;
128136             }
128137         }
128138         function transformJSDocOptionalType(node) {
128139             return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
128140         }
128141         function transformJSDocNullableType(node) {
128142             return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
128143         }
128144         function transformJSDocVariadicType(node) {
128145             return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
128146         }
128147         function transformJSDocFunctionType(node) {
128148             return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type);
128149         }
128150         function transformJSDocParameter(node) {
128151             var index = node.parent.parameters.indexOf(node);
128152             var isRest = node.type.kind === 301 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
128153             var name = node.name || (isRest ? "rest" : "arg" + index);
128154             var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
128155             return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
128156         }
128157         function transformJSDocTypeReference(node) {
128158             var name = node.typeName;
128159             var args = node.typeArguments;
128160             if (ts.isIdentifier(node.typeName)) {
128161                 if (ts.isJSDocIndexSignature(node)) {
128162                     return transformJSDocIndexSignature(node);
128163                 }
128164                 var text = node.typeName.text;
128165                 switch (node.typeName.text) {
128166                     case "String":
128167                     case "Boolean":
128168                     case "Object":
128169                     case "Number":
128170                         text = text.toLowerCase();
128171                         break;
128172                     case "array":
128173                     case "date":
128174                     case "promise":
128175                         text = text[0].toUpperCase() + text.slice(1);
128176                         break;
128177                 }
128178                 name = ts.createIdentifier(text);
128179                 if ((text === "Array" || text === "Promise") && !node.typeArguments) {
128180                     args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
128181                 }
128182                 else {
128183                     args = ts.visitNodes(node.typeArguments, transformJSDocType);
128184                 }
128185             }
128186             return ts.createTypeReferenceNode(name, args);
128187         }
128188         function transformJSDocIndexSignature(node) {
128189             var index = ts.createParameter(
128190             /*decorators*/ undefined, 
128191             /*modifiers*/ undefined, 
128192             /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 140 /* NumberKeyword */ ? "n" : "s", 
128193             /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 140 /* NumberKeyword */ ? "number" : "string", []), 
128194             /*initializer*/ undefined);
128195             var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
128196             ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
128197             return indexSignature;
128198         }
128199     })(codefix = ts.codefix || (ts.codefix = {}));
128200 })(ts || (ts = {}));
128201 /* @internal */
128202 var ts;
128203 (function (ts) {
128204     var codefix;
128205     (function (codefix) {
128206         var fixId = "convertFunctionToEs6Class";
128207         var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
128208         codefix.registerCodeFix({
128209             errorCodes: errorCodes,
128210             getCodeActions: function (context) {
128211                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
128212                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)];
128213             },
128214             fixIds: [fixId],
128215             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
128216         });
128217         function doChange(changes, sourceFile, position, checker) {
128218             var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position));
128219             if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
128220                 // Bad input
128221                 return undefined;
128222             }
128223             var ctorDeclaration = ctorSymbol.valueDeclaration;
128224             var precedingNode;
128225             var newClassDeclaration;
128226             switch (ctorDeclaration.kind) {
128227                 case 244 /* FunctionDeclaration */:
128228                     precedingNode = ctorDeclaration;
128229                     changes.delete(sourceFile, ctorDeclaration);
128230                     newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
128231                     break;
128232                 case 242 /* VariableDeclaration */:
128233                     precedingNode = ctorDeclaration.parent.parent;
128234                     newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
128235                     if (ctorDeclaration.parent.declarations.length === 1) {
128236                         ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
128237                         changes.delete(sourceFile, precedingNode);
128238                     }
128239                     else {
128240                         changes.delete(sourceFile, ctorDeclaration);
128241                     }
128242                     break;
128243             }
128244             if (!newClassDeclaration) {
128245                 return undefined;
128246             }
128247             // Deleting a declaration only deletes JSDoc style comments, so only copy those to the new node.
128248             if (ts.hasJSDocNodes(ctorDeclaration)) {
128249                 ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
128250             }
128251             // Because the preceding node could be touched, we need to insert nodes before delete nodes.
128252             changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
128253             function createClassElementsFromSymbol(symbol) {
128254                 var memberElements = [];
128255                 // all instance members are stored in the "member" array of symbol
128256                 if (symbol.members) {
128257                     symbol.members.forEach(function (member) {
128258                         var memberElement = createClassElement(member, /*modifiers*/ undefined);
128259                         if (memberElement) {
128260                             memberElements.push(memberElement);
128261                         }
128262                     });
128263                 }
128264                 // all static members are stored in the "exports" array of symbol
128265                 if (symbol.exports) {
128266                     symbol.exports.forEach(function (member) {
128267                         var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]);
128268                         if (memberElement) {
128269                             memberElements.push(memberElement);
128270                         }
128271                     });
128272                 }
128273                 return memberElements;
128274                 function shouldConvertDeclaration(_target, source) {
128275                     // Right now the only thing we can convert are function expressions - other values shouldn't get
128276                     // transformed. We can update this once ES public class properties are available.
128277                     return ts.isFunctionLike(source);
128278                 }
128279                 function createClassElement(symbol, modifiers) {
128280                     // Right now the only thing we can convert are function expressions, which are marked as methods
128281                     if (!(symbol.flags & 8192 /* Method */)) {
128282                         return;
128283                     }
128284                     var memberDeclaration = symbol.valueDeclaration;
128285                     var assignmentBinaryExpression = memberDeclaration.parent;
128286                     if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
128287                         return;
128288                     }
128289                     // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end
128290                     var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 226 /* ExpressionStatement */
128291                         ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
128292                     changes.delete(sourceFile, nodeToDelete);
128293                     if (!assignmentBinaryExpression.right) {
128294                         return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, 
128295                         /*type*/ undefined, /*initializer*/ undefined);
128296                     }
128297                     switch (assignmentBinaryExpression.right.kind) {
128298                         case 201 /* FunctionExpression */: {
128299                             var functionExpression = assignmentBinaryExpression.right;
128300                             var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */));
128301                             var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, 
128302                             /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
128303                             ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
128304                             return method;
128305                         }
128306                         case 202 /* ArrowFunction */: {
128307                             var arrowFunction = assignmentBinaryExpression.right;
128308                             var arrowFunctionBody = arrowFunction.body;
128309                             var bodyBlock = void 0;
128310                             // case 1: () => { return [1,2,3] }
128311                             if (arrowFunctionBody.kind === 223 /* Block */) {
128312                                 bodyBlock = arrowFunctionBody;
128313                             }
128314                             // case 2: () => [1,2,3]
128315                             else {
128316                                 bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
128317                             }
128318                             var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */));
128319                             var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, 
128320                             /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
128321                             ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
128322                             return method;
128323                         }
128324                         default: {
128325                             // Don't try to declare members in JavaScript files
128326                             if (ts.isSourceFileJS(sourceFile)) {
128327                                 return;
128328                             }
128329                             var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, 
128330                             /*type*/ undefined, assignmentBinaryExpression.right);
128331                             ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
128332                             return prop;
128333                         }
128334                     }
128335                 }
128336             }
128337             function createClassFromVariableDeclaration(node) {
128338                 var initializer = node.initializer;
128339                 if (!initializer || initializer.kind !== 201 /* FunctionExpression */) {
128340                     return undefined;
128341                 }
128342                 if (node.name.kind !== 75 /* Identifier */) {
128343                     return undefined;
128344                 }
128345                 var memberElements = createClassElementsFromSymbol(node.symbol);
128346                 if (initializer.body) {
128347                     memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
128348                 }
128349                 var modifiers = getModifierKindFromSource(precedingNode, 89 /* ExportKeyword */);
128350                 var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, 
128351                 /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
128352                 // Don't call copyComments here because we'll already leave them in place
128353                 return cls;
128354             }
128355             function createClassFromFunctionDeclaration(node) {
128356                 var memberElements = createClassElementsFromSymbol(ctorSymbol);
128357                 if (node.body) {
128358                     memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
128359                 }
128360                 var modifiers = getModifierKindFromSource(node, 89 /* ExportKeyword */);
128361                 var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, 
128362                 /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
128363                 // Don't call copyComments here because we'll already leave them in place
128364                 return cls;
128365             }
128366         }
128367         function getModifierKindFromSource(source, kind) {
128368             return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
128369         }
128370     })(codefix = ts.codefix || (ts.codefix = {}));
128371 })(ts || (ts = {}));
128372 /* @internal */
128373 var ts;
128374 (function (ts) {
128375     var codefix;
128376     (function (codefix) {
128377         var fixId = "convertToAsyncFunction";
128378         var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code];
128379         var codeActionSucceeded = true;
128380         codefix.registerCodeFix({
128381             errorCodes: errorCodes,
128382             getCodeActions: function (context) {
128383                 codeActionSucceeded = true;
128384                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); });
128385                 return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : [];
128386             },
128387             fixIds: [fixId],
128388             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); },
128389         });
128390         var SynthBindingNameKind;
128391         (function (SynthBindingNameKind) {
128392             SynthBindingNameKind[SynthBindingNameKind["Identifier"] = 0] = "Identifier";
128393             SynthBindingNameKind[SynthBindingNameKind["BindingPattern"] = 1] = "BindingPattern";
128394         })(SynthBindingNameKind || (SynthBindingNameKind = {}));
128395         function convertToAsyncFunction(changes, sourceFile, position, checker, context) {
128396             // get the function declaration - returns a promise
128397             var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position);
128398             var functionToConvert;
128399             // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name
128400             if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) &&
128401                 tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) {
128402                 functionToConvert = tokenAtPosition.parent.initializer;
128403             }
128404             else {
128405                 functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration);
128406             }
128407             if (!functionToConvert) {
128408                 return;
128409             }
128410             var synthNamesMap = ts.createMap();
128411             var isInJavascript = ts.isInJSFile(functionToConvert);
128412             var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker);
128413             var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context.sourceFile);
128414             var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray;
128415             var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript };
128416             if (!returnStatements.length) {
128417                 return;
128418             }
128419             // add the async keyword
128420             changes.insertLastModifierBefore(sourceFile, 126 /* AsyncKeyword */, functionToConvert);
128421             var _loop_12 = function (returnStatement) {
128422                 ts.forEachChild(returnStatement, function visit(node) {
128423                     if (ts.isCallExpression(node)) {
128424                         var newNodes = transformExpression(node, transformer);
128425                         changes.replaceNodeWithNodes(sourceFile, returnStatement, newNodes);
128426                     }
128427                     else if (!ts.isFunctionLike(node)) {
128428                         ts.forEachChild(node, visit);
128429                     }
128430                 });
128431             };
128432             for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
128433                 var returnStatement = returnStatements_1[_i];
128434                 _loop_12(returnStatement);
128435             }
128436         }
128437         function getReturnStatementsWithPromiseHandlers(body) {
128438             var res = [];
128439             ts.forEachReturnStatement(body, function (ret) {
128440                 if (ts.isReturnStatementWithFixablePromiseHandler(ret))
128441                     res.push(ret);
128442             });
128443             return res;
128444         }
128445         /*
128446             Finds all of the expressions of promise type that should not be saved in a variable during the refactor
128447         */
128448         function getAllPromiseExpressionsToReturn(func, checker) {
128449             if (!func.body) {
128450                 return ts.createMap();
128451             }
128452             var setOfExpressionsToReturn = ts.createMap();
128453             ts.forEachChild(func.body, function visit(node) {
128454                 if (isPromiseReturningCallExpression(node, checker, "then")) {
128455                     setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
128456                     ts.forEach(node.arguments, visit);
128457                 }
128458                 else if (isPromiseReturningCallExpression(node, checker, "catch")) {
128459                     setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
128460                     // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned
128461                     ts.forEachChild(node, visit);
128462                 }
128463                 else if (isPromiseTypedExpression(node, checker)) {
128464                     setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
128465                     // don't recurse here, since we won't refactor any children or arguments of the expression
128466                 }
128467                 else {
128468                     ts.forEachChild(node, visit);
128469                 }
128470             });
128471             return setOfExpressionsToReturn;
128472         }
128473         function isPromiseReturningCallExpression(node, checker, name) {
128474             if (!ts.isCallExpression(node))
128475                 return false;
128476             var isExpressionOfName = ts.hasPropertyAccessExpressionWithName(node, name);
128477             var nodeType = isExpressionOfName && checker.getTypeAtLocation(node);
128478             return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType));
128479         }
128480         function isPromiseTypedExpression(node, checker) {
128481             if (!ts.isExpression(node))
128482                 return false;
128483             return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node));
128484         }
128485         function declaredInFile(symbol, sourceFile) {
128486             return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile;
128487         }
128488         /*
128489             Renaming of identifiers may be neccesary as the refactor changes scopes -
128490             This function collects all existing identifier names and names of identifiers that will be created in the refactor.
128491             It then checks for any collisions and renames them through getSynthesizedDeepClone
128492         */
128493         function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, sourceFile) {
128494             var identsToRenameMap = ts.createMap(); // key is the symbol id
128495             var collidingSymbolMap = ts.createMultiMap();
128496             ts.forEachChild(nodeToRename, function visit(node) {
128497                 if (!ts.isIdentifier(node)) {
128498                     ts.forEachChild(node, visit);
128499                     return;
128500                 }
128501                 var symbol = checker.getSymbolAtLocation(node);
128502                 var isDefinedInFile = symbol && declaredInFile(symbol, sourceFile);
128503                 if (symbol && isDefinedInFile) {
128504                     var type = checker.getTypeAtLocation(node);
128505                     // Note - the choice of the last call signature is arbitrary
128506                     var lastCallSignature = getLastCallSignature(type, checker);
128507                     var symbolIdString = ts.getSymbolId(symbol).toString();
128508                     // If the identifier refers to a function, we want to add the new synthesized variable for the declaration. Example:
128509                     //   fetch('...').then(response => { ... })
128510                     // will eventually become
128511                     //   const response = await fetch('...')
128512                     // so we push an entry for 'response'.
128513                     if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) {
128514                         var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters);
128515                         var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result");
128516                         var synthName = getNewNameIfConflict(ident, collidingSymbolMap);
128517                         synthNamesMap.set(symbolIdString, synthName);
128518                         collidingSymbolMap.add(ident.text, symbol);
128519                     }
128520                     // We only care about identifiers that are parameters, variable declarations, or binding elements
128521                     else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent) || ts.isBindingElement(node.parent))) {
128522                         var originalName = node.text;
128523                         var collidingSymbols = collidingSymbolMap.get(originalName);
128524                         // if the identifier name conflicts with a different identifier that we've already seen
128525                         if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) {
128526                             var newName = getNewNameIfConflict(node, collidingSymbolMap);
128527                             identsToRenameMap.set(symbolIdString, newName.identifier);
128528                             synthNamesMap.set(symbolIdString, newName);
128529                             collidingSymbolMap.add(originalName, symbol);
128530                         }
128531                         else {
128532                             var identifier = ts.getSynthesizedDeepClone(node);
128533                             synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier));
128534                             collidingSymbolMap.add(originalName, symbol);
128535                         }
128536                     }
128537                 }
128538             });
128539             return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker);
128540         }
128541         function getNewNameIfConflict(name, originalNames) {
128542             var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length;
128543             var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName);
128544             return createSynthIdentifier(identifier);
128545         }
128546         function silentFail() {
128547             codeActionSucceeded = false;
128548             return ts.emptyArray;
128549         }
128550         // dispatch function to recursively build the refactoring
128551         // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts
128552         function transformExpression(node, transformer, prevArgName) {
128553             if (isPromiseReturningCallExpression(node, transformer.checker, "then")) {
128554                 if (node.arguments.length === 0)
128555                     return silentFail();
128556                 return transformThen(node, transformer, prevArgName);
128557             }
128558             if (isPromiseReturningCallExpression(node, transformer.checker, "catch")) {
128559                 if (node.arguments.length === 0)
128560                     return silentFail();
128561                 return transformCatch(node, transformer, prevArgName);
128562             }
128563             if (ts.isPropertyAccessExpression(node)) {
128564                 return transformExpression(node.expression, transformer, prevArgName);
128565             }
128566             var nodeType = transformer.checker.getTypeAtLocation(node);
128567             if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) {
128568                 ts.Debug.assertNode(node.original.parent, ts.isPropertyAccessExpression);
128569                 return transformPromiseExpressionOfPropertyAccess(node, transformer, prevArgName);
128570             }
128571             return silentFail();
128572         }
128573         function transformCatch(node, transformer, prevArgName) {
128574             var func = node.arguments[0];
128575             var argName = getArgBindingName(func, transformer);
128576             var possibleNameForVarDecl;
128577             /*
128578                 If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block)
128579                 To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap
128580                 We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step
128581             */
128582             if (prevArgName && !shouldReturn(node, transformer)) {
128583                 if (isSynthIdentifier(prevArgName)) {
128584                     possibleNameForVarDecl = prevArgName;
128585                     transformer.synthNamesMap.forEach(function (val, key) {
128586                         if (val.identifier.text === prevArgName.identifier.text) {
128587                             var newSynthName = createUniqueSynthName(prevArgName);
128588                             transformer.synthNamesMap.set(key, newSynthName);
128589                         }
128590                     });
128591                 }
128592                 else {
128593                     possibleNameForVarDecl = createSynthIdentifier(ts.createOptimisticUniqueName("result"), prevArgName.types);
128594                 }
128595                 // We are about to write a 'let' variable declaration, but `transformExpression` for both
128596                 // the try block and catch block will assign to this name. Setting this flag indicates
128597                 // that future assignments should be written as `name = value` instead of `const name = value`.
128598                 possibleNameForVarDecl.hasBeenDeclared = true;
128599             }
128600             var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, possibleNameForVarDecl));
128601             var transformationBody = getTransformationBody(func, possibleNameForVarDecl, argName, node, transformer);
128602             var catchArg = argName ? isSynthIdentifier(argName) ? argName.identifier.text : argName.bindingPattern : "e";
128603             var catchVariableDeclaration = ts.createVariableDeclaration(catchArg);
128604             var catchClause = ts.createCatchClause(catchVariableDeclaration, ts.createBlock(transformationBody));
128605             /*
128606                 In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block)
128607             */
128608             var varDeclList;
128609             var varDeclIdentifier;
128610             if (possibleNameForVarDecl && !shouldReturn(node, transformer)) {
128611                 varDeclIdentifier = ts.getSynthesizedDeepClone(possibleNameForVarDecl.identifier);
128612                 var typeArray = possibleNameForVarDecl.types;
128613                 var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */);
128614                 var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined);
128615                 var varDecl = [ts.createVariableDeclaration(varDeclIdentifier, unionTypeNode)];
128616                 varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */));
128617             }
128618             var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined);
128619             var destructuredResult = prevArgName && varDeclIdentifier && isSynthBindingPattern(prevArgName)
128620                 && ts.createVariableStatement(/* modifiers */ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepCloneWithRenames(prevArgName.bindingPattern), /* type */ undefined, varDeclIdentifier)], 2 /* Const */));
128621             return ts.compact([varDeclList, tryStatement, destructuredResult]);
128622         }
128623         function createUniqueSynthName(prevArgName) {
128624             var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text);
128625             return createSynthIdentifier(renamedPrevArg);
128626         }
128627         function transformThen(node, transformer, prevArgName) {
128628             var _a = node.arguments, onFulfilled = _a[0], onRejected = _a[1];
128629             var onFulfilledArgumentName = getArgBindingName(onFulfilled, transformer);
128630             var transformationBody = getTransformationBody(onFulfilled, prevArgName, onFulfilledArgumentName, node, transformer);
128631             if (onRejected) {
128632                 var onRejectedArgumentName = getArgBindingName(onRejected, transformer);
128633                 var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, onFulfilledArgumentName).concat(transformationBody));
128634                 var transformationBody2 = getTransformationBody(onRejected, prevArgName, onRejectedArgumentName, node, transformer);
128635                 var catchArg = onRejectedArgumentName ? isSynthIdentifier(onRejectedArgumentName) ? onRejectedArgumentName.identifier.text : onRejectedArgumentName.bindingPattern : "e";
128636                 var catchVariableDeclaration = ts.createVariableDeclaration(catchArg);
128637                 var catchClause = ts.createCatchClause(catchVariableDeclaration, ts.createBlock(transformationBody2));
128638                 return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)];
128639             }
128640             return transformExpression(node.expression, transformer, onFulfilledArgumentName).concat(transformationBody);
128641         }
128642         /**
128643          * Transforms the 'x' part of `x.then(...)`, or the 'y()' part of `y().catch(...)`, where 'x' and 'y()' are Promises.
128644          */
128645         function transformPromiseExpressionOfPropertyAccess(node, transformer, prevArgName) {
128646             if (shouldReturn(node, transformer)) {
128647                 return [ts.createReturn(ts.getSynthesizedDeepClone(node))];
128648             }
128649             return createVariableOrAssignmentOrExpressionStatement(prevArgName, ts.createAwait(node), /*typeAnnotation*/ undefined);
128650         }
128651         function createVariableOrAssignmentOrExpressionStatement(variableName, rightHandSide, typeAnnotation) {
128652             if (!variableName || isEmptyBindingName(variableName)) {
128653                 // if there's no argName to assign to, there still might be side effects
128654                 return [ts.createExpressionStatement(rightHandSide)];
128655             }
128656             if (isSynthIdentifier(variableName) && variableName.hasBeenDeclared) {
128657                 // if the variable has already been declared, we don't need "let" or "const"
128658                 return [ts.createExpressionStatement(ts.createAssignment(ts.getSynthesizedDeepClone(variableName.identifier), rightHandSide))];
128659             }
128660             return [
128661                 ts.createVariableStatement(
128662                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
128663                     ts.createVariableDeclaration(ts.getSynthesizedDeepClone(getNode(variableName)), typeAnnotation, rightHandSide)
128664                 ], 2 /* Const */))
128665             ];
128666         }
128667         function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) {
128668             if (typeAnnotation && expressionToReturn) {
128669                 var name = ts.createOptimisticUniqueName("result");
128670                 return __spreadArrays(createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), [
128671                     ts.createReturn(name)
128672                 ]);
128673             }
128674             return [ts.createReturn(expressionToReturn)];
128675         }
128676         // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts
128677         function getTransformationBody(func, prevArgName, argName, parent, transformer) {
128678             var _a, _b, _c, _d;
128679             switch (func.kind) {
128680                 case 100 /* NullKeyword */:
128681                     // do not produce a transformed statement for a null argument
128682                     break;
128683                 case 75 /* Identifier */: // identifier includes undefined
128684                     if (!argName) {
128685                         // undefined was argument passed to promise handler
128686                         break;
128687                     }
128688                     var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, isSynthIdentifier(argName) ? [argName.identifier] : []);
128689                     if (shouldReturn(parent, transformer)) {
128690                         return maybeAnnotateAndReturn(synthCall, (_a = parent.typeArguments) === null || _a === void 0 ? void 0 : _a[0]);
128691                     }
128692                     var type = transformer.checker.getTypeAtLocation(func);
128693                     var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */);
128694                     if (!callSignatures.length) {
128695                         // if identifier in handler has no call signatures, it's invalid
128696                         return silentFail();
128697                     }
128698                     var returnType = callSignatures[0].getReturnType();
128699                     var varDeclOrAssignment = createVariableOrAssignmentOrExpressionStatement(prevArgName, ts.createAwait(synthCall), (_b = parent.typeArguments) === null || _b === void 0 ? void 0 : _b[0]);
128700                     if (prevArgName) {
128701                         prevArgName.types.push(returnType);
128702                     }
128703                     return varDeclOrAssignment;
128704                 case 201 /* FunctionExpression */:
128705                 case 202 /* ArrowFunction */: {
128706                     var funcBody = func.body;
128707                     // Arrow functions with block bodies { } will enter this control flow
128708                     if (ts.isBlock(funcBody)) {
128709                         var refactoredStmts = [];
128710                         var seenReturnStatement = false;
128711                         for (var _i = 0, _e = funcBody.statements; _i < _e.length; _i++) {
128712                             var statement = _e[_i];
128713                             if (ts.isReturnStatement(statement)) {
128714                                 seenReturnStatement = true;
128715                                 if (ts.isReturnStatementWithFixablePromiseHandler(statement)) {
128716                                     refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName));
128717                                 }
128718                                 else {
128719                                     refactoredStmts.push.apply(refactoredStmts, maybeAnnotateAndReturn(statement.expression, (_c = parent.typeArguments) === null || _c === void 0 ? void 0 : _c[0]));
128720                                 }
128721                             }
128722                             else {
128723                                 refactoredStmts.push(statement);
128724                             }
128725                         }
128726                         return shouldReturn(parent, transformer)
128727                             ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); })
128728                             : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement);
128729                     }
128730                     else {
128731                         var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray;
128732                         var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName);
128733                         if (innerCbBody.length > 0) {
128734                             return innerCbBody;
128735                         }
128736                         var type_1 = transformer.checker.getTypeAtLocation(func);
128737                         var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
128738                         var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
128739                         var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
128740                         if (!shouldReturn(parent, transformer)) {
128741                             var transformedStatement = createVariableOrAssignmentOrExpressionStatement(prevArgName, possiblyAwaitedRightHandSide, /*typeAnnotation*/ undefined);
128742                             if (prevArgName) {
128743                                 prevArgName.types.push(returnType_1);
128744                             }
128745                             return transformedStatement;
128746                         }
128747                         else {
128748                             return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, (_d = parent.typeArguments) === null || _d === void 0 ? void 0 : _d[0]);
128749                         }
128750                     }
128751                 }
128752                 default:
128753                     // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code.
128754                     return silentFail();
128755             }
128756             return ts.emptyArray;
128757         }
128758         function getLastCallSignature(type, checker) {
128759             var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */);
128760             return ts.lastOrUndefined(callSignatures);
128761         }
128762         function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) {
128763             var ret = [];
128764             for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) {
128765                 var stmt = stmts_1[_i];
128766                 if (ts.isReturnStatement(stmt)) {
128767                     if (stmt.expression) {
128768                         var possiblyAwaitedExpression = isPromiseTypedExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression;
128769                         if (prevArgName === undefined) {
128770                             ret.push(ts.createExpressionStatement(possiblyAwaitedExpression));
128771                         }
128772                         else {
128773                             ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, possiblyAwaitedExpression)], 2 /* Const */))));
128774                         }
128775                     }
128776                 }
128777                 else {
128778                     ret.push(ts.getSynthesizedDeepClone(stmt));
128779                 }
128780             }
128781             // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables
128782             if (!seenReturnStatement && prevArgName !== undefined) {
128783                 ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, ts.createIdentifier("undefined"))], 2 /* Const */))));
128784             }
128785             return ret;
128786         }
128787         function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) {
128788             var innerCbBody = [];
128789             for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) {
128790                 var stmt = innerRetStmts_1[_i];
128791                 ts.forEachChild(stmt, function visit(node) {
128792                     if (ts.isCallExpression(node)) {
128793                         var temp = transformExpression(node, transformer, prevArgName);
128794                         innerCbBody = innerCbBody.concat(temp);
128795                         if (innerCbBody.length > 0) {
128796                             return;
128797                         }
128798                     }
128799                     else if (!ts.isFunctionLike(node)) {
128800                         ts.forEachChild(node, visit);
128801                     }
128802                 });
128803             }
128804             return innerCbBody;
128805         }
128806         function getArgBindingName(funcNode, transformer) {
128807             var types = [];
128808             var name;
128809             if (ts.isFunctionLikeDeclaration(funcNode)) {
128810                 if (funcNode.parameters.length > 0) {
128811                     var param = funcNode.parameters[0].name;
128812                     name = getMappedBindingNameOrDefault(param);
128813                 }
128814             }
128815             else if (ts.isIdentifier(funcNode)) {
128816                 name = getMapEntryOrDefault(funcNode);
128817             }
128818             // return undefined argName when arg is null or undefined
128819             // eslint-disable-next-line no-in-operator
128820             if (!name || "identifier" in name && name.identifier.text === "undefined") {
128821                 return undefined;
128822             }
128823             return name;
128824             function getMappedBindingNameOrDefault(bindingName) {
128825                 if (ts.isIdentifier(bindingName))
128826                     return getMapEntryOrDefault(bindingName);
128827                 var elements = ts.flatMap(bindingName.elements, function (element) {
128828                     if (ts.isOmittedExpression(element))
128829                         return [];
128830                     return [getMappedBindingNameOrDefault(element.name)];
128831                 });
128832                 return createSynthBindingPattern(bindingName, elements);
128833             }
128834             function getMapEntryOrDefault(identifier) {
128835                 var originalNode = getOriginalNode(identifier);
128836                 var symbol = getSymbol(originalNode);
128837                 if (!symbol) {
128838                     return createSynthIdentifier(identifier, types);
128839                 }
128840                 var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString());
128841                 return mapEntry || createSynthIdentifier(identifier, types);
128842             }
128843             function getSymbol(node) {
128844                 return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node);
128845             }
128846             function getOriginalNode(node) {
128847                 return node.original ? node.original : node;
128848             }
128849         }
128850         function isEmptyBindingName(bindingName) {
128851             if (!bindingName) {
128852                 return true;
128853             }
128854             if (isSynthIdentifier(bindingName)) {
128855                 return !bindingName.identifier.text;
128856             }
128857             return ts.every(bindingName.elements, isEmptyBindingName);
128858         }
128859         function getNode(bindingName) {
128860             return isSynthIdentifier(bindingName) ? bindingName.identifier : bindingName.bindingPattern;
128861         }
128862         function createSynthIdentifier(identifier, types) {
128863             if (types === void 0) { types = []; }
128864             return { kind: 0 /* Identifier */, identifier: identifier, types: types, hasBeenDeclared: false };
128865         }
128866         function createSynthBindingPattern(bindingPattern, elements, types) {
128867             if (elements === void 0) { elements = ts.emptyArray; }
128868             if (types === void 0) { types = []; }
128869             return { kind: 1 /* BindingPattern */, bindingPattern: bindingPattern, elements: elements, types: types };
128870         }
128871         function isSynthIdentifier(bindingName) {
128872             return bindingName.kind === 0 /* Identifier */;
128873         }
128874         function isSynthBindingPattern(bindingName) {
128875             return bindingName.kind === 1 /* BindingPattern */;
128876         }
128877         function shouldReturn(expression, transformer) {
128878             return !!expression.original && transformer.setOfExpressionsToReturn.has(ts.getNodeId(expression.original).toString());
128879         }
128880     })(codefix = ts.codefix || (ts.codefix = {}));
128881 })(ts || (ts = {}));
128882 /* @internal */
128883 var ts;
128884 (function (ts) {
128885     var codefix;
128886     (function (codefix) {
128887         codefix.registerCodeFix({
128888             errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],
128889             getCodeActions: function (context) {
128890                 var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences;
128891                 var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
128892                     var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences));
128893                     if (moduleExportsChangedToDefault) {
128894                         for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
128895                             var importingFile = _a[_i];
128896                             fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences));
128897                         }
128898                     }
128899                 });
128900                 // No support for fix-all since this applies to the whole file at once anyway.
128901                 return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)];
128902             },
128903         });
128904         function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) {
128905             for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
128906                 var moduleSpecifier = _a[_i];
128907                 var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
128908                 if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
128909                     continue;
128910                 }
128911                 var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
128912                 switch (importNode.kind) {
128913                     case 253 /* ImportEqualsDeclaration */:
128914                         changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference));
128915                         break;
128916                     case 196 /* CallExpression */:
128917                         if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
128918                             changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default"));
128919                         }
128920                         break;
128921                 }
128922             }
128923         }
128924         /** @returns Whether we converted a `module.exports =` to a default export. */
128925         function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) {
128926             var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
128927             var exports = collectExportRenames(sourceFile, checker, identifiers);
128928             convertExportsAccesses(sourceFile, exports, changes);
128929             var moduleExportsChangedToDefault = false;
128930             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
128931                 var statement = _a[_i];
128932                 var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference);
128933                 moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
128934             }
128935             return moduleExportsChangedToDefault;
128936         }
128937         function collectExportRenames(sourceFile, checker, identifiers) {
128938             var res = ts.createMap();
128939             forEachExportReference(sourceFile, function (node) {
128940                 var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
128941                 if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
128942                     || checker.resolveName(text, node, 111551 /* Value */, /*excludeGlobals*/ true))) {
128943                     // Unconditionally add an underscore in case `text` is a keyword.
128944                     res.set(text, makeUniqueName("_" + text, identifiers));
128945                 }
128946             });
128947             return res;
128948         }
128949         function convertExportsAccesses(sourceFile, exports, changes) {
128950             forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
128951                 if (isAssignmentLhs) {
128952                     return;
128953                 }
128954                 var text = node.name.text;
128955                 changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
128956             });
128957         }
128958         function forEachExportReference(sourceFile, cb) {
128959             sourceFile.forEachChild(function recur(node) {
128960                 if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && ts.isIdentifier(node.name)) {
128961                     var parent = node.parent;
128962                     cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 62 /* EqualsToken */);
128963                 }
128964                 node.forEachChild(recur);
128965             });
128966         }
128967         function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) {
128968             switch (statement.kind) {
128969                 case 225 /* VariableStatement */:
128970                     convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
128971                     return false;
128972                 case 226 /* ExpressionStatement */: {
128973                     var expression = statement.expression;
128974                     switch (expression.kind) {
128975                         case 196 /* CallExpression */: {
128976                             if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
128977                                 // For side-effecting require() call, just make a side-effecting import.
128978                                 changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference));
128979                             }
128980                             return false;
128981                         }
128982                         case 209 /* BinaryExpression */: {
128983                             var operatorToken = expression.operatorToken;
128984                             return operatorToken.kind === 62 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports);
128985                         }
128986                     }
128987                 }
128988                 // falls through
128989                 default:
128990                     return false;
128991             }
128992         }
128993         function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) {
128994             var declarationList = statement.declarationList;
128995             var foundImport = false;
128996             var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
128997                 var name = decl.name, initializer = decl.initializer;
128998                 if (initializer) {
128999                     if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
129000                         // `const alias = module.exports;` can be removed.
129001                         foundImport = true;
129002                         return [];
129003                     }
129004                     else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
129005                         foundImport = true;
129006                         return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference);
129007                     }
129008                     else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) {
129009                         foundImport = true;
129010                         return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference);
129011                     }
129012                 }
129013                 // Move it out to its own variable statement. (This will not be used if `!foundImport`)
129014                 return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
129015             });
129016             if (foundImport) {
129017                 // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
129018                 changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
129019             }
129020         }
129021         /** Converts `const name = require("moduleSpecifier").propertyName` */
129022         function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) {
129023             switch (name.kind) {
129024                 case 189 /* ObjectBindingPattern */:
129025                 case 190 /* ArrayBindingPattern */: {
129026                     // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
129027                     var tmp = makeUniqueName(propertyName, identifiers);
129028                     return [
129029                         makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference),
129030                         makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
129031                     ];
129032                 }
129033                 case 75 /* Identifier */:
129034                     // `const a = require("b").c` --> `import { c as a } from "./b";
129035                     return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)];
129036                 default:
129037                     return ts.Debug.assertNever(name, "Convert to ES6 module got invalid syntax form " + name.kind);
129038             }
129039         }
129040         function convertAssignment(sourceFile, checker, assignment, changes, exports) {
129041             var left = assignment.left, right = assignment.right;
129042             if (!ts.isPropertyAccessExpression(left)) {
129043                 return false;
129044             }
129045             if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
129046                 if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
129047                     // `const alias = module.exports;` or `module.exports = alias;` can be removed.
129048                     changes.delete(sourceFile, assignment.parent);
129049                 }
129050                 else {
129051                     var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
129052                         : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
129053                             : undefined;
129054                     if (replacement) {
129055                         changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
129056                         return replacement[1];
129057                     }
129058                     else {
129059                         changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default");
129060                         return true;
129061                     }
129062                 }
129063             }
129064             else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
129065                 convertNamedExport(sourceFile, assignment, changes, exports);
129066             }
129067             return false;
129068         }
129069         /**
129070          * Convert `module.exports = { ... }` to individual exports..
129071          * We can't always do this if the module has interesting members -- then it will be a default export instead.
129072          */
129073         function tryChangeModuleExportsObject(object) {
129074             var statements = ts.mapAllOrFail(object.properties, function (prop) {
129075                 switch (prop.kind) {
129076                     case 163 /* GetAccessor */:
129077                     case 164 /* SetAccessor */:
129078                     // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
129079                     // falls through
129080                     case 282 /* ShorthandPropertyAssignment */:
129081                     case 283 /* SpreadAssignment */:
129082                         return undefined;
129083                     case 281 /* PropertyAssignment */:
129084                         return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer);
129085                     case 161 /* MethodDeclaration */:
129086                         return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(89 /* ExportKeyword */)], prop);
129087                     default:
129088                         ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind " + prop.kind);
129089                 }
129090             });
129091             return statements && [statements, false];
129092         }
129093         function convertNamedExport(sourceFile, assignment, changes, exports) {
129094             // If "originalKeywordKind" was set, this is e.g. `exports.
129095             var text = assignment.left.name.text;
129096             var rename = exports.get(text);
129097             if (rename !== undefined) {
129098                 /*
129099                 const _class = 0;
129100                 export { _class as class };
129101                 */
129102                 var newNodes = [
129103                     makeConst(/*modifiers*/ undefined, rename, assignment.right),
129104                     makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
129105                 ];
129106                 changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
129107             }
129108             else {
129109                 convertExportsPropertyAssignment(assignment, sourceFile, changes);
129110             }
129111         }
129112         function convertReExportAll(reExported, checker) {
129113             // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
129114             var moduleSpecifier = reExported.text;
129115             var moduleSymbol = checker.getSymbolAtLocation(reExported);
129116             var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
129117             return exports.has("export=") ? [[reExportDefault(moduleSpecifier)], true] :
129118                 !exports.has("default") ? [[reExportStar(moduleSpecifier)], false] :
129119                     // If there's some non-default export, must include both `export *` and `export default`.
129120                     exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
129121         }
129122         function reExportStar(moduleSpecifier) {
129123             return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
129124         }
129125         function reExportDefault(moduleSpecifier) {
129126             return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
129127         }
129128         function convertExportsPropertyAssignment(_a, sourceFile, changes) {
129129             var left = _a.left, right = _a.right, parent = _a.parent;
129130             var name = left.name.text;
129131             if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) {
129132                 // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`.
129133                 changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(89 /* ExportKeyword */), { suffix: " " });
129134                 if (!right.name)
129135                     changes.insertName(sourceFile, right, name);
129136                 var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile);
129137                 if (semi)
129138                     changes.delete(sourceFile, semi);
129139             }
129140             else {
129141                 // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const `
129142                 changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(89 /* ExportKeyword */), ts.createToken(81 /* ConstKeyword */)], { joiner: " ", suffix: " " });
129143             }
129144         }
129145         // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node.
129146         function convertExportsDotXEquals_replaceNode(name, exported) {
129147             var modifiers = [ts.createToken(89 /* ExportKeyword */)];
129148             switch (exported.kind) {
129149                 case 201 /* FunctionExpression */: {
129150                     var expressionName = exported.name;
129151                     if (expressionName && expressionName.text !== name) {
129152                         // `exports.f = function g() {}` -> `export const f = function g() {}`
129153                         return exportConst();
129154                     }
129155                 }
129156                 // falls through
129157                 case 202 /* ArrowFunction */:
129158                     // `exports.f = function() {}` --> `export function f() {}`
129159                     return functionExpressionToDeclaration(name, modifiers, exported);
129160                 case 214 /* ClassExpression */:
129161                     // `exports.C = class {}` --> `export class C {}`
129162                     return classExpressionToDeclaration(name, modifiers, exported);
129163                 default:
129164                     return exportConst();
129165             }
129166             function exportConst() {
129167                 // `exports.x = 0;` --> `export const x = 0;`
129168                 return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217
129169             }
129170         }
129171         /**
129172          * Converts `const <<name>> = require("x");`.
129173          * Returns nodes that will replace the variable declaration for the commonjs import.
129174          * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
129175          */
129176         function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) {
129177             switch (name.kind) {
129178                 case 189 /* ObjectBindingPattern */: {
129179                     var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) {
129180                         return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name)
129181                             ? undefined
129182                             // (TODO: GH#18217)
129183                             // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
129184                             : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
129185                     });
129186                     if (importSpecifiers) {
129187                         return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)];
129188                     }
129189                 }
129190                 // falls through -- object destructuring has an interesting pattern and must be a variable declaration
129191                 case 190 /* ArrayBindingPattern */: {
129192                     /*
129193                     import x from "x";
129194                     const [a, b, c] = x;
129195                     */
129196                     var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
129197                     return [
129198                         ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference),
129199                         makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
129200                     ];
129201                 }
129202                 case 75 /* Identifier */:
129203                     return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference);
129204                 default:
129205                     return ts.Debug.assertNever(name, "Convert to ES6 module got invalid name kind " + name.kind);
129206             }
129207         }
129208         /**
129209          * Convert `import x = require("x").`
129210          * Also converts uses like `x.y()` to `y()` and uses a named import.
129211          */
129212         function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) {
129213             var nameSymbol = checker.getSymbolAtLocation(name);
129214             // Maps from module property name to name actually used. (The same if there isn't shadowing.)
129215             var namedBindingsNames = ts.createMap();
129216             // True if there is some non-property use like `x()` or `f(x)`.
129217             var needDefaultImport = false;
129218             for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
129219                 var use = _a[_i];
129220                 if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
129221                     // This was a use of a different symbol with the same name, due to shadowing. Ignore.
129222                     continue;
129223                 }
129224                 var parent = use.parent;
129225                 if (ts.isPropertyAccessExpression(parent)) {
129226                     var expression = parent.expression, propertyName = parent.name.text;
129227                     ts.Debug.assert(expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers`
129228                     var idName = namedBindingsNames.get(propertyName);
129229                     if (idName === undefined) {
129230                         idName = makeUniqueName(propertyName, identifiers);
129231                         namedBindingsNames.set(propertyName, idName);
129232                     }
129233                     changes.replaceNode(file, parent, ts.createIdentifier(idName));
129234                 }
129235                 else {
129236                     needDefaultImport = true;
129237                 }
129238             }
129239             var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
129240                 var propertyName = _a[0], idName = _a[1];
129241                 return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
129242             }));
129243             if (!namedBindings) {
129244                 // If it was unused, ensure that we at least import *something*.
129245                 needDefaultImport = true;
129246             }
129247             return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)];
129248         }
129249         // Identifiers helpers
129250         function makeUniqueName(name, identifiers) {
129251             while (identifiers.original.has(name) || identifiers.additional.has(name)) {
129252                 name = "_" + name;
129253             }
129254             identifiers.additional.set(name, true);
129255             return name;
129256         }
129257         function collectFreeIdentifiers(file) {
129258             var map = ts.createMultiMap();
129259             forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); });
129260             return map;
129261         }
129262         /**
129263          * A free identifier is an identifier that can be accessed through name lookup as a local variable.
129264          * In the expression `x.y`, `x` is a free identifier, but `y` is not.
129265          */
129266         function forEachFreeIdentifier(node, cb) {
129267             if (ts.isIdentifier(node) && isFreeIdentifier(node))
129268                 cb(node);
129269             node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); });
129270         }
129271         function isFreeIdentifier(node) {
129272             var parent = node.parent;
129273             switch (parent.kind) {
129274                 case 194 /* PropertyAccessExpression */:
129275                     return parent.name !== node;
129276                 case 191 /* BindingElement */:
129277                     return parent.propertyName !== node;
129278                 case 258 /* ImportSpecifier */:
129279                     return parent.propertyName !== node;
129280                 default:
129281                     return true;
129282             }
129283         }
129284         // Node helpers
129285         function functionExpressionToDeclaration(name, additionalModifiers, fn) {
129286             return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
129287             ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
129288         }
129289         function classExpressionToDeclaration(name, additionalModifiers, cls) {
129290             return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
129291             ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
129292         }
129293         function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) {
129294             return propertyName === "default"
129295                 ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference)
129296                 : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference);
129297         }
129298         function makeImportSpecifier(propertyName, name) {
129299             return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
129300         }
129301         function makeConst(modifiers, name, init) {
129302             return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
129303         }
129304         function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
129305             return ts.createExportDeclaration(
129306             /*decorators*/ undefined, 
129307             /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
129308         }
129309     })(codefix = ts.codefix || (ts.codefix = {}));
129310 })(ts || (ts = {}));
129311 /* @internal */
129312 var ts;
129313 (function (ts) {
129314     var codefix;
129315     (function (codefix) {
129316         var fixId = "correctQualifiedNameToIndexedAccessType";
129317         var errorCodes = [ts.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.code];
129318         codefix.registerCodeFix({
129319             errorCodes: errorCodes,
129320             getCodeActions: function (context) {
129321                 var qualifiedName = getQualifiedName(context.sourceFile, context.span.start);
129322                 if (!qualifiedName)
129323                     return undefined;
129324                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); });
129325                 var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]";
129326                 return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)];
129327             },
129328             fixIds: [fixId],
129329             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
129330                 var q = getQualifiedName(diag.file, diag.start);
129331                 if (q) {
129332                     doChange(changes, diag.file, q);
129333                 }
129334             }); },
129335         });
129336         function getQualifiedName(sourceFile, pos) {
129337             var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName);
129338             ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name.");
129339             return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined;
129340         }
129341         function doChange(changeTracker, sourceFile, qualifiedName) {
129342             var rightText = qualifiedName.right.text;
129343             var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText)));
129344             changeTracker.replaceNode(sourceFile, qualifiedName, replacement);
129345         }
129346     })(codefix = ts.codefix || (ts.codefix = {}));
129347 })(ts || (ts = {}));
129348 /* @internal */
129349 var ts;
129350 (function (ts) {
129351     var codefix;
129352     (function (codefix) {
129353         var errorCodes = [ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type.code];
129354         var fixId = "convertToTypeOnlyExport";
129355         codefix.registerCodeFix({
129356             errorCodes: errorCodes,
129357             getCodeActions: function (context) {
129358                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context); });
129359                 if (changes.length) {
129360                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_type_only_export, fixId, ts.Diagnostics.Convert_all_re_exported_types_to_type_only_exports)];
129361                 }
129362             },
129363             fixIds: [fixId],
129364             getAllCodeActions: function (context) {
129365                 var fixedExportDeclarations = ts.createMap();
129366                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
129367                     var exportSpecifier = getExportSpecifierForDiagnosticSpan(diag, context.sourceFile);
129368                     if (exportSpecifier && !ts.addToSeen(fixedExportDeclarations, ts.getNodeId(exportSpecifier.parent.parent))) {
129369                         fixSingleExportDeclaration(changes, exportSpecifier, context);
129370                     }
129371                 });
129372             }
129373         });
129374         function getExportSpecifierForDiagnosticSpan(span, sourceFile) {
129375             return ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start).parent, ts.isExportSpecifier);
129376         }
129377         function fixSingleExportDeclaration(changes, exportSpecifier, context) {
129378             if (!exportSpecifier) {
129379                 return;
129380             }
129381             var exportClause = exportSpecifier.parent;
129382             var exportDeclaration = exportClause.parent;
129383             var typeExportSpecifiers = getTypeExportSpecifiers(exportSpecifier, context);
129384             if (typeExportSpecifiers.length === exportClause.elements.length) {
129385                 changes.replaceNode(context.sourceFile, exportDeclaration, ts.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, exportClause, exportDeclaration.moduleSpecifier, 
129386                 /*isTypeOnly*/ true));
129387             }
129388             else {
129389                 var valueExportDeclaration = ts.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, ts.updateNamedExports(exportClause, ts.filter(exportClause.elements, function (e) { return !ts.contains(typeExportSpecifiers, e); })), exportDeclaration.moduleSpecifier, 
129390                 /*isTypeOnly*/ false);
129391                 var typeExportDeclaration = ts.createExportDeclaration(
129392                 /*decorators*/ undefined, 
129393                 /*modifiers*/ undefined, ts.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, 
129394                 /*isTypeOnly*/ true);
129395                 changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration);
129396                 changes.insertNodeAfter(context.sourceFile, exportDeclaration, typeExportDeclaration);
129397             }
129398         }
129399         function getTypeExportSpecifiers(originExportSpecifier, context) {
129400             var exportClause = originExportSpecifier.parent;
129401             if (exportClause.elements.length === 1) {
129402                 return exportClause.elements;
129403             }
129404             var diagnostics = ts.getDiagnosticsWithinSpan(ts.createTextSpanFromNode(exportClause), context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken));
129405             return ts.filter(exportClause.elements, function (element) {
129406                 var _a;
129407                 return element === originExportSpecifier || ((_a = ts.findDiagnosticForNode(element, diagnostics)) === null || _a === void 0 ? void 0 : _a.code) === errorCodes[0];
129408             });
129409         }
129410     })(codefix = ts.codefix || (ts.codefix = {}));
129411 })(ts || (ts = {}));
129412 /* @internal */
129413 var ts;
129414 (function (ts) {
129415     var codefix;
129416     (function (codefix) {
129417         var errorCodes = [ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error.code];
129418         var fixId = "convertToTypeOnlyImport";
129419         codefix.registerCodeFix({
129420             errorCodes: errorCodes,
129421             getCodeActions: function (context) {
129422                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
129423                     var importDeclaration = getImportDeclarationForDiagnosticSpan(context.span, context.sourceFile);
129424                     fixSingleImportDeclaration(t, importDeclaration, context);
129425                 });
129426                 if (changes.length) {
129427                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_type_only_import, fixId, ts.Diagnostics.Convert_all_imports_not_used_as_a_value_to_type_only_imports)];
129428                 }
129429             },
129430             fixIds: [fixId],
129431             getAllCodeActions: function (context) {
129432                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
129433                     var importDeclaration = getImportDeclarationForDiagnosticSpan(diag, context.sourceFile);
129434                     fixSingleImportDeclaration(changes, importDeclaration, context);
129435                 });
129436             }
129437         });
129438         function getImportDeclarationForDiagnosticSpan(span, sourceFile) {
129439             return ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start).parent, ts.isImportDeclaration);
129440         }
129441         function fixSingleImportDeclaration(changes, importDeclaration, context) {
129442             if (!(importDeclaration === null || importDeclaration === void 0 ? void 0 : importDeclaration.importClause)) {
129443                 return;
129444             }
129445             var importClause = importDeclaration.importClause;
129446             // `changes.insertModifierBefore` produces a range that might overlap further changes
129447             changes.insertText(context.sourceFile, importDeclaration.getStart() + "import".length, " type");
129448             // `import type foo, { Bar }` is not allowed, so move `foo` to new declaration
129449             if (importClause.name && importClause.namedBindings) {
129450                 changes.deleteNodeRangeExcludingEnd(context.sourceFile, importClause.name, importDeclaration.importClause.namedBindings);
129451                 changes.insertNodeBefore(context.sourceFile, importDeclaration, ts.updateImportDeclaration(importDeclaration, 
129452                 /*decorators*/ undefined, 
129453                 /*modifiers*/ undefined, ts.createImportClause(importClause.name, 
129454                 /*namedBindings*/ undefined, 
129455                 /*isTypeOnly*/ true), importDeclaration.moduleSpecifier));
129456             }
129457         }
129458     })(codefix = ts.codefix || (ts.codefix = {}));
129459 })(ts || (ts = {}));
129460 /* @internal */
129461 var ts;
129462 (function (ts) {
129463     var codefix;
129464     (function (codefix) {
129465         var errorCodes = [
129466             ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code,
129467             ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code
129468         ];
129469         var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember?
129470         codefix.registerCodeFix({
129471             errorCodes: errorCodes,
129472             getCodeActions: function (context) {
129473                 var sourceFile = context.sourceFile, span = context.span;
129474                 var classDeclaration = getClass(sourceFile, span.start);
129475                 return ts.mapDefined(ts.getEffectiveImplementsTypeNodes(classDeclaration), function (implementedTypeNode) {
129476                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); });
129477                     return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces);
129478                 });
129479             },
129480             fixIds: [fixId],
129481             getAllCodeActions: function (context) {
129482                 var seenClassDeclarations = ts.createMap();
129483                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
129484                     var classDeclaration = getClass(diag.file, diag.start);
129485                     if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
129486                         for (var _i = 0, _a = ts.getEffectiveImplementsTypeNodes(classDeclaration); _i < _a.length; _i++) {
129487                             var implementedTypeNode = _a[_i];
129488                             addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences);
129489                         }
129490                     }
129491                 });
129492             },
129493         });
129494         function getClass(sourceFile, pos) {
129495             return ts.Debug.checkDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos)), "There should be a containing class");
129496         }
129497         function symbolPointsToNonPrivateMember(symbol) {
129498             return !symbol.valueDeclaration || !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */);
129499         }
129500         function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) {
129501             var checker = context.program.getTypeChecker();
129502             var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker);
129503             // Note that this is ultimately derived from a map indexed by symbol names,
129504             // so duplicates cannot occur.
129505             var implementedType = checker.getTypeAtLocation(implementedTypeNode);
129506             var implementedTypeSymbols = checker.getPropertiesOfType(implementedType);
129507             var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); }));
129508             var classType = checker.getTypeAtLocation(classDeclaration);
129509             var constructor = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m); });
129510             if (!classType.getNumberIndexType()) {
129511                 createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */);
129512             }
129513             if (!classType.getStringIndexType()) {
129514                 createMissingIndexSignatureDeclaration(implementedType, 0 /* String */);
129515             }
129516             var importAdder = codefix.createImportAdder(sourceFile, context.program, preferences, context.host);
129517             codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, importAdder, function (member) { return insertInterfaceMemberNode(sourceFile, classDeclaration, member); });
129518             importAdder.writeFixes(changeTracker);
129519             function createMissingIndexSignatureDeclaration(type, kind) {
129520                 var indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
129521                 if (indexInfoOfKind) {
129522                     insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, codefix.getNoopSymbolTrackerWithResolver(context)));
129523                 }
129524             }
129525             // Either adds the node at the top of the class, or if there's a constructor right after that
129526             function insertInterfaceMemberNode(sourceFile, cls, newElement) {
129527                 if (constructor) {
129528                     changeTracker.insertNodeAfter(sourceFile, constructor, newElement);
129529                 }
129530                 else {
129531                     changeTracker.insertNodeAtClassStart(sourceFile, cls, newElement);
129532                 }
129533             }
129534         }
129535         function getHeritageClauseSymbolTable(classDeclaration, checker) {
129536             var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration);
129537             if (!heritageClauseNode)
129538                 return ts.createSymbolTable();
129539             var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode);
129540             var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType);
129541             return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember));
129542         }
129543     })(codefix = ts.codefix || (ts.codefix = {}));
129544 })(ts || (ts = {}));
129545 /* @internal */
129546 var ts;
129547 (function (ts) {
129548     var codefix;
129549     (function (codefix) {
129550         codefix.importFixName = "import";
129551         var importFixId = "fixMissingImport";
129552         var errorCodes = [
129553             ts.Diagnostics.Cannot_find_name_0.code,
129554             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
129555             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
129556             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
129557             ts.Diagnostics.Cannot_find_namespace_0.code,
129558             ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code,
129559             ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code,
129560         ];
129561         codefix.registerCodeFix({
129562             errorCodes: errorCodes,
129563             getCodeActions: function (context) {
129564                 var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span;
129565                 var info = getFixesInfo(context, errorCode, span.start);
129566                 if (!info)
129567                     return undefined;
129568                 var fixes = info.fixes, symbolName = info.symbolName;
129569                 var quotePreference = ts.getQuotePreference(sourceFile, preferences);
129570                 return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); });
129571             },
129572             fixIds: [importFixId],
129573             getAllCodeActions: function (context) {
129574                 var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences, host = context.host;
129575                 var importAdder = createImportAdder(sourceFile, program, preferences, host);
129576                 codefix.eachDiagnostic(context, errorCodes, function (diag) { return importAdder.addImportFromDiagnostic(diag, context); });
129577                 return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, importAdder.writeFixes));
129578             },
129579         });
129580         function createImportAdder(sourceFile, program, preferences, host) {
129581             var compilerOptions = program.getCompilerOptions();
129582             // Namespace fixes don't conflict, so just build a list.
129583             var addToNamespace = [];
129584             var importType = [];
129585             // Keys are import clause node IDs.
129586             var addToExisting = ts.createMap();
129587             var newImports = ts.createMap();
129588             return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes };
129589             function addImportFromDiagnostic(diagnostic, context) {
129590                 var info = getFixesInfo(context, diagnostic.code, diagnostic.start);
129591                 if (!info || !info.fixes.length)
129592                     return;
129593                 addImport(info);
129594             }
129595             function addImportFromExportedSymbol(exportedSymbol, usageIsTypeOnly) {
129596                 var moduleSymbol = ts.Debug.checkDefined(exportedSymbol.parent);
129597                 var symbolName = ts.getNameForExportedSymbol(exportedSymbol, ts.getEmitScriptTarget(compilerOptions));
129598                 var checker = program.getTypeChecker();
129599                 var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker));
129600                 var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, sourceFile, compilerOptions, checker, program.getSourceFiles());
129601                 var preferTypeOnlyImport = !!usageIsTypeOnly && compilerOptions.importsNotUsedAsValues === 2 /* Error */;
129602                 var useRequire = shouldUseRequire(sourceFile, compilerOptions);
129603                 var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, useRequire, host, preferences);
129604                 addImport({ fixes: [fix], symbolName: symbolName });
129605             }
129606             function addImport(info) {
129607                 var fixes = info.fixes, symbolName = info.symbolName;
129608                 var fix = ts.first(fixes);
129609                 switch (fix.kind) {
129610                     case 0 /* UseNamespace */:
129611                         addToNamespace.push(fix);
129612                         break;
129613                     case 1 /* ImportType */:
129614                         importType.push(fix);
129615                         break;
129616                     case 2 /* AddToExisting */: {
129617                         var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport;
129618                         var key = String(ts.getNodeId(importClauseOrBindingPattern));
129619                         var entry = addToExisting.get(key);
129620                         if (!entry) {
129621                             addToExisting.set(key, entry = { importClauseOrBindingPattern: importClauseOrBindingPattern, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport });
129622                         }
129623                         if (importKind === 0 /* Named */) {
129624                             ts.pushIfUnique(entry.namedImports, symbolName);
129625                         }
129626                         else {
129627                             ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add to Existing) Default import should be missing or match symbolName");
129628                             entry.defaultImport = symbolName;
129629                         }
129630                         break;
129631                     }
129632                     case 3 /* AddNew */: {
129633                         var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, useRequire = fix.useRequire, typeOnly = fix.typeOnly;
129634                         var entry = newImports.get(moduleSpecifier);
129635                         if (!entry) {
129636                             newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire });
129637                         }
129638                         else {
129639                             // An import clause can only be type-only if every import fix contributing to it can be type-only.
129640                             entry.typeOnly = entry.typeOnly && typeOnly;
129641                         }
129642                         switch (importKind) {
129643                             case 1 /* Default */:
129644                                 ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add new) Default import should be missing or match symbolName");
129645                                 entry.defaultImport = symbolName;
129646                                 break;
129647                             case 0 /* Named */:
129648                                 ts.pushIfUnique(entry.namedImports || (entry.namedImports = []), symbolName);
129649                                 break;
129650                             case 3 /* CommonJS */:
129651                             case 2 /* Namespace */:
129652                                 ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName");
129653                                 entry.namespaceLikeImport = { importKind: importKind, name: symbolName };
129654                                 break;
129655                         }
129656                         break;
129657                     }
129658                     default:
129659                         ts.Debug.assertNever(fix, "fix wasn't never - got kind " + fix.kind);
129660                 }
129661             }
129662             function writeFixes(changeTracker) {
129663                 var quotePreference = ts.getQuotePreference(sourceFile, preferences);
129664                 for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) {
129665                     var fix = addToNamespace_1[_i];
129666                     addNamespaceQualifier(changeTracker, sourceFile, fix);
129667                 }
129668                 for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) {
129669                     var fix = importType_1[_a];
129670                     addImportType(changeTracker, sourceFile, fix, quotePreference);
129671                 }
129672                 addToExisting.forEach(function (_a) {
129673                     var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport;
129674                     doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport);
129675                 });
129676                 var newDeclarations;
129677                 newImports.forEach(function (_a, moduleSpecifier) {
129678                     var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]);
129679                     var getDeclarations = useRequire ? getNewRequires : getNewImports;
129680                     newDeclarations = ts.combine(newDeclarations, getDeclarations(moduleSpecifier, quotePreference, imports));
129681                 });
129682                 if (newDeclarations) {
129683                     ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true);
129684                 }
129685             }
129686         }
129687         codefix.createImportAdder = createImportAdder;
129688         // Sorted with the preferred fix coming first.
129689         var ImportFixKind;
129690         (function (ImportFixKind) {
129691             ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace";
129692             ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType";
129693             ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting";
129694             ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew";
129695         })(ImportFixKind || (ImportFixKind = {}));
129696         var ImportKind;
129697         (function (ImportKind) {
129698             ImportKind[ImportKind["Named"] = 0] = "Named";
129699             ImportKind[ImportKind["Default"] = 1] = "Default";
129700             ImportKind[ImportKind["Namespace"] = 2] = "Namespace";
129701             ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS";
129702         })(ImportKind || (ImportKind = {}));
129703         function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) {
129704             var compilerOptions = program.getCompilerOptions();
129705             var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, compilerOptions, program.getTypeChecker(), program.getSourceFiles());
129706             var useRequire = shouldUseRequire(sourceFile, compilerOptions);
129707             var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position));
129708             var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier;
129709             var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences);
129710             return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) };
129711         }
129712         codefix.getImportCompletionAction = getImportCompletionAction;
129713         function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) {
129714             ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol");
129715             // We sort the best codefixes first, so taking `first` is best.
129716             return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences));
129717         }
129718         function codeFixActionToCodeAction(_a) {
129719             var description = _a.description, changes = _a.changes, commands = _a.commands;
129720             return { description: description, changes: changes, commands: commands };
129721         }
129722         function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) {
129723             var result = [];
129724             forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) {
129725                 // Don't import from a re-export when looking "up" like to `./index` or `../index`.
129726                 if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) {
129727                     return;
129728                 }
129729                 var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions);
129730                 if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) {
129731                     result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) });
129732                 }
129733                 for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) {
129734                     var exported = _a[_i];
129735                     if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) {
129736                         result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) });
129737                     }
129738                 }
129739             });
129740             return result;
129741         }
129742         function isTypeOnlySymbol(s, checker) {
129743             return !(ts.skipAlias(s, checker).flags & 111551 /* Value */);
129744         }
129745         function isTypeOnlyPosition(sourceFile, position) {
129746             return ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position));
129747         }
129748         function getFixForImport(exportInfos, symbolName, 
129749         /** undefined only for missing JSX namespace */
129750         position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) {
129751             var checker = program.getTypeChecker();
129752             var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); });
129753             var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker);
129754             var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position));
129755             // Don't bother providing an action to add a new import if we can add to an existing one.
129756             var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences);
129757             return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport);
129758         }
129759         function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) {
129760             // It is possible that multiple import statements with the same specifier exist in the file.
129761             // e.g.
129762             //
129763             //     import * as ns from "foo";
129764             //     import { member1, member2 } from "foo";
129765             //
129766             //     member3/**/ <-- cusor here
129767             //
129768             // in this case we should provie 2 actions:
129769             //     1. change "member3" to "ns.member3"
129770             //     2. add "member3" to the second import statement's import list
129771             // and it is up to the user to decide which one fits best.
129772             return ts.firstDefined(existingImports, function (_a) {
129773                 var declaration = _a.declaration;
129774                 var namespacePrefix = getNamespaceLikeImportText(declaration);
129775                 if (namespacePrefix) {
129776                     var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker);
129777                     if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) {
129778                         return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position };
129779                     }
129780                 }
129781             });
129782         }
129783         function getTargetModuleFromNamespaceLikeImport(declaration, checker) {
129784             var _a;
129785             switch (declaration.kind) {
129786                 case 242 /* VariableDeclaration */:
129787                     return checker.resolveExternalModuleName(declaration.initializer.arguments[0]);
129788                 case 253 /* ImportEqualsDeclaration */:
129789                     return checker.getAliasedSymbol(declaration.symbol);
129790                 case 254 /* ImportDeclaration */:
129791                     var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport);
129792                     return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol);
129793                 default:
129794                     return ts.Debug.assertNever(declaration);
129795             }
129796         }
129797         function getNamespaceLikeImportText(declaration) {
129798             var _a, _b, _c;
129799             switch (declaration.kind) {
129800                 case 242 /* VariableDeclaration */:
129801                     return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text;
129802                 case 253 /* ImportEqualsDeclaration */:
129803                     return declaration.name.text;
129804                 case 254 /* ImportDeclaration */:
129805                     return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text;
129806                 default:
129807                     return ts.Debug.assertNever(declaration);
129808             }
129809         }
129810         function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) {
129811             return ts.firstDefined(existingImports, function (_a) {
129812                 var declaration = _a.declaration, importKind = _a.importKind;
129813                 if (declaration.kind === 253 /* ImportEqualsDeclaration */)
129814                     return undefined;
129815                 if (declaration.kind === 242 /* VariableDeclaration */) {
129816                     return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 189 /* ObjectBindingPattern */
129817                         ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false }
129818                         : undefined;
129819                 }
129820                 var importClause = declaration.importClause;
129821                 if (!importClause)
129822                     return undefined;
129823                 var name = importClause.name, namedBindings = importClause.namedBindings;
129824                 return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 257 /* NamedImports */)
129825                     ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport }
129826                     : undefined;
129827             });
129828         }
129829         function getExistingImportDeclarations(_a, checker, sourceFile) {
129830             var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
129831             // Can't use an es6 import for a type in JS.
129832             return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) {
129833                 var i = ts.importFromModuleSpecifier(moduleSpecifier);
129834                 if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) {
129835                     return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined;
129836                 }
129837                 if (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) {
129838                     return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined;
129839                 }
129840             });
129841         }
129842         function shouldUseRequire(sourceFile, compilerOptions) {
129843             return ts.isSourceFileJS(sourceFile)
129844                 && !sourceFile.externalModuleIndicator
129845                 && (!!sourceFile.commonJsModuleIndicator || ts.getEmitModuleKind(compilerOptions) < ts.ModuleKind.ES2015);
129846         }
129847         function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) {
129848             var isJs = ts.isSourceFileJS(sourceFile);
129849             var compilerOptions = program.getCompilerOptions();
129850             var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier;
129851             var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
129852                 var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
129853                 return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences)
129854                     .map(function (moduleSpecifier) {
129855                     // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
129856                     return exportedSymbolIsTypeOnly && isJs
129857                         ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.checkDefined(position, "position should be defined") }
129858                         : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport };
129859                 });
129860             });
129861             // Sort by presence in package.json, then shortest paths first
129862             return ts.sort(choicesForEachExportingModule, function (a, b) {
129863                 var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier);
129864                 var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier);
129865                 if (allowsImportingA && !allowsImportingB) {
129866                     return -1;
129867                 }
129868                 if (allowsImportingB && !allowsImportingA) {
129869                     return 1;
129870                 }
129871                 return a.moduleSpecifier.length - b.moduleSpecifier.length;
129872             });
129873         }
129874         function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) {
129875             var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); });
129876             return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences);
129877         }
129878         function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) {
129879             var declaration = _a.declaration, importKind = _a.importKind;
129880             var moduleSpecifier = declaration.kind === 254 /* ImportDeclaration */ ? declaration.moduleSpecifier :
129881                 declaration.kind === 242 /* VariableDeclaration */ ? declaration.initializer.arguments[0] :
129882                     declaration.moduleReference.kind === 265 /* ExternalModuleReference */ ? declaration.moduleReference.expression :
129883                         undefined;
129884             return moduleSpecifier && ts.isStringLiteral(moduleSpecifier)
129885                 ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire }
129886                 : undefined;
129887         }
129888         function getFixesInfo(context, errorCode, pos) {
129889             var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos);
129890             var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
129891                 ? getFixesInfoForUMDImport(context, symbolToken)
129892                 : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined;
129893             return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) });
129894         }
129895         function getFixesInfoForUMDImport(_a, token) {
129896             var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences;
129897             var checker = program.getTypeChecker();
129898             var umdSymbol = getUmdSymbol(token, checker);
129899             if (!umdSymbol)
129900                 return undefined;
129901             var symbol = checker.getAliasedSymbol(umdSymbol);
129902             var symbolName = umdSymbol.name;
129903             var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }];
129904             var useRequire = shouldUseRequire(sourceFile, program.getCompilerOptions());
129905             var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences);
129906             return { fixes: fixes, symbolName: symbolName };
129907         }
129908         function getUmdSymbol(token, checker) {
129909             // try the identifier to see if it is the umd symbol
129910             var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined;
129911             if (ts.isUMDExportSymbol(umdSymbol))
129912                 return umdSymbol;
129913             // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`.
129914             var parent = token.parent;
129915             return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent)
129916                 ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 111551 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol)
129917                 : undefined;
129918         }
129919         function getUmdImportKind(importingFile, compilerOptions) {
129920             // Import a synthetic `default` if enabled.
129921             if (ts.getAllowSyntheticDefaultImports(compilerOptions)) {
129922                 return 1 /* Default */;
129923             }
129924             // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it.
129925             var moduleKind = ts.getEmitModuleKind(compilerOptions);
129926             switch (moduleKind) {
129927                 case ts.ModuleKind.AMD:
129928                 case ts.ModuleKind.CommonJS:
129929                 case ts.ModuleKind.UMD:
129930                     if (ts.isInJSFile(importingFile)) {
129931                         return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 3 /* CommonJS */;
129932                     }
129933                     return 3 /* CommonJS */;
129934                 case ts.ModuleKind.System:
129935                 case ts.ModuleKind.ES2015:
129936                 case ts.ModuleKind.ES2020:
129937                 case ts.ModuleKind.ESNext:
129938                 case ts.ModuleKind.None:
129939                     // Fall back to the `import * as ns` style import.
129940                     return 2 /* Namespace */;
129941                 default:
129942                     return ts.Debug.assertNever(moduleKind, "Unexpected moduleKind " + moduleKind);
129943             }
129944         }
129945         function getFixesInfoForNonUMDImport(_a, symbolToken) {
129946             var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences;
129947             var checker = program.getTypeChecker();
129948             // If we're at `<Foo/>`, we must check if `Foo` is already in scope, and if so, get an import for `React` instead.
129949             var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent)
129950                 && symbolToken.parent.tagName === symbolToken
129951                 && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false))
129952                 ? checker.getJsxNamespace(sourceFile)
129953                 : symbolToken.text;
129954             // "default" is a keyword and not a legal identifier for the import, so we don't expect it here
129955             ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here");
129956             var compilerOptions = program.getCompilerOptions();
129957             var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken);
129958             var useRequire = shouldUseRequire(sourceFile, compilerOptions);
129959             var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, host);
129960             var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) {
129961                 var _ = _a[0], exportInfos = _a[1];
129962                 return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences);
129963             }));
129964             return { fixes: fixes, symbolName: symbolName };
129965         }
129966         // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported.
129967         function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program, host) {
129968             // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once.
129969             // Maps symbol id to info for modules providing that symbol (original export + re-exports).
129970             var originalSymbolToExportInfos = ts.createMultiMap();
129971             function addSymbol(moduleSymbol, exportedSymbol, importKind) {
129972                 originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) });
129973             }
129974             forEachExternalModuleToImportFrom(program, host, sourceFile, /*filterByPackageJson*/ true, function (moduleSymbol) {
129975                 cancellationToken.throwIfCancellationRequested();
129976                 var defaultInfo = getDefaultLikeExportInfo(sourceFile, moduleSymbol, checker, program.getCompilerOptions());
129977                 if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) {
129978                     addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind);
129979                 }
129980                 // check exports with the same name
129981                 var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol);
129982                 if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
129983                     addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */);
129984                 }
129985             });
129986             return originalSymbolToExportInfos;
129987         }
129988         function getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions) {
129989             var exported = getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions);
129990             if (!exported)
129991                 return undefined;
129992             var symbol = exported.symbol, kind = exported.kind;
129993             var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions);
129994             return info && __assign({ symbol: symbol, kind: kind }, info);
129995         }
129996         function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) {
129997             var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
129998             if (defaultExport)
129999                 return { symbol: defaultExport, kind: 1 /* Default */ };
130000             var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol);
130001             return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: getExportEqualsImportKind(importingFile, compilerOptions) };
130002         }
130003         function getExportEqualsImportKind(importingFile, compilerOptions) {
130004             var allowSyntheticDefaults = ts.getAllowSyntheticDefaultImports(compilerOptions);
130005             // 1. 'import =' will not work in es2015+, so the decision is between a default
130006             //    and a namespace import, based on allowSyntheticDefaultImports/esModuleInterop.
130007             if (ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
130008                 return allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */;
130009             }
130010             // 2. 'import =' will not work in JavaScript, so the decision is between a default
130011             //    and const/require.
130012             if (ts.isInJSFile(importingFile)) {
130013                 return ts.isExternalModule(importingFile) ? 1 /* Default */ : 3 /* CommonJS */;
130014             }
130015             // 3. At this point the most correct choice is probably 'import =', but people
130016             //    really hate that, so look to see if the importing file has any precedent
130017             //    on how to handle it.
130018             for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) {
130019                 var statement = _a[_i];
130020                 if (ts.isImportEqualsDeclaration(statement)) {
130021                     return 3 /* CommonJS */;
130022                 }
130023             }
130024             // 4. We have no precedent to go on, so just use a default import if
130025             //    allowSyntheticDefaultImports/esModuleInterop is enabled.
130026             return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */;
130027         }
130028         function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) {
130029             var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport);
130030             if (localSymbol)
130031                 return { symbolForMeaning: localSymbol, name: localSymbol.name };
130032             var name = getNameForExportDefault(defaultExport);
130033             if (name !== undefined)
130034                 return { symbolForMeaning: defaultExport, name: name };
130035             if (defaultExport.flags & 2097152 /* Alias */) {
130036                 var aliased = checker.getImmediateAliasedSymbol(defaultExport);
130037                 return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.checkDefined(aliased.parent, "Alias targets of default exports must have a parent"), checker, compilerOptions);
130038             }
130039             if (defaultExport.escapedName !== "default" /* Default */ &&
130040                 defaultExport.escapedName !== "export=" /* ExportEquals */) {
130041                 return { symbolForMeaning: defaultExport, name: defaultExport.getName() };
130042             }
130043             return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) };
130044         }
130045         function getNameForExportDefault(symbol) {
130046             return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) {
130047                 if (ts.isExportAssignment(declaration)) {
130048                     if (ts.isIdentifier(declaration.expression)) {
130049                         return declaration.expression.text;
130050                     }
130051                 }
130052                 else if (ts.isExportSpecifier(declaration)) {
130053                     ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export");
130054                     return declaration.propertyName && declaration.propertyName.text;
130055                 }
130056             });
130057         }
130058         function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) {
130059             var diag;
130060             var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) {
130061                 diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference);
130062             });
130063             return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports);
130064         }
130065         function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) {
130066             switch (fix.kind) {
130067                 case 0 /* UseNamespace */:
130068                     addNamespaceQualifier(changes, sourceFile, fix);
130069                     return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName];
130070                 case 1 /* ImportType */:
130071                     addImportType(changes, sourceFile, fix, quotePreference);
130072                     return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName];
130073                 case 2 /* AddToExisting */: {
130074                     var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport, moduleSpecifier = fix.moduleSpecifier;
130075                     doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport);
130076                     var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier);
130077                     return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too!
130078                 }
130079                 case 3 /* AddNew */: {
130080                     var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire;
130081                     var getDeclarations = useRequire ? getNewRequires : getNewImports;
130082                     var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } :
130083                         importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } :
130084                             { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly };
130085                     ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, importsCollection), /*blankLineBetween*/ true);
130086                     return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier];
130087                 }
130088                 default:
130089                     return ts.Debug.assertNever(fix, "Unexpected fix kind " + fix.kind);
130090             }
130091         }
130092         function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) {
130093             if (clause.kind === 189 /* ObjectBindingPattern */) {
130094                 if (defaultImport) {
130095                     addElementToBindingPattern(clause, defaultImport, "default");
130096                 }
130097                 for (var _i = 0, namedImports_1 = namedImports; _i < namedImports_1.length; _i++) {
130098                     var specifier = namedImports_1[_i];
130099                     addElementToBindingPattern(clause, specifier, /*propertyName*/ undefined);
130100                 }
130101                 return;
130102             }
130103             var convertTypeOnlyToRegular = !canUseTypeOnlyImport && clause.isTypeOnly;
130104             if (defaultImport) {
130105                 ts.Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one");
130106                 changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " });
130107             }
130108             if (namedImports.length) {
130109                 var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); });
130110                 if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) {
130111                     for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) {
130112                         var spec = specifiers_1[_a];
130113                         changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec);
130114                     }
130115                 }
130116                 else {
130117                     if (specifiers.length) {
130118                         var namedImports_2 = ts.createNamedImports(specifiers);
130119                         if (clause.namedBindings) {
130120                             changes.replaceNode(sourceFile, clause.namedBindings, namedImports_2);
130121                         }
130122                         else {
130123                             changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_2);
130124                         }
130125                     }
130126                 }
130127             }
130128             if (convertTypeOnlyToRegular) {
130129                 changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(clause, sourceFile));
130130             }
130131             function addElementToBindingPattern(bindingPattern, name, propertyName) {
130132                 var element = ts.createBindingElement(/*dotDotDotToken*/ undefined, propertyName, name);
130133                 if (bindingPattern.elements.length) {
130134                     changes.insertNodeInListAfter(sourceFile, ts.last(bindingPattern.elements), element);
130135                 }
130136                 else {
130137                     changes.replaceNode(sourceFile, bindingPattern, ts.createObjectBindingPattern([element]));
130138                 }
130139             }
130140         }
130141         function addNamespaceQualifier(changes, sourceFile, _a) {
130142             var namespacePrefix = _a.namespacePrefix, position = _a.position;
130143             changes.insertText(sourceFile, position, namespacePrefix + ".");
130144         }
130145         function addImportType(changes, sourceFile, _a, quotePreference) {
130146             var moduleSpecifier = _a.moduleSpecifier, position = _a.position;
130147             changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference));
130148         }
130149         function getImportTypePrefix(moduleSpecifier, quotePreference) {
130150             var quote = ts.getQuoteFromPreference(quotePreference);
130151             return "import(" + quote + moduleSpecifier + quote + ").";
130152         }
130153         function getNewImports(moduleSpecifier, quotePreference, imports) {
130154             var _a, _b;
130155             var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference);
130156             var statements;
130157             if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) {
130158                 statements = ts.combine(statements, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly));
130159             }
130160             var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly;
130161             if (namespaceLikeImport) {
130162                 var declaration = namespaceLikeImport.importKind === 3 /* CommonJS */
130163                     ? ts.createImportEqualsDeclaration(
130164                     /*decorators*/ undefined, 
130165                     /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier))
130166                     : ts.createImportDeclaration(
130167                     /*decorators*/ undefined, 
130168                     /*modifiers*/ undefined, ts.createImportClause(
130169                     /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier);
130170                 statements = ts.combine(statements, declaration);
130171             }
130172             return ts.Debug.checkDefined(statements);
130173         }
130174         function getNewRequires(moduleSpecifier, quotePreference, imports) {
130175             var _a, _b;
130176             var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference);
130177             var statements;
130178             // const { default: foo, bar, etc } = require('./mod');
130179             if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) {
130180                 var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || [];
130181                 if (imports.defaultImport) {
130182                     bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport));
130183                 }
130184                 var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier);
130185                 statements = ts.combine(statements, declaration);
130186             }
130187             // const foo = require('./mod');
130188             if (imports.namespaceLikeImport) {
130189                 var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier);
130190                 statements = ts.combine(statements, declaration);
130191             }
130192             return ts.Debug.checkDefined(statements);
130193         }
130194         function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) {
130195             return ts.createVariableStatement(
130196             /*modifiers*/ undefined, ts.createVariableDeclarationList([
130197                 ts.createVariableDeclaration(typeof name === "string" ? ts.createIdentifier(name) : name, 
130198                 /*type*/ undefined, ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier]))
130199             ], 2 /* Const */));
130200         }
130201         function symbolHasMeaning(_a, meaning) {
130202             var declarations = _a.declarations;
130203             return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); });
130204         }
130205         function forEachExternalModuleToImportFrom(program, host, from, filterByPackageJson, cb) {
130206             var filteredCount = 0;
130207             var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host);
130208             var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host, moduleSpecifierResolutionHost);
130209             forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, sourceFile) {
130210                 if (sourceFile === undefined) {
130211                     if (!packageJson || packageJson.allowsImportingAmbientModule(module)) {
130212                         cb(module);
130213                     }
130214                     else if (packageJson) {
130215                         filteredCount++;
130216                     }
130217                 }
130218                 else if (sourceFile &&
130219                     sourceFile !== from &&
130220                     isImportableFile(program, from, sourceFile, moduleSpecifierResolutionHost)) {
130221                     if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile)) {
130222                         cb(module);
130223                     }
130224                     else if (packageJson) {
130225                         filteredCount++;
130226                     }
130227                 }
130228             });
130229             if (host.log) {
130230                 host.log("forEachExternalModuleToImportFrom: filtered out " + filteredCount + " modules by package.json contents");
130231             }
130232         }
130233         codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom;
130234         function forEachExternalModule(checker, allSourceFiles, cb) {
130235             for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) {
130236                 var ambient = _a[_i];
130237                 cb(ambient, /*sourceFile*/ undefined);
130238             }
130239             for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) {
130240                 var sourceFile = allSourceFiles_1[_b];
130241                 if (ts.isExternalOrCommonJsModule(sourceFile)) {
130242                     cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
130243                 }
130244             }
130245         }
130246         function isImportableFile(program, from, to, moduleSpecifierResolutionHost) {
130247             var _a;
130248             var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost);
130249             var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost);
130250             return !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, 
130251             /*preferSymlinks*/ false, function (toPath) {
130252                 var toFile = program.getSourceFile(toPath);
130253                 // Determine to import using toPath only if toPath is what we were looking at
130254                 // or there doesnt exist the file in the program by the symlink
130255                 return (toFile === to || !toFile) &&
130256                     isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache);
130257             });
130258         }
130259         /**
130260          * Don't include something from a `node_modules` that isn't actually reachable by a global import.
130261          * A relative import to node_modules is usually a bad idea.
130262          */
130263         function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) {
130264             // If it's in a `node_modules` but is not reachable from here via a global import, don't bother.
130265             var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; });
130266             var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules));
130267             return toNodeModulesParent === undefined
130268                 || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent)
130269                 || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent));
130270         }
130271         function moduleSymbolToValidIdentifier(moduleSymbol, target) {
130272             return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target);
130273         }
130274         codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier;
130275         function moduleSpecifierToValidIdentifier(moduleSpecifier, target) {
130276             var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index"));
130277             var res = "";
130278             var lastCharWasValid = true;
130279             var firstCharCode = baseName.charCodeAt(0);
130280             if (ts.isIdentifierStart(firstCharCode, target)) {
130281                 res += String.fromCharCode(firstCharCode);
130282             }
130283             else {
130284                 lastCharWasValid = false;
130285             }
130286             for (var i = 1; i < baseName.length; i++) {
130287                 var ch = baseName.charCodeAt(i);
130288                 var isValid = ts.isIdentifierPart(ch, target);
130289                 if (isValid) {
130290                     var char = String.fromCharCode(ch);
130291                     if (!lastCharWasValid) {
130292                         char = char.toUpperCase();
130293                     }
130294                     res += char;
130295                 }
130296                 lastCharWasValid = isValid;
130297             }
130298             // Need `|| "_"` to ensure result isn't empty.
130299             return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res;
130300         }
130301         codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier;
130302         function createAutoImportFilter(fromFile, program, host, moduleSpecifierResolutionHost) {
130303             if (moduleSpecifierResolutionHost === void 0) { moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); }
130304             var packageJsons = host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName) || ts.getPackageJsonsVisibleToFile(fromFile.fileName, host);
130305             var dependencyGroups = 1 /* Dependencies */ | 2 /* DevDependencies */ | 8 /* OptionalDependencies */;
130306             var usesNodeCoreModules;
130307             return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier, moduleSpecifierResolutionHost: moduleSpecifierResolutionHost };
130308             function moduleSpecifierIsCoveredByPackageJson(specifier) {
130309                 var packageName = getNodeModuleRootSpecifier(specifier);
130310                 for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) {
130311                     var packageJson = packageJsons_1[_i];
130312                     if (packageJson.has(packageName, dependencyGroups) || packageJson.has(ts.getTypesPackageName(packageName), dependencyGroups)) {
130313                         return true;
130314                     }
130315                 }
130316                 return false;
130317             }
130318             function allowsImportingAmbientModule(moduleSymbol) {
130319                 if (!packageJsons.length) {
130320                     return true;
130321                 }
130322                 var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile();
130323                 var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName);
130324                 if (typeof declaringNodeModuleName === "undefined") {
130325                     return true;
130326                 }
130327                 var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName());
130328                 if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) {
130329                     return true;
130330                 }
130331                 return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName)
130332                     || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier);
130333             }
130334             function allowsImportingSourceFile(sourceFile) {
130335                 if (!packageJsons.length) {
130336                     return true;
130337                 }
130338                 var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName);
130339                 if (!moduleSpecifier) {
130340                     return true;
130341                 }
130342                 return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
130343             }
130344             /**
130345              * Use for a specific module specifier that has already been resolved.
130346              * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve
130347              * the best module specifier for a given module _and_ determine if it’s importable.
130348              */
130349             function allowsImportingSpecifier(moduleSpecifier) {
130350                 if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) {
130351                     return true;
130352                 }
130353                 if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) {
130354                     return true;
130355                 }
130356                 return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
130357             }
130358             function isAllowedCoreNodeModulesImport(moduleSpecifier) {
130359                 // If we’re in JavaScript, it can be difficult to tell whether the user wants to import
130360                 // from Node core modules or not. We can start by seeing if the user is actually using
130361                 // any node core modules, as opposed to simply having @types/node accidentally as a
130362                 // dependency of a dependency.
130363                 if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) {
130364                     if (usesNodeCoreModules === undefined) {
130365                         usesNodeCoreModules = ts.consumesNodeCoreModules(fromFile);
130366                     }
130367                     if (usesNodeCoreModules) {
130368                         return true;
130369                     }
130370                 }
130371                 return false;
130372             }
130373             function getNodeModulesPackageNameFromFileName(importedFileName) {
130374                 if (!ts.stringContains(importedFileName, "node_modules")) {
130375                     return undefined;
130376                 }
130377                 var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost);
130378                 if (!specifier) {
130379                     return undefined;
130380                 }
130381                 // Paths here are not node_modules, so we don’t care about them;
130382                 // returning anything will trigger a lookup in package.json.
130383                 if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) {
130384                     return getNodeModuleRootSpecifier(specifier);
130385                 }
130386             }
130387             function getNodeModuleRootSpecifier(fullSpecifier) {
130388                 var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1);
130389                 // Scoped packages
130390                 if (ts.startsWith(components[0], "@")) {
130391                     return components[0] + "/" + components[1];
130392                 }
130393                 return components[0];
130394             }
130395         }
130396     })(codefix = ts.codefix || (ts.codefix = {}));
130397 })(ts || (ts = {}));
130398 /* @internal */
130399 var ts;
130400 (function (ts) {
130401     var codefix;
130402     (function (codefix) {
130403         var fixId = "fixImplicitThis";
130404         var errorCodes = [ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code];
130405         codefix.registerCodeFix({
130406             errorCodes: errorCodes,
130407             getCodeActions: function (context) {
130408                 var sourceFile = context.sourceFile, program = context.program, span = context.span;
130409                 var diagnostic;
130410                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
130411                     diagnostic = doChange(t, sourceFile, span.start, program.getTypeChecker());
130412                 });
130413                 return diagnostic ? [codefix.createCodeFixAction(fixId, changes, diagnostic, fixId, ts.Diagnostics.Fix_all_implicit_this_errors)] : ts.emptyArray;
130414             },
130415             fixIds: [fixId],
130416             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
130417                 doChange(changes, diag.file, diag.start, context.program.getTypeChecker());
130418             }); },
130419         });
130420         function doChange(changes, sourceFile, pos, checker) {
130421             var token = ts.getTokenAtPosition(sourceFile, pos);
130422             ts.Debug.assert(token.kind === 104 /* ThisKeyword */);
130423             var fn = ts.getThisContainer(token, /*includeArrowFunctions*/ false);
130424             if (!ts.isFunctionDeclaration(fn) && !ts.isFunctionExpression(fn))
130425                 return undefined;
130426             if (!ts.isSourceFile(ts.getThisContainer(fn, /*includeArrowFunctions*/ false))) { // 'this' is defined outside, convert to arrow function
130427                 var fnKeyword = ts.Debug.assertDefined(ts.findChildOfKind(fn, 94 /* FunctionKeyword */, sourceFile));
130428                 var name = fn.name;
130429                 var body = ts.Debug.assertDefined(fn.body); // Should be defined because the function contained a 'this' expression
130430                 if (ts.isFunctionExpression(fn)) {
130431                     if (name && ts.FindAllReferences.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) {
130432                         // Function expression references itself. To fix we would have to extract it to a const.
130433                         return undefined;
130434                     }
130435                     // `function() {}` --> `() => {}`
130436                     changes.delete(sourceFile, fnKeyword);
130437                     if (name) {
130438                         changes.delete(sourceFile, name);
130439                     }
130440                     changes.insertText(sourceFile, body.pos, " =>");
130441                     return [ts.Diagnostics.Convert_function_expression_0_to_arrow_function, name ? name.text : ts.ANONYMOUS];
130442                 }
130443                 else {
130444                     // `function f() {}` => `const f = () => {}`
130445                     // `name` should be defined because we only do this in inner contexts, and name is only undefined for `export default function() {}`.
130446                     changes.replaceNode(sourceFile, fnKeyword, ts.createToken(81 /* ConstKeyword */));
130447                     changes.insertText(sourceFile, name.end, " = ");
130448                     changes.insertText(sourceFile, body.pos, " =>");
130449                     return [ts.Diagnostics.Convert_function_declaration_0_to_arrow_function, name.text];
130450                 }
130451             }
130452             // No outer 'this', add a @class tag if in a JS constructor function
130453             else if (ts.isSourceFileJS(sourceFile) && ts.isPropertyAccessExpression(token.parent) && ts.isAssignmentExpression(token.parent.parent)) {
130454                 codefix.addJSDocTags(changes, sourceFile, fn, [ts.createJSDocClassTag()]);
130455                 return ts.Diagnostics.Add_class_tag;
130456             }
130457         }
130458     })(codefix = ts.codefix || (ts.codefix = {}));
130459 })(ts || (ts = {}));
130460 /* @internal */
130461 var ts;
130462 (function (ts) {
130463     var codefix;
130464     (function (codefix) {
130465         var fixId = "fixSpelling";
130466         var errorCodes = [
130467             ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
130468             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
130469             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
130470             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
130471             ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code,
130472         ];
130473         codefix.registerCodeFix({
130474             errorCodes: errorCodes,
130475             getCodeActions: function (context) {
130476                 var sourceFile = context.sourceFile;
130477                 var info = getInfo(sourceFile, context.span.start, context);
130478                 if (!info)
130479                     return undefined;
130480                 var node = info.node, suggestedSymbol = info.suggestedSymbol;
130481                 var target = context.host.getCompilationSettings().target;
130482                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestedSymbol, target); });
130483                 return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, ts.symbolName(suggestedSymbol)], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)];
130484             },
130485             fixIds: [fixId],
130486             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
130487                 var info = getInfo(diag.file, diag.start, context);
130488                 var target = context.host.getCompilationSettings().target;
130489                 if (info)
130490                     doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target);
130491             }); },
130492         });
130493         function getInfo(sourceFile, pos, context) {
130494             // This is the identifier of the misspelled word. eg:
130495             // this.speling = 1;
130496             //      ^^^^^^^
130497             var node = ts.getTokenAtPosition(sourceFile, pos);
130498             var parent = node.parent;
130499             var checker = context.program.getTypeChecker();
130500             var suggestedSymbol;
130501             if (ts.isPropertyAccessExpression(parent) && parent.name === node) {
130502                 ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)");
130503                 var containingType = checker.getTypeAtLocation(parent.expression);
130504                 if (parent.flags & 32 /* OptionalChain */) {
130505                     containingType = checker.getNonNullableType(containingType);
130506                 }
130507                 suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType);
130508             }
130509             else if (ts.isImportSpecifier(parent) && parent.name === node) {
130510                 ts.Debug.assertNode(node, ts.isIdentifier, "Expected an identifier for spelling (import)");
130511                 var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration);
130512                 var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration);
130513                 if (resolvedSourceFile && resolvedSourceFile.symbol) {
130514                     suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol);
130515                 }
130516             }
130517             else {
130518                 var meaning = ts.getMeaningFromLocation(node);
130519                 var name = ts.getTextOfNode(node);
130520                 ts.Debug.assert(name !== undefined, "name should be defined");
130521                 suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning));
130522             }
130523             return suggestedSymbol === undefined ? undefined : { node: node, suggestedSymbol: suggestedSymbol };
130524         }
130525         function doChange(changes, sourceFile, node, suggestedSymbol, target) {
130526             var suggestion = ts.symbolName(suggestedSymbol);
130527             if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) {
130528                 var valDecl = suggestedSymbol.valueDeclaration;
130529                 if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) {
130530                     changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion));
130531                 }
130532                 else {
130533                     changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion)));
130534                 }
130535             }
130536             else {
130537                 changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion));
130538             }
130539         }
130540         function convertSemanticMeaningToSymbolFlags(meaning) {
130541             var flags = 0;
130542             if (meaning & 4 /* Namespace */) {
130543                 flags |= 1920 /* Namespace */;
130544             }
130545             if (meaning & 2 /* Type */) {
130546                 flags |= 788968 /* Type */;
130547             }
130548             if (meaning & 1 /* Value */) {
130549                 flags |= 111551 /* Value */;
130550             }
130551             return flags;
130552         }
130553         function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) {
130554             if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier))
130555                 return undefined;
130556             var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text);
130557             if (!resolvedModule)
130558                 return undefined;
130559             return context.program.getSourceFile(resolvedModule.resolvedFileName);
130560         }
130561     })(codefix = ts.codefix || (ts.codefix = {}));
130562 })(ts || (ts = {}));
130563 /* @internal */
130564 var ts;
130565 (function (ts) {
130566     var codefix;
130567     (function (codefix) {
130568         var fixId = "returnValueCorrect";
130569         var fixIdAddReturnStatement = "fixAddReturnStatement";
130570         var fixIdRemoveBlockBodyBrace = "fixRemoveBlockBodyBrace";
130571         var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen";
130572         var errorCodes = [
130573             ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code,
130574             ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code,
130575             ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code
130576         ];
130577         var ProblemKind;
130578         (function (ProblemKind) {
130579             ProblemKind[ProblemKind["MissingReturnStatement"] = 0] = "MissingReturnStatement";
130580             ProblemKind[ProblemKind["MissingParentheses"] = 1] = "MissingParentheses";
130581         })(ProblemKind || (ProblemKind = {}));
130582         codefix.registerCodeFix({
130583             errorCodes: errorCodes,
130584             fixIds: [fixIdAddReturnStatement, fixIdRemoveBlockBodyBrace, fixIdWrapTheBlockWithParen],
130585             getCodeActions: function (context) {
130586                 var program = context.program, sourceFile = context.sourceFile, start = context.span.start, errorCode = context.errorCode;
130587                 var info = getInfo(program.getTypeChecker(), sourceFile, start, errorCode);
130588                 if (!info)
130589                     return undefined;
130590                 if (info.kind === ProblemKind.MissingReturnStatement) {
130591                     return ts.append([getActionForfixAddReturnStatement(context, info.expression, info.statement)], ts.isArrowFunction(info.declaration) ? getActionForfixRemoveBlockBodyBrace(context, info.declaration, info.expression, info.commentSource) : undefined);
130592                 }
130593                 else {
130594                     return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)];
130595                 }
130596             },
130597             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
130598                 var info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code);
130599                 if (!info)
130600                     return undefined;
130601                 switch (context.fixId) {
130602                     case fixIdAddReturnStatement:
130603                         addReturnStatement(changes, diag.file, info.expression, info.statement);
130604                         break;
130605                     case fixIdRemoveBlockBodyBrace:
130606                         if (!ts.isArrowFunction(info.declaration))
130607                             return undefined;
130608                         removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /* withParen */ false);
130609                         break;
130610                     case fixIdWrapTheBlockWithParen:
130611                         if (!ts.isArrowFunction(info.declaration))
130612                             return undefined;
130613                         wrapBlockWithParen(changes, diag.file, info.declaration, info.expression);
130614                         break;
130615                     default:
130616                         ts.Debug.fail(JSON.stringify(context.fixId));
130617                 }
130618             }); },
130619         });
130620         function getFixInfo(checker, declaration, expectType, isFunctionType) {
130621             if (!declaration.body || !ts.isBlock(declaration.body) || ts.length(declaration.body.statements) !== 1)
130622                 return undefined;
130623             var firstStatement = ts.first(declaration.body.statements);
130624             if (ts.isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, firstStatement.expression, expectType, isFunctionType)) {
130625                 return {
130626                     declaration: declaration,
130627                     kind: ProblemKind.MissingReturnStatement,
130628                     expression: firstStatement.expression,
130629                     statement: firstStatement,
130630                     commentSource: firstStatement.expression
130631                 };
130632             }
130633             else if (ts.isLabeledStatement(firstStatement) && ts.isExpressionStatement(firstStatement.statement)) {
130634                 var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]);
130635                 if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) {
130636                     return ts.isArrowFunction(declaration) ? {
130637                         declaration: declaration,
130638                         kind: ProblemKind.MissingParentheses,
130639                         expression: node,
130640                         statement: firstStatement,
130641                         commentSource: firstStatement.statement.expression
130642                     } : {
130643                         declaration: declaration,
130644                         kind: ProblemKind.MissingReturnStatement,
130645                         expression: node,
130646                         statement: firstStatement,
130647                         commentSource: firstStatement.statement.expression
130648                     };
130649                 }
130650             }
130651             else if (ts.isBlock(firstStatement) && ts.length(firstStatement.statements) === 1) {
130652                 var firstBlockStatement = ts.first(firstStatement.statements);
130653                 if (ts.isLabeledStatement(firstBlockStatement) && ts.isExpressionStatement(firstBlockStatement.statement)) {
130654                     var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]);
130655                     if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) {
130656                         return {
130657                             declaration: declaration,
130658                             kind: ProblemKind.MissingReturnStatement,
130659                             expression: node,
130660                             statement: firstStatement,
130661                             commentSource: firstBlockStatement
130662                         };
130663                     }
130664                 }
130665             }
130666             return undefined;
130667         }
130668         function checkFixedAssignableTo(checker, declaration, expr, type, isFunctionType) {
130669             return checker.isTypeAssignableTo(checker.getTypeAtLocation(isFunctionType ? ts.updateFunctionLikeBody(declaration, ts.createBlock([ts.createReturn(expr)])) : expr), type);
130670         }
130671         function getInfo(checker, sourceFile, position, errorCode) {
130672             var node = ts.getTokenAtPosition(sourceFile, position);
130673             if (!node.parent)
130674                 return undefined;
130675             var declaration = ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration);
130676             switch (errorCode) {
130677                 case ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code:
130678                     if (!declaration || !declaration.body || !declaration.type || !ts.rangeContainsRange(declaration.type, node))
130679                         return undefined;
130680                     return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false);
130681                 case ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code:
130682                     if (!declaration || !ts.isCallExpression(declaration.parent) || !declaration.body)
130683                         return undefined;
130684                     var pos = declaration.parent.arguments.indexOf(declaration);
130685                     var type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos);
130686                     if (!type)
130687                         return undefined;
130688                     return getFixInfo(checker, declaration, type, /* isFunctionType */ true);
130689                 case ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code:
130690                     if (!ts.isDeclarationName(node) || !ts.isVariableLike(node.parent) && !ts.isJsxAttribute(node.parent))
130691                         return undefined;
130692                     var initializer = getVariableLikeInitializer(node.parent);
130693                     if (!initializer || !ts.isFunctionLikeDeclaration(initializer) || !initializer.body)
130694                         return undefined;
130695                     return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /* isFunctionType */ true);
130696             }
130697             return undefined;
130698         }
130699         function getVariableLikeInitializer(declaration) {
130700             switch (declaration.kind) {
130701                 case 242 /* VariableDeclaration */:
130702                 case 156 /* Parameter */:
130703                 case 191 /* BindingElement */:
130704                 case 159 /* PropertyDeclaration */:
130705                 case 281 /* PropertyAssignment */:
130706                     return declaration.initializer;
130707                 case 273 /* JsxAttribute */:
130708                     return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined);
130709                 case 282 /* ShorthandPropertyAssignment */:
130710                 case 158 /* PropertySignature */:
130711                 case 284 /* EnumMember */:
130712                 case 323 /* JSDocPropertyTag */:
130713                 case 317 /* JSDocParameterTag */:
130714                     return undefined;
130715             }
130716         }
130717         function addReturnStatement(changes, sourceFile, expression, statement) {
130718             ts.suppressLeadingAndTrailingTrivia(expression);
130719             var probablyNeedSemi = ts.probablyUsesSemicolons(sourceFile);
130720             changes.replaceNode(sourceFile, statement, ts.createReturn(expression), {
130721                 leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
130722                 trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude,
130723                 suffix: probablyNeedSemi ? ";" : undefined
130724             });
130725         }
130726         function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) {
130727             var newBody = (withParen || ts.needsParentheses(expression)) ? ts.createParen(expression) : expression;
130728             ts.suppressLeadingAndTrailingTrivia(commentSource);
130729             ts.copyComments(commentSource, newBody);
130730             changes.replaceNode(sourceFile, declaration.body, newBody);
130731         }
130732         function wrapBlockWithParen(changes, sourceFile, declaration, expression) {
130733             changes.replaceNode(sourceFile, declaration.body, ts.createParen(expression));
130734         }
130735         function getActionForfixAddReturnStatement(context, expression, statement) {
130736             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addReturnStatement(t, context.sourceFile, expression, statement); });
130737             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, ts.Diagnostics.Add_all_missing_return_statement);
130738         }
130739         function getActionForfixRemoveBlockBodyBrace(context, declaration, expression, commentSource) {
130740             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /* withParen */ false); });
130741             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_block_body_braces, fixIdRemoveBlockBodyBrace, ts.Diagnostics.Remove_all_incorrect_body_block_braces);
130742         }
130743         function getActionForfixWrapTheBlockWithParen(context, declaration, expression) {
130744             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return wrapBlockWithParen(t, context.sourceFile, declaration, expression); });
130745             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, ts.Diagnostics.Wrap_all_object_literal_with_parentheses);
130746         }
130747     })(codefix = ts.codefix || (ts.codefix = {}));
130748 })(ts || (ts = {}));
130749 /* @internal */
130750 var ts;
130751 (function (ts) {
130752     var codefix;
130753     (function (codefix) {
130754         var fixName = "addMissingMember";
130755         var errorCodes = [
130756             ts.Diagnostics.Property_0_does_not_exist_on_type_1.code,
130757             ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
130758             ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code,
130759             ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code,
130760             ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code
130761         ];
130762         var fixId = "addMissingMember";
130763         codefix.registerCodeFix({
130764             errorCodes: errorCodes,
130765             getCodeActions: function (context) {
130766                 var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker(), context.program);
130767                 if (!info)
130768                     return undefined;
130769                 if (info.kind === 0 /* Enum */) {
130770                     var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration;
130771                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); });
130772                     return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)];
130773                 }
130774                 var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
130775                 var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs);
130776                 var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ?
130777                     ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) :
130778                     getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic);
130779                 return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember);
130780             },
130781             fixIds: [fixId],
130782             getAllCodeActions: function (context) {
130783                 var program = context.program;
130784                 var checker = program.getTypeChecker();
130785                 var seen = ts.createMap();
130786                 var typeDeclToMembers = new ts.NodeMap();
130787                 return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
130788                     codefix.eachDiagnostic(context, errorCodes, function (diag) {
130789                         var info = getInfo(diag.file, diag.start, checker, context.program);
130790                         if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) {
130791                             return;
130792                         }
130793                         if (info.kind === 0 /* Enum */) {
130794                             var token = info.token, parentDeclaration = info.parentDeclaration;
130795                             addEnumMemberDeclaration(changes, checker, token, parentDeclaration);
130796                         }
130797                         else {
130798                             var parentDeclaration = info.parentDeclaration, token_2 = info.token;
130799                             var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; });
130800                             if (!infos.some(function (i) { return i.token.text === token_2.text; }))
130801                                 infos.push(info);
130802                         }
130803                     });
130804                     typeDeclToMembers.forEach(function (infos, classDeclaration) {
130805                         var supers = getAllSupers(classDeclaration, checker);
130806                         var _loop_13 = function (info) {
130807                             // If some superclass added this property, don't add it again.
130808                             if (supers.some(function (superClassOrInterface) {
130809                                 var superInfos = typeDeclToMembers.get(superClassOrInterface);
130810                                 return !!superInfos && superInfos.some(function (_a) {
130811                                     var token = _a.token;
130812                                     return token.text === info.token.text;
130813                                 });
130814                             }))
130815                                 return "continue";
130816                             var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
130817                             // Always prefer to add a method declaration if possible.
130818                             if (call && !ts.isPrivateIdentifier(token)) {
130819                                 addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs);
130820                             }
130821                             else {
130822                                 if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) {
130823                                     addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, makeStatic);
130824                                 }
130825                                 else {
130826                                     var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token);
130827                                     addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic ? 32 /* Static */ : 0);
130828                                 }
130829                             }
130830                         };
130831                         for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
130832                             var info = infos_1[_i];
130833                             _loop_13(info);
130834                         }
130835                     });
130836                 }));
130837             },
130838         });
130839         function getAllSupers(decl, checker) {
130840             var res = [];
130841             while (decl) {
130842                 var superElement = ts.getClassExtendsHeritageElement(decl);
130843                 var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression);
130844                 var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike);
130845                 if (superDecl) {
130846                     res.push(superDecl);
130847                 }
130848                 decl = superDecl;
130849             }
130850             return res;
130851         }
130852         var InfoKind;
130853         (function (InfoKind) {
130854             InfoKind[InfoKind["Enum"] = 0] = "Enum";
130855             InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface";
130856         })(InfoKind || (InfoKind = {}));
130857         function getInfo(tokenSourceFile, tokenPos, checker, program) {
130858             // The identifier of the missing property. eg:
130859             // this.missing = 1;
130860             //      ^^^^^^^
130861             var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos);
130862             if (!ts.isIdentifier(token) && !ts.isPrivateIdentifier(token)) {
130863                 return undefined;
130864             }
130865             var parent = token.parent;
130866             if (!ts.isPropertyAccessExpression(parent))
130867                 return undefined;
130868             var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression));
130869             var symbol = leftExpressionType.symbol;
130870             if (!symbol || !symbol.declarations)
130871                 return undefined;
130872             var classDeclaration = ts.find(symbol.declarations, ts.isClassLike);
130873             // Don't suggest adding private identifiers to anything other than a class.
130874             if (!classDeclaration && ts.isPrivateIdentifier(token)) {
130875                 return undefined;
130876             }
130877             // Prefer to change the class instead of the interface if they are merged
130878             var classOrInterface = classDeclaration || ts.find(symbol.declarations, ts.isInterfaceDeclaration);
130879             if (classOrInterface && !program.isSourceFileFromExternalLibrary(classOrInterface.getSourceFile())) {
130880                 var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol);
130881                 if (makeStatic && (ts.isPrivateIdentifier(token) || ts.isInterfaceDeclaration(classOrInterface))) {
130882                     return undefined;
130883                 }
130884                 var declSourceFile = classOrInterface.getSourceFile();
130885                 var inJs = ts.isSourceFileJS(declSourceFile);
130886                 var call = ts.tryCast(parent.parent, ts.isCallExpression);
130887                 return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call };
130888             }
130889             var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration);
130890             if (enumDeclaration && !ts.isPrivateIdentifier(token) && !program.isSourceFileFromExternalLibrary(enumDeclaration.getSourceFile())) {
130891                 return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration };
130892             }
130893             return undefined;
130894         }
130895         function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, token, makeStatic) {
130896             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, token, makeStatic); });
130897             if (changes.length === 0) {
130898                 return undefined;
130899             }
130900             var diagnostic = makeStatic ? ts.Diagnostics.Initialize_static_property_0 :
130901                 ts.isPrivateIdentifier(token) ? ts.Diagnostics.Declare_a_private_field_named_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor;
130902             return codefix.createCodeFixAction(fixName, changes, [diagnostic, token.text], fixId, ts.Diagnostics.Add_all_missing_members);
130903         }
130904         function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, token, makeStatic) {
130905             var tokenName = token.text;
130906             if (makeStatic) {
130907                 if (classDeclaration.kind === 214 /* ClassExpression */) {
130908                     return;
130909                 }
130910                 var className = classDeclaration.name.getText();
130911                 var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName);
130912                 changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization);
130913             }
130914             else if (ts.isPrivateIdentifier(token)) {
130915                 var property = ts.createProperty(
130916                 /*decorators*/ undefined, 
130917                 /*modifiers*/ undefined, tokenName, 
130918                 /*questionToken*/ undefined, 
130919                 /*type*/ undefined, 
130920                 /*initializer*/ undefined);
130921                 var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
130922                 if (lastProp) {
130923                     changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
130924                 }
130925                 else {
130926                     changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
130927                 }
130928             }
130929             else {
130930                 var classConstructor = ts.getFirstConstructorWithBody(classDeclaration);
130931                 if (!classConstructor) {
130932                     return;
130933                 }
130934                 var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName);
130935                 changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization);
130936             }
130937         }
130938         function initializePropertyToUndefined(obj, propertyName) {
130939             return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined")));
130940         }
130941         function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) {
130942             var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token);
130943             var actions = [createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, token.text, typeNode, makeStatic ? 32 /* Static */ : 0)];
130944             if (makeStatic || ts.isPrivateIdentifier(token)) {
130945                 return actions;
130946             }
130947             if (ts.startsWithUnderscore(token.text)) {
130948                 actions.unshift(createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, token.text, typeNode, 8 /* Private */));
130949             }
130950             actions.push(createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode));
130951             return actions;
130952         }
130953         function getTypeNode(checker, classDeclaration, token) {
130954             var typeNode;
130955             if (token.parent.parent.kind === 209 /* BinaryExpression */) {
130956                 var binaryExpression = token.parent.parent;
130957                 var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left;
130958                 var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression)));
130959                 typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined);
130960             }
130961             else {
130962                 var contextualType = checker.getContextualType(token.parent);
130963                 typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined;
130964             }
130965             return typeNode || ts.createKeywordTypeNode(125 /* AnyKeyword */);
130966         }
130967         function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags) {
130968             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags); });
130969             if (modifierFlags & 8 /* Private */) {
130970                 return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Declare_private_property_0, tokenName]);
130971             }
130972             return codefix.createCodeFixAction(fixName, changes, [modifierFlags & 32 /* Static */ ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members);
130973         }
130974         function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags) {
130975             var property = ts.createProperty(
130976             /*decorators*/ undefined, 
130977             /*modifiers*/ modifierFlags ? ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined, tokenName, 
130978             /*questionToken*/ undefined, typeNode, 
130979             /*initializer*/ undefined);
130980             var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
130981             if (lastProp) {
130982                 changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
130983             }
130984             else {
130985                 changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
130986             }
130987         }
130988         // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
130989         function getNodeToInsertPropertyAfter(cls) {
130990             var res;
130991             for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
130992                 var member = _a[_i];
130993                 if (!ts.isPropertyDeclaration(member))
130994                     break;
130995                 res = member;
130996             }
130997             return res;
130998         }
130999         function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) {
131000             // Index signatures cannot have the static modifier.
131001             var stringTypeNode = ts.createKeywordTypeNode(143 /* StringKeyword */);
131002             var indexingParameter = ts.createParameter(
131003             /*decorators*/ undefined, 
131004             /*modifiers*/ undefined, 
131005             /*dotDotDotToken*/ undefined, "x", 
131006             /*questionToken*/ undefined, stringTypeNode, 
131007             /*initializer*/ undefined);
131008             var indexSignature = ts.createIndexSignature(
131009             /*decorators*/ undefined, 
131010             /*modifiers*/ undefined, [indexingParameter], typeNode);
131011             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); });
131012             // No fixId here because code-fix-all currently only works on adding individual named properties.
131013             return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]);
131014         }
131015         function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) {
131016             // Private methods are not implemented yet.
131017             if (ts.isPrivateIdentifier(token)) {
131018                 return undefined;
131019             }
131020             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); });
131021             return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members);
131022         }
131023         function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs) {
131024             var importAdder = codefix.createImportAdder(declSourceFile, context.program, context.preferences, context.host);
131025             var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, typeDecl, importAdder);
131026             var containingMethodDeclaration = ts.getAncestor(callExpression, 161 /* MethodDeclaration */);
131027             if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) {
131028                 changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration);
131029             }
131030             else {
131031                 changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration);
131032             }
131033             importAdder.writeFixes(changeTracker);
131034         }
131035         function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) {
131036             /**
131037              * create initializer only literal enum that has string initializer.
131038              * value of initializer is a string literal that equal to name of enum member.
131039              * numeric enum or empty enum will not create initializer.
131040              */
131041             var hasStringInitializer = ts.some(enumDeclaration.members, function (member) {
131042                 var type = checker.getTypeAtLocation(member);
131043                 return !!(type && type.flags & 132 /* StringLike */);
131044             });
131045             var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined);
131046             changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember))), {
131047                 leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
131048                 trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude
131049             });
131050         }
131051     })(codefix = ts.codefix || (ts.codefix = {}));
131052 })(ts || (ts = {}));
131053 /* @internal */
131054 var ts;
131055 (function (ts) {
131056     var codefix;
131057     (function (codefix) {
131058         var fixId = "addMissingNewOperator";
131059         var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
131060         codefix.registerCodeFix({
131061             errorCodes: errorCodes,
131062             getCodeActions: function (context) {
131063                 var sourceFile = context.sourceFile, span = context.span;
131064                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); });
131065                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)];
131066             },
131067             fixIds: [fixId],
131068             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131069                 return addMissingNewOperator(changes, context.sourceFile, diag);
131070             }); },
131071         });
131072         function addMissingNewOperator(changes, sourceFile, span) {
131073             var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression);
131074             var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments);
131075             changes.replaceNode(sourceFile, call, newExpression);
131076         }
131077         function findAncestorMatchingSpan(sourceFile, span) {
131078             var token = ts.getTokenAtPosition(sourceFile, span.start);
131079             var end = ts.textSpanEnd(span);
131080             while (token.end < end) {
131081                 token = token.parent;
131082             }
131083             return token;
131084         }
131085     })(codefix = ts.codefix || (ts.codefix = {}));
131086 })(ts || (ts = {}));
131087 /* @internal */
131088 var ts;
131089 (function (ts) {
131090     var codefix;
131091     (function (codefix) {
131092         var fixName = "fixCannotFindModule";
131093         var fixIdInstallTypesPackage = "installTypesPackage";
131094         var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code;
131095         var errorCodes = [
131096             errorCodeCannotFindModule,
131097             ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code,
131098         ];
131099         codefix.registerCodeFix({
131100             errorCodes: errorCodes,
131101             getCodeActions: function (context) {
131102                 var host = context.host, sourceFile = context.sourceFile, start = context.span.start;
131103                 var packageName = tryGetImportedPackageName(sourceFile, start);
131104                 if (packageName === undefined)
131105                     return undefined;
131106                 var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode);
131107                 return typesPackageName === undefined
131108                     ? []
131109                     : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))];
131110             },
131111             fixIds: [fixIdInstallTypesPackage],
131112             getAllCodeActions: function (context) {
131113                 return codefix.codeFixAll(context, errorCodes, function (_changes, diag, commands) {
131114                     var packageName = tryGetImportedPackageName(diag.file, diag.start);
131115                     if (packageName === undefined)
131116                         return undefined;
131117                     switch (context.fixId) {
131118                         case fixIdInstallTypesPackage: {
131119                             var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code);
131120                             if (pkg) {
131121                                 commands.push(getInstallCommand(diag.file.fileName, pkg));
131122                             }
131123                             break;
131124                         }
131125                         default:
131126                             ts.Debug.fail("Bad fixId: " + context.fixId);
131127                     }
131128                 });
131129             },
131130         });
131131         function getInstallCommand(fileName, packageName) {
131132             return { type: "install package", file: fileName, packageName: packageName };
131133         }
131134         function tryGetImportedPackageName(sourceFile, pos) {
131135             var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text;
131136             var packageName = ts.parsePackageName(moduleName).packageName;
131137             return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName;
131138         }
131139         function getTypesPackageNameToInstall(packageName, host, diagCode) {
131140             return diagCode === errorCodeCannotFindModule
131141                 ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined)
131142                 : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217
131143         }
131144     })(codefix = ts.codefix || (ts.codefix = {}));
131145 })(ts || (ts = {}));
131146 /* @internal */
131147 var ts;
131148 (function (ts) {
131149     var codefix;
131150     (function (codefix) {
131151         var errorCodes = [
131152             ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code,
131153             ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code,
131154         ];
131155         var fixId = "fixClassDoesntImplementInheritedAbstractMember";
131156         codefix.registerCodeFix({
131157             errorCodes: errorCodes,
131158             getCodeActions: function (context) {
131159                 var sourceFile = context.sourceFile, span = context.span;
131160                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
131161                     return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences);
131162                 });
131163                 return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)];
131164             },
131165             fixIds: [fixId],
131166             getAllCodeActions: function (context) {
131167                 var seenClassDeclarations = ts.createMap();
131168                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131169                     var classDeclaration = getClass(diag.file, diag.start);
131170                     if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
131171                         addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences);
131172                     }
131173                 });
131174             },
131175         });
131176         function getClass(sourceFile, pos) {
131177             // Token is the identifier in the case of a class declaration
131178             // or the class keyword token in the case of a class expression.
131179             var token = ts.getTokenAtPosition(sourceFile, pos);
131180             return ts.cast(token.parent, ts.isClassLike);
131181         }
131182         function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) {
131183             var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration);
131184             var checker = context.program.getTypeChecker();
131185             var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
131186             // Note that this is ultimately derived from a map indexed by symbol names,
131187             // so duplicates cannot occur.
131188             var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);
131189             var importAdder = codefix.createImportAdder(sourceFile, context.program, preferences, context.host);
131190             codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, importAdder, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); });
131191             importAdder.writeFixes(changeTracker);
131192         }
131193         function symbolPointsToNonPrivateAndAbstractMember(symbol) {
131194             // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files
131195             // (now named `codeFixClassExtendAbstractPrivateProperty.ts`)
131196             var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations()));
131197             return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */);
131198         }
131199     })(codefix = ts.codefix || (ts.codefix = {}));
131200 })(ts || (ts = {}));
131201 /* @internal */
131202 var ts;
131203 (function (ts) {
131204     var codefix;
131205     (function (codefix) {
131206         var fixId = "classSuperMustPrecedeThisAccess";
131207         var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code];
131208         codefix.registerCodeFix({
131209             errorCodes: errorCodes,
131210             getCodeActions: function (context) {
131211                 var sourceFile = context.sourceFile, span = context.span;
131212                 var nodes = getNodes(sourceFile, span.start);
131213                 if (!nodes)
131214                     return undefined;
131215                 var constructor = nodes.constructor, superCall = nodes.superCall;
131216                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); });
131217                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)];
131218             },
131219             fixIds: [fixId],
131220             getAllCodeActions: function (context) {
131221                 var sourceFile = context.sourceFile;
131222                 var seenClasses = ts.createMap(); // Ensure we only do this once per class.
131223                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131224                     var nodes = getNodes(diag.file, diag.start);
131225                     if (!nodes)
131226                         return;
131227                     var constructor = nodes.constructor, superCall = nodes.superCall;
131228                     if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) {
131229                         doChange(changes, sourceFile, constructor, superCall);
131230                     }
131231                 });
131232             },
131233         });
131234         function doChange(changes, sourceFile, constructor, superCall) {
131235             changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall);
131236             changes.delete(sourceFile, superCall);
131237         }
131238         function getNodes(sourceFile, pos) {
131239             var token = ts.getTokenAtPosition(sourceFile, pos);
131240             if (token.kind !== 104 /* ThisKeyword */)
131241                 return undefined;
131242             var constructor = ts.getContainingFunction(token);
131243             var superCall = findSuperCall(constructor.body);
131244             // figure out if the `this` access is actually inside the supercall
131245             // i.e. super(this.a), since in that case we won't suggest a fix
131246             return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined;
131247         }
131248         function findSuperCall(n) {
131249             return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression)
131250                 ? n
131251                 : ts.isFunctionLike(n)
131252                     ? undefined
131253                     : ts.forEachChild(n, findSuperCall);
131254         }
131255     })(codefix = ts.codefix || (ts.codefix = {}));
131256 })(ts || (ts = {}));
131257 /* @internal */
131258 var ts;
131259 (function (ts) {
131260     var codefix;
131261     (function (codefix) {
131262         var fixId = "constructorForDerivedNeedSuperCall";
131263         var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code];
131264         codefix.registerCodeFix({
131265             errorCodes: errorCodes,
131266             getCodeActions: function (context) {
131267                 var sourceFile = context.sourceFile, span = context.span;
131268                 var ctr = getNode(sourceFile, span.start);
131269                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); });
131270                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)];
131271             },
131272             fixIds: [fixId],
131273             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131274                 return doChange(changes, context.sourceFile, getNode(diag.file, diag.start));
131275             }); },
131276         });
131277         function getNode(sourceFile, pos) {
131278             var token = ts.getTokenAtPosition(sourceFile, pos);
131279             ts.Debug.assert(ts.isConstructorDeclaration(token.parent), "token should be at the constructor declaration");
131280             return token.parent;
131281         }
131282         function doChange(changes, sourceFile, ctr) {
131283             var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray));
131284             changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall);
131285         }
131286     })(codefix = ts.codefix || (ts.codefix = {}));
131287 })(ts || (ts = {}));
131288 /* @internal */
131289 var ts;
131290 (function (ts) {
131291     var codefix;
131292     (function (codefix) {
131293         var fixId = "enableExperimentalDecorators";
131294         var errorCodes = [
131295             ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning.code
131296         ];
131297         codefix.registerCodeFix({
131298             errorCodes: errorCodes,
131299             getCodeActions: function (context) {
131300                 var configFile = context.program.getCompilerOptions().configFile;
131301                 if (configFile === undefined) {
131302                     return undefined;
131303                 }
131304                 var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return doChange(changeTracker, configFile); });
131305                 return [codefix.createCodeFixActionWithoutFixAll(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)];
131306             },
131307             fixIds: [fixId],
131308             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes) {
131309                 var configFile = context.program.getCompilerOptions().configFile;
131310                 if (configFile === undefined) {
131311                     return undefined;
131312                 }
131313                 doChange(changes, configFile);
131314             }); },
131315         });
131316         function doChange(changeTracker, configFile) {
131317             codefix.setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", ts.createTrue());
131318         }
131319     })(codefix = ts.codefix || (ts.codefix = {}));
131320 })(ts || (ts = {}));
131321 /* @internal */
131322 var ts;
131323 (function (ts) {
131324     var codefix;
131325     (function (codefix) {
131326         var fixID = "fixEnableJsxFlag";
131327         var errorCodes = [ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code];
131328         codefix.registerCodeFix({
131329             errorCodes: errorCodes,
131330             getCodeActions: function (context) {
131331                 var configFile = context.program.getCompilerOptions().configFile;
131332                 if (configFile === undefined) {
131333                     return undefined;
131334                 }
131335                 var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) {
131336                     return doChange(changeTracker, configFile);
131337                 });
131338                 return [
131339                     codefix.createCodeFixActionWithoutFixAll(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file)
131340                 ];
131341             },
131342             fixIds: [fixID],
131343             getAllCodeActions: function (context) {
131344                 return codefix.codeFixAll(context, errorCodes, function (changes) {
131345                     var configFile = context.program.getCompilerOptions().configFile;
131346                     if (configFile === undefined) {
131347                         return undefined;
131348                     }
131349                     doChange(changes, configFile);
131350                 });
131351             }
131352         });
131353         function doChange(changeTracker, configFile) {
131354             codefix.setJsonCompilerOptionValue(changeTracker, configFile, "jsx", ts.createStringLiteral("react"));
131355         }
131356     })(codefix = ts.codefix || (ts.codefix = {}));
131357 })(ts || (ts = {}));
131358 /* @internal */
131359 var ts;
131360 (function (ts) {
131361     var codefix;
131362     (function (codefix) {
131363         codefix.registerCodeFix({
131364             errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code],
131365             getCodeActions: function (context) {
131366                 var compilerOptions = context.program.getCompilerOptions();
131367                 var configFile = compilerOptions.configFile;
131368                 if (configFile === undefined) {
131369                     return undefined;
131370                 }
131371                 var codeFixes = [];
131372                 var moduleKind = ts.getEmitModuleKind(compilerOptions);
131373                 var moduleOutOfRange = moduleKind >= ts.ModuleKind.ES2015 && moduleKind < ts.ModuleKind.ESNext;
131374                 if (moduleOutOfRange) {
131375                     var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
131376                         codefix.setJsonCompilerOptionValue(changes, configFile, "module", ts.createStringLiteral("esnext"));
131377                     });
131378                     codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ts.Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"]));
131379                 }
131380                 var target = ts.getEmitScriptTarget(compilerOptions);
131381                 var targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */;
131382                 if (targetOutOfRange) {
131383                     var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) {
131384                         var configObject = ts.getTsConfigObjectLiteralExpression(configFile);
131385                         if (!configObject)
131386                             return;
131387                         var options = [["target", ts.createStringLiteral("es2017")]];
131388                         if (moduleKind === ts.ModuleKind.CommonJS) {
131389                             // Ensure we preserve the default module kind (commonjs), as targets >= ES2015 have a default module kind of es2015.
131390                             options.push(["module", ts.createStringLiteral("commonjs")]);
131391                         }
131392                         codefix.setJsonCompilerOptionValues(tracker, configFile, options);
131393                     });
131394                     codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ts.Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"]));
131395                 }
131396                 return codeFixes.length ? codeFixes : undefined;
131397             }
131398         });
131399     })(codefix = ts.codefix || (ts.codefix = {}));
131400 })(ts || (ts = {}));
131401 /* @internal */
131402 var ts;
131403 (function (ts) {
131404     var codefix;
131405     (function (codefix) {
131406         var fixId = "extendsInterfaceBecomesImplements";
131407         var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
131408         codefix.registerCodeFix({
131409             errorCodes: errorCodes,
131410             getCodeActions: function (context) {
131411                 var sourceFile = context.sourceFile;
131412                 var nodes = getNodes(sourceFile, context.span.start);
131413                 if (!nodes)
131414                     return undefined;
131415                 var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses;
131416                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); });
131417                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)];
131418             },
131419             fixIds: [fixId],
131420             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131421                 var nodes = getNodes(diag.file, diag.start);
131422                 if (nodes)
131423                     doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses);
131424             }); },
131425         });
131426         function getNodes(sourceFile, pos) {
131427             var token = ts.getTokenAtPosition(sourceFile, pos);
131428             var heritageClauses = ts.getContainingClass(token).heritageClauses;
131429             var extendsToken = heritageClauses[0].getFirstToken();
131430             return extendsToken.kind === 90 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined;
131431         }
131432         function doChanges(changes, sourceFile, extendsToken, heritageClauses) {
131433             changes.replaceNode(sourceFile, extendsToken, ts.createToken(113 /* ImplementsKeyword */));
131434             // If there is already an implements clause, replace the implements keyword with a comma.
131435             if (heritageClauses.length === 2 &&
131436                 heritageClauses[0].token === 90 /* ExtendsKeyword */ &&
131437                 heritageClauses[1].token === 113 /* ImplementsKeyword */) {
131438                 var implementsToken = heritageClauses[1].getFirstToken();
131439                 var implementsFullStart = implementsToken.getFullStart();
131440                 changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */));
131441                 // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive.
131442                 // (Trailing because leading might be indentation, which is more sensitive.)
131443                 var text = sourceFile.text;
131444                 var end = implementsToken.end;
131445                 while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) {
131446                     end++;
131447                 }
131448                 changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end });
131449             }
131450         }
131451     })(codefix = ts.codefix || (ts.codefix = {}));
131452 })(ts || (ts = {}));
131453 /* @internal */
131454 var ts;
131455 (function (ts) {
131456     var codefix;
131457     (function (codefix) {
131458         var fixId = "forgottenThisPropertyAccess";
131459         var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code;
131460         var errorCodes = [
131461             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
131462             ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code,
131463             didYouMeanStaticMemberCode,
131464         ];
131465         codefix.registerCodeFix({
131466             errorCodes: errorCodes,
131467             getCodeActions: function (context) {
131468                 var sourceFile = context.sourceFile;
131469                 var info = getInfo(sourceFile, context.span.start, context.errorCode);
131470                 if (!info) {
131471                     return undefined;
131472                 }
131473                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
131474                 return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)];
131475             },
131476             fixIds: [fixId],
131477             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131478                 var info = getInfo(diag.file, diag.start, diag.code);
131479                 if (info)
131480                     doChange(changes, context.sourceFile, info);
131481             }); },
131482         });
131483         function getInfo(sourceFile, pos, diagCode) {
131484             var node = ts.getTokenAtPosition(sourceFile, pos);
131485             if (ts.isIdentifier(node)) {
131486                 return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined };
131487             }
131488         }
131489         function doChange(changes, sourceFile, _a) {
131490             var node = _a.node, className = _a.className;
131491             // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper
131492             ts.suppressLeadingAndTrailingTrivia(node);
131493             changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node));
131494         }
131495     })(codefix = ts.codefix || (ts.codefix = {}));
131496 })(ts || (ts = {}));
131497 /* @internal */
131498 var ts;
131499 (function (ts) {
131500     var codefix;
131501     (function (codefix) {
131502         var fixIdExpression = "fixInvalidJsxCharacters_expression";
131503         var fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity";
131504         var errorCodes = [
131505             ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt.code,
131506             ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code
131507         ];
131508         codefix.registerCodeFix({
131509             errorCodes: errorCodes,
131510             fixIds: [fixIdExpression, fixIdHtmlEntity],
131511             getCodeActions: function (context) {
131512                 var sourceFile = context.sourceFile, preferences = context.preferences, span = context.span;
131513                 var changeToExpression = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, preferences, sourceFile, span.start, /* useHtmlEntity */ false); });
131514                 var changeToHtmlEntity = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, preferences, sourceFile, span.start, /* useHtmlEntity */ true); });
131515                 return [
131516                     codefix.createCodeFixAction(fixIdExpression, changeToExpression, ts.Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, ts.Diagnostics.Wrap_all_invalid_characters_in_an_expression_container),
131517                     codefix.createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, ts.Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, ts.Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code)
131518                 ];
131519             },
131520             getAllCodeActions: function (context) {
131521                 return codefix.codeFixAll(context, errorCodes, function (changes, diagnostic) { return doChange(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity); });
131522             }
131523         });
131524         var htmlEntity = {
131525             ">": "&gt;",
131526             "}": "&rbrace;",
131527         };
131528         function isValidCharacter(character) {
131529             return ts.hasProperty(htmlEntity, character);
131530         }
131531         function doChange(changes, preferences, sourceFile, start, useHtmlEntity) {
131532             var character = sourceFile.getText()[start];
131533             // sanity check
131534             if (!isValidCharacter(character)) {
131535                 return;
131536             }
131537             var replacement = useHtmlEntity ? htmlEntity[character] : "{" + ts.quote(character, preferences) + "}";
131538             changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 1 }, replacement);
131539         }
131540     })(codefix = ts.codefix || (ts.codefix = {}));
131541 })(ts || (ts = {}));
131542 /* @internal */
131543 var ts;
131544 (function (ts) {
131545     var codefix;
131546     (function (codefix) {
131547         var fixName = "unusedIdentifier";
131548         var fixIdPrefix = "unusedIdentifier_prefix";
131549         var fixIdDelete = "unusedIdentifier_delete";
131550         var fixIdInfer = "unusedIdentifier_infer";
131551         var errorCodes = [
131552             ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code,
131553             ts.Diagnostics._0_is_declared_but_never_used.code,
131554             ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
131555             ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
131556             ts.Diagnostics.All_destructured_elements_are_unused.code,
131557             ts.Diagnostics.All_variables_are_unused.code,
131558             ts.Diagnostics.All_type_parameters_are_unused.code,
131559         ];
131560         codefix.registerCodeFix({
131561             errorCodes: errorCodes,
131562             getCodeActions: function (context) {
131563                 var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program;
131564                 var checker = program.getTypeChecker();
131565                 var sourceFiles = program.getSourceFiles();
131566                 var token = ts.getTokenAtPosition(sourceFile, context.span.start);
131567                 if (ts.isJSDocTemplateTag(token)) {
131568                     return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)];
131569                 }
131570                 if (token.kind === 29 /* LessThanToken */) {
131571                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); });
131572                     return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)];
131573                 }
131574                 var importDecl = tryGetFullImport(token);
131575                 if (importDecl) {
131576                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); });
131577                     return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])];
131578                 }
131579                 var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) {
131580                     return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false);
131581                 });
131582                 if (delDestructure.length) {
131583                     return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)];
131584                 }
131585                 var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); });
131586                 if (delVar.length) {
131587                     return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)];
131588                 }
131589                 var result = [];
131590                 if (token.kind === 132 /* InferKeyword */) {
131591                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); });
131592                     var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text;
131593                     result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown));
131594                 }
131595                 else {
131596                     var deletion = ts.textChanges.ChangeTracker.with(context, function (t) {
131597                         return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false);
131598                     });
131599                     if (deletion.length) {
131600                         var name = ts.isComputedPropertyName(token.parent) ? token.parent : token;
131601                         result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)]));
131602                     }
131603                 }
131604                 var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); });
131605                 if (prefix.length) {
131606                     result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible));
131607                 }
131608                 return result;
131609             },
131610             fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer],
131611             getAllCodeActions: function (context) {
131612                 var sourceFile = context.sourceFile, program = context.program;
131613                 var checker = program.getTypeChecker();
131614                 var sourceFiles = program.getSourceFiles();
131615                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131616                     var token = ts.getTokenAtPosition(sourceFile, diag.start);
131617                     switch (context.fixId) {
131618                         case fixIdPrefix:
131619                             tryPrefixDeclaration(changes, diag.code, sourceFile, token);
131620                             break;
131621                         case fixIdDelete: {
131622                             if (token.kind === 132 /* InferKeyword */)
131623                                 break; // Can't delete
131624                             var importDecl = tryGetFullImport(token);
131625                             if (importDecl) {
131626                                 changes.delete(sourceFile, importDecl);
131627                             }
131628                             else if (ts.isJSDocTemplateTag(token)) {
131629                                 changes.delete(sourceFile, token);
131630                             }
131631                             else if (token.kind === 29 /* LessThanToken */) {
131632                                 deleteTypeParameters(changes, sourceFile, token);
131633                             }
131634                             else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) &&
131635                                 !tryDeleteFullVariableStatement(sourceFile, token, changes)) {
131636                                 tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true);
131637                             }
131638                             break;
131639                         }
131640                         case fixIdInfer:
131641                             if (token.kind === 132 /* InferKeyword */) {
131642                                 changeInferToUnknown(changes, sourceFile, token);
131643                             }
131644                             break;
131645                         default:
131646                             ts.Debug.fail(JSON.stringify(context.fixId));
131647                     }
131648                 });
131649             },
131650         });
131651         function changeInferToUnknown(changes, sourceFile, token) {
131652             changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(148 /* UnknownKeyword */));
131653         }
131654         function createDeleteFix(changes, diag) {
131655             return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations);
131656         }
131657         function deleteTypeParameters(changes, sourceFile, token) {
131658             changes.delete(sourceFile, ts.Debug.checkDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist"));
131659         }
131660         // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
131661         function tryGetFullImport(token) {
131662             return token.kind === 96 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined;
131663         }
131664         function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
131665             if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent))
131666                 return false;
131667             var decl = token.parent.parent;
131668             if (decl.kind === 156 /* Parameter */) {
131669                 tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll);
131670             }
131671             else {
131672                 changes.delete(sourceFile, decl);
131673             }
131674             return true;
131675         }
131676         function tryDeleteFullVariableStatement(sourceFile, token, changes) {
131677             var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList);
131678             if (declarationList && declarationList.getChildren(sourceFile)[0] === token) {
131679                 changes.delete(sourceFile, declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList);
131680                 return true;
131681             }
131682             return false;
131683         }
131684         function tryPrefixDeclaration(changes, errorCode, sourceFile, token) {
131685             // Don't offer to prefix a property.
131686             if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code)
131687                 return;
131688             if (token.kind === 132 /* InferKeyword */) {
131689                 token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name;
131690             }
131691             if (ts.isIdentifier(token) && canPrefix(token)) {
131692                 changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text));
131693                 if (ts.isParameter(token.parent)) {
131694                     ts.getJSDocParameterTags(token.parent).forEach(function (tag) {
131695                         if (ts.isIdentifier(tag.name)) {
131696                             changes.replaceNode(sourceFile, tag.name, ts.createIdentifier("_" + tag.name.text));
131697                         }
131698                     });
131699                 }
131700             }
131701         }
131702         function canPrefix(token) {
131703             switch (token.parent.kind) {
131704                 case 156 /* Parameter */:
131705                 case 155 /* TypeParameter */:
131706                     return true;
131707                 case 242 /* VariableDeclaration */: {
131708                     var varDecl = token.parent;
131709                     switch (varDecl.parent.parent.kind) {
131710                         case 232 /* ForOfStatement */:
131711                         case 231 /* ForInStatement */:
131712                             return true;
131713                     }
131714                 }
131715             }
131716             return false;
131717         }
131718         function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) {
131719             tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll);
131720             if (ts.isIdentifier(token))
131721                 deleteAssignments(changes, sourceFile, token, checker);
131722         }
131723         function deleteAssignments(changes, sourceFile, token, checker) {
131724             ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) {
131725                 if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref)
131726                     ref = ref.parent;
131727                 if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) {
131728                     changes.delete(sourceFile, ref.parent.parent);
131729                 }
131730             });
131731         }
131732         function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
131733             var parent = token.parent;
131734             if (ts.isParameter(parent)) {
131735                 tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll);
131736             }
131737             else {
131738                 changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent);
131739             }
131740         }
131741         function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) {
131742             if (mayDeleteParameter(p, checker, isFixAll)) {
131743                 if (p.modifiers && p.modifiers.length > 0
131744                     && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) {
131745                     p.modifiers.forEach(function (modifier) {
131746                         changes.deleteModifier(sourceFile, modifier);
131747                     });
131748                 }
131749                 else {
131750                     changes.delete(sourceFile, p);
131751                     deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker);
131752                 }
131753             }
131754         }
131755         function mayDeleteParameter(p, checker, isFixAll) {
131756             var parent = p.parent;
131757             switch (parent.kind) {
131758                 case 161 /* MethodDeclaration */:
131759                     // Don't remove a parameter if this overrides something.
131760                     var symbol = checker.getSymbolAtLocation(parent.name);
131761                     if (ts.isMemberSymbolInBaseType(symbol, checker))
131762                         return false;
131763                 // falls through
131764                 case 162 /* Constructor */:
131765                 case 244 /* FunctionDeclaration */:
131766                     return true;
131767                 case 201 /* FunctionExpression */:
131768                 case 202 /* ArrowFunction */: {
131769                     // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused.
131770                     var parameters = parent.parameters;
131771                     var index = parameters.indexOf(p);
131772                     ts.Debug.assert(index !== -1, "The parameter should already be in the list");
131773                     return isFixAll
131774                         ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 75 /* Identifier */ && !p.symbol.isReferenced; })
131775                         : index === parameters.length - 1;
131776                 }
131777                 case 164 /* SetAccessor */:
131778                     // Setter must have a parameter
131779                     return false;
131780                 default:
131781                     return ts.Debug.failBadSyntaxKind(parent);
131782             }
131783         }
131784         function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) {
131785             ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) {
131786                 var index = deletedParameter.parent.parameters.indexOf(deletedParameter);
131787                 if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments.
131788                     changes.delete(sourceFile, call.arguments[index]);
131789                 }
131790             });
131791         }
131792     })(codefix = ts.codefix || (ts.codefix = {}));
131793 })(ts || (ts = {}));
131794 /* @internal */
131795 var ts;
131796 (function (ts) {
131797     var codefix;
131798     (function (codefix) {
131799         var fixId = "fixUnreachableCode";
131800         var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code];
131801         codefix.registerCodeFix({
131802             errorCodes: errorCodes,
131803             getCodeActions: function (context) {
131804                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length, context.errorCode); });
131805                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)];
131806             },
131807             fixIds: [fixId],
131808             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length, diag.code); }); },
131809         });
131810         function doChange(changes, sourceFile, start, length, errorCode) {
131811             var token = ts.getTokenAtPosition(sourceFile, start);
131812             var statement = ts.findAncestor(token, ts.isStatement);
131813             if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) {
131814                 var logData = JSON.stringify({
131815                     statementKind: ts.Debug.formatSyntaxKind(statement.kind),
131816                     tokenKind: ts.Debug.formatSyntaxKind(token.kind),
131817                     errorCode: errorCode,
131818                     start: start,
131819                     length: length
131820                 });
131821                 ts.Debug.fail("Token and statement should start at the same point. " + logData);
131822             }
131823             var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent;
131824             if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) {
131825                 switch (container.kind) {
131826                     case 227 /* IfStatement */:
131827                         if (container.elseStatement) {
131828                             if (ts.isBlock(statement.parent)) {
131829                                 break;
131830                             }
131831                             else {
131832                                 changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray));
131833                             }
131834                             return;
131835                         }
131836                     // falls through
131837                     case 229 /* WhileStatement */:
131838                     case 230 /* ForStatement */:
131839                         changes.delete(sourceFile, container);
131840                         return;
131841                 }
131842             }
131843             if (ts.isBlock(statement.parent)) {
131844                 var end_3 = start + length;
131845                 var lastStatement = ts.Debug.checkDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_3; }), "Some statement should be last");
131846                 changes.deleteNodeRange(sourceFile, statement, lastStatement);
131847             }
131848             else {
131849                 changes.delete(sourceFile, statement);
131850             }
131851         }
131852         function lastWhere(a, pred) {
131853             var last;
131854             for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
131855                 var value = a_1[_i];
131856                 if (!pred(value))
131857                     break;
131858                 last = value;
131859             }
131860             return last;
131861         }
131862     })(codefix = ts.codefix || (ts.codefix = {}));
131863 })(ts || (ts = {}));
131864 /* @internal */
131865 var ts;
131866 (function (ts) {
131867     var codefix;
131868     (function (codefix) {
131869         var fixId = "fixUnusedLabel";
131870         var errorCodes = [ts.Diagnostics.Unused_label.code];
131871         codefix.registerCodeFix({
131872             errorCodes: errorCodes,
131873             getCodeActions: function (context) {
131874                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
131875                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
131876             },
131877             fixIds: [fixId],
131878             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
131879         });
131880         function doChange(changes, sourceFile, start) {
131881             var token = ts.getTokenAtPosition(sourceFile, start);
131882             var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
131883             var pos = token.getStart(sourceFile);
131884             var statementPos = labeledStatement.statement.getStart(sourceFile);
131885             // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
131886             var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
131887                 : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 58 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
131888             changes.deleteRange(sourceFile, { pos: pos, end: end });
131889         }
131890     })(codefix = ts.codefix || (ts.codefix = {}));
131891 })(ts || (ts = {}));
131892 /* @internal */
131893 var ts;
131894 (function (ts) {
131895     var codefix;
131896     (function (codefix) {
131897         var fixIdPlain = "fixJSDocTypes_plain";
131898         var fixIdNullable = "fixJSDocTypes_nullable";
131899         var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code];
131900         codefix.registerCodeFix({
131901             errorCodes: errorCodes,
131902             getCodeActions: function (context) {
131903                 var sourceFile = context.sourceFile;
131904                 var checker = context.program.getTypeChecker();
131905                 var info = getInfo(sourceFile, context.span.start, checker);
131906                 if (!info)
131907                     return undefined;
131908                 var typeNode = info.typeNode, type = info.type;
131909                 var original = typeNode.getText(sourceFile);
131910                 var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
131911                 if (typeNode.kind === 297 /* JSDocNullableType */) {
131912                     // for nullable types, suggest the flow-compatible `T | null | undefined`
131913                     // in addition to the jsdoc/closure-compatible `T | null`
131914                     actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
131915                 }
131916                 return actions;
131917                 function fix(type, fixId, fixAllDescription) {
131918                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); });
131919                     return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription);
131920                 }
131921             },
131922             fixIds: [fixIdPlain, fixIdNullable],
131923             getAllCodeActions: function (context) {
131924                 var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile;
131925                 var checker = program.getTypeChecker();
131926                 return codefix.codeFixAll(context, errorCodes, function (changes, err) {
131927                     var info = getInfo(err.file, err.start, checker);
131928                     if (!info)
131929                         return;
131930                     var typeNode = info.typeNode, type = info.type;
131931                     var fixedType = typeNode.kind === 297 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
131932                     doChange(changes, sourceFile, typeNode, fixedType, checker);
131933                 });
131934             }
131935         });
131936         function doChange(changes, sourceFile, oldTypeNode, newType, checker) {
131937             changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)); // TODO: GH#18217
131938         }
131939         function getInfo(sourceFile, pos, checker) {
131940             var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer);
131941             var typeNode = decl && decl.type;
131942             return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) };
131943         }
131944         function isTypeContainer(node) {
131945             // NOTE: Some locations are not handled yet:
131946             // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments
131947             switch (node.kind) {
131948                 case 217 /* AsExpression */:
131949                 case 165 /* CallSignature */:
131950                 case 166 /* ConstructSignature */:
131951                 case 244 /* FunctionDeclaration */:
131952                 case 163 /* GetAccessor */:
131953                 case 167 /* IndexSignature */:
131954                 case 186 /* MappedType */:
131955                 case 161 /* MethodDeclaration */:
131956                 case 160 /* MethodSignature */:
131957                 case 156 /* Parameter */:
131958                 case 159 /* PropertyDeclaration */:
131959                 case 158 /* PropertySignature */:
131960                 case 164 /* SetAccessor */:
131961                 case 247 /* TypeAliasDeclaration */:
131962                 case 199 /* TypeAssertionExpression */:
131963                 case 242 /* VariableDeclaration */:
131964                     return true;
131965                 default:
131966                     return false;
131967             }
131968         }
131969     })(codefix = ts.codefix || (ts.codefix = {}));
131970 })(ts || (ts = {}));
131971 /* @internal */
131972 var ts;
131973 (function (ts) {
131974     var codefix;
131975     (function (codefix) {
131976         var fixId = "fixMissingCallParentheses";
131977         var errorCodes = [
131978             ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead.code,
131979         ];
131980         codefix.registerCodeFix({
131981             errorCodes: errorCodes,
131982             fixIds: [fixId],
131983             getCodeActions: function (context) {
131984                 var sourceFile = context.sourceFile, span = context.span;
131985                 var callName = getCallName(sourceFile, span.start);
131986                 if (!callName)
131987                     return;
131988                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, callName); });
131989                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_call_parentheses, fixId, ts.Diagnostics.Add_all_missing_call_parentheses)];
131990             },
131991             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131992                 var callName = getCallName(diag.file, diag.start);
131993                 if (callName)
131994                     doChange(changes, diag.file, callName);
131995             }); }
131996         });
131997         function doChange(changes, sourceFile, name) {
131998             changes.replaceNodeWithText(sourceFile, name, name.text + "()");
131999         }
132000         function getCallName(sourceFile, start) {
132001             var token = ts.getTokenAtPosition(sourceFile, start);
132002             if (ts.isPropertyAccessExpression(token.parent)) {
132003                 var current = token.parent;
132004                 while (ts.isPropertyAccessExpression(current.parent)) {
132005                     current = current.parent;
132006                 }
132007                 return current.name;
132008             }
132009             if (ts.isIdentifier(token)) {
132010                 return token;
132011             }
132012             return undefined;
132013         }
132014     })(codefix = ts.codefix || (ts.codefix = {}));
132015 })(ts || (ts = {}));
132016 /* @internal */
132017 var ts;
132018 (function (ts) {
132019     var codefix;
132020     (function (codefix) {
132021         var fixId = "fixAwaitInSyncFunction";
132022         var errorCodes = [
132023             ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
132024             ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code,
132025         ];
132026         codefix.registerCodeFix({
132027             errorCodes: errorCodes,
132028             getCodeActions: function (context) {
132029                 var sourceFile = context.sourceFile, span = context.span;
132030                 var nodes = getNodes(sourceFile, span.start);
132031                 if (!nodes)
132032                     return undefined;
132033                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); });
132034                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)];
132035             },
132036             fixIds: [fixId],
132037             getAllCodeActions: function (context) {
132038                 var seen = ts.createMap();
132039                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
132040                     var nodes = getNodes(diag.file, diag.start);
132041                     if (!nodes || !ts.addToSeen(seen, ts.getNodeId(nodes.insertBefore)))
132042                         return;
132043                     doChange(changes, context.sourceFile, nodes);
132044                 });
132045             },
132046         });
132047         function getReturnType(expr) {
132048             if (expr.type) {
132049                 return expr.type;
132050             }
132051             if (ts.isVariableDeclaration(expr.parent) &&
132052                 expr.parent.type &&
132053                 ts.isFunctionTypeNode(expr.parent.type)) {
132054                 return expr.parent.type.type;
132055             }
132056         }
132057         function getNodes(sourceFile, start) {
132058             var token = ts.getTokenAtPosition(sourceFile, start);
132059             var containingFunction = ts.getContainingFunction(token);
132060             if (!containingFunction) {
132061                 return;
132062             }
132063             var insertBefore;
132064             switch (containingFunction.kind) {
132065                 case 161 /* MethodDeclaration */:
132066                     insertBefore = containingFunction.name;
132067                     break;
132068                 case 244 /* FunctionDeclaration */:
132069                 case 201 /* FunctionExpression */:
132070                     insertBefore = ts.findChildOfKind(containingFunction, 94 /* FunctionKeyword */, sourceFile);
132071                     break;
132072                 case 202 /* ArrowFunction */:
132073                     insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters);
132074                     break;
132075                 default:
132076                     return;
132077             }
132078             return insertBefore && {
132079                 insertBefore: insertBefore,
132080                 returnType: getReturnType(containingFunction)
132081             };
132082         }
132083         function doChange(changes, sourceFile, _a) {
132084             var insertBefore = _a.insertBefore, returnType = _a.returnType;
132085             if (returnType) {
132086                 var entityName = ts.getEntityNameFromTypeNode(returnType);
132087                 if (!entityName || entityName.kind !== 75 /* Identifier */ || entityName.text !== "Promise") {
132088                     changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType])));
132089                 }
132090             }
132091             changes.insertModifierBefore(sourceFile, 126 /* AsyncKeyword */, insertBefore);
132092         }
132093     })(codefix = ts.codefix || (ts.codefix = {}));
132094 })(ts || (ts = {}));
132095 /* @internal */
132096 var ts;
132097 (function (ts) {
132098     var codefix;
132099     (function (codefix) {
132100         var fixId = "inferFromUsage";
132101         var errorCodes = [
132102             // Variable declarations
132103             ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code,
132104             // Variable uses
132105             ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code,
132106             // Parameter declarations
132107             ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code,
132108             ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code,
132109             // Get Accessor declarations
132110             ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code,
132111             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code,
132112             // Set Accessor declarations
132113             ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code,
132114             // Property declarations
132115             ts.Diagnostics.Member_0_implicitly_has_an_1_type.code,
132116             //// Suggestions
132117             // Variable declarations
132118             ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code,
132119             // Variable uses
132120             ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
132121             // Parameter declarations
132122             ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
132123             ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code,
132124             // Get Accessor declarations
132125             ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code,
132126             ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code,
132127             // Set Accessor declarations
132128             ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code,
132129             // Property declarations
132130             ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
132131             // Function expressions and declarations
132132             ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code,
132133         ];
132134         codefix.registerCodeFix({
132135             errorCodes: errorCodes,
132136             getCodeActions: function (context) {
132137                 var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, preferences = context.preferences;
132138                 var token = ts.getTokenAtPosition(sourceFile, start);
132139                 var declaration;
132140                 var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, preferences); });
132141                 var name = declaration && ts.getNameOfDeclaration(declaration);
132142                 return !name || changes.length === 0 ? undefined
132143                     : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)];
132144             },
132145             fixIds: [fixId],
132146             getAllCodeActions: function (context) {
132147                 var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, preferences = context.preferences;
132148                 var markSeen = ts.nodeSeenTracker();
132149                 return codefix.codeFixAll(context, errorCodes, function (changes, err) {
132150                     doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences);
132151                 });
132152             },
132153         });
132154         function getDiagnostic(errorCode, token) {
132155             switch (errorCode) {
132156                 case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
132157                 case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
132158                     return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217
132159                 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
132160                 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
132161                     return ts.Diagnostics.Infer_parameter_types_from_usage;
132162                 case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
132163                     return ts.Diagnostics.Infer_this_type_of_0_from_usage;
132164                 default:
132165                     return ts.Diagnostics.Infer_type_of_0_from_usage;
132166             }
132167         }
132168         /** Map suggestion code to error code */
132169         function mapSuggestionDiagnostic(errorCode) {
132170             switch (errorCode) {
132171                 case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code:
132172                     return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code;
132173                 case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
132174                     return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code;
132175                 case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
132176                     return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code;
132177                 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
132178                     return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code;
132179                 case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code:
132180                     return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code;
132181                 case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code:
132182                     return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code;
132183                 case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code:
132184                     return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code;
132185                 case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
132186                     return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code;
132187             }
132188             return errorCode;
132189         }
132190         function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) {
132191             if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 104 /* ThisKeyword */) {
132192                 return undefined;
132193             }
132194             var parent = token.parent;
132195             var importAdder = codefix.createImportAdder(sourceFile, program, preferences, host);
132196             errorCode = mapSuggestionDiagnostic(errorCode);
132197             switch (errorCode) {
132198                 // Variable and Property declarations
132199                 case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code:
132200                 case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
132201                     if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
132202                         annotateVariableDeclaration(changes, importAdder, sourceFile, parent, program, host, cancellationToken);
132203                         importAdder.writeFixes(changes);
132204                         return parent;
132205                     }
132206                     if (ts.isPropertyAccessExpression(parent)) {
132207                         var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
132208                         var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
132209                         if (typeNode) {
132210                             // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
132211                             var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
132212                             addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]);
132213                         }
132214                         importAdder.writeFixes(changes);
132215                         return parent;
132216                     }
132217                     return undefined;
132218                 case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
132219                     var symbol = program.getTypeChecker().getSymbolAtLocation(token);
132220                     if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
132221                         annotateVariableDeclaration(changes, importAdder, sourceFile, symbol.valueDeclaration, program, host, cancellationToken);
132222                         importAdder.writeFixes(changes);
132223                         return symbol.valueDeclaration;
132224                     }
132225                     return undefined;
132226                 }
132227             }
132228             var containingFunction = ts.getContainingFunction(token);
132229             if (containingFunction === undefined) {
132230                 return undefined;
132231             }
132232             var declaration;
132233             switch (errorCode) {
132234                 // Parameter declarations
132235                 case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
132236                     if (ts.isSetAccessorDeclaration(containingFunction)) {
132237                         annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken);
132238                         declaration = containingFunction;
132239                         break;
132240                     }
132241                 // falls through
132242                 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
132243                     if (markSeen(containingFunction)) {
132244                         var param = ts.cast(parent, ts.isParameter);
132245                         annotateParameters(changes, importAdder, sourceFile, param, containingFunction, program, host, cancellationToken);
132246                         declaration = param;
132247                     }
132248                     break;
132249                 // Get Accessor declarations
132250                 case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code:
132251                 case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code:
132252                     if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) {
132253                         annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host);
132254                         declaration = containingFunction;
132255                     }
132256                     break;
132257                 // Set Accessor declarations
132258                 case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
132259                     if (ts.isSetAccessorDeclaration(containingFunction)) {
132260                         annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken);
132261                         declaration = containingFunction;
132262                     }
132263                     break;
132264                 // Function 'this'
132265                 case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
132266                     if (ts.textChanges.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) {
132267                         annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken);
132268                         declaration = containingFunction;
132269                     }
132270                     break;
132271                 default:
132272                     return ts.Debug.fail(String(errorCode));
132273             }
132274             importAdder.writeFixes(changes);
132275             return declaration;
132276         }
132277         function annotateVariableDeclaration(changes, importAdder, sourceFile, declaration, program, host, cancellationToken) {
132278             if (ts.isIdentifier(declaration.name)) {
132279                 annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host);
132280             }
132281         }
132282         function annotateParameters(changes, importAdder, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) {
132283             if (!ts.isIdentifier(parameterDeclaration.name)) {
132284                 return;
132285             }
132286             var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken);
132287             ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match");
132288             if (ts.isInJSFile(containingFunction)) {
132289                 annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host);
132290             }
132291             else {
132292                 var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile);
132293                 if (needParens)
132294                     changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */));
132295                 for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) {
132296                     var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type;
132297                     if (declaration && !declaration.type && !declaration.initializer) {
132298                         annotate(changes, importAdder, sourceFile, declaration, type, program, host);
132299                     }
132300                 }
132301                 if (needParens)
132302                     changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */));
132303             }
132304         }
132305         function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) {
132306             var references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken);
132307             if (!references || !references.length) {
132308                 return;
132309             }
132310             var thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter();
132311             var typeNode = ts.getTypeNodeIfAccessible(thisInference, containingFunction, program, host);
132312             if (!typeNode) {
132313                 return;
132314             }
132315             if (ts.isInJSFile(containingFunction)) {
132316                 annotateJSDocThis(changes, sourceFile, containingFunction, typeNode);
132317             }
132318             else {
132319                 changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode);
132320             }
132321         }
132322         function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) {
132323             addJSDocTags(changes, sourceFile, containingFunction, [
132324                 ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)),
132325             ]);
132326         }
132327         function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) {
132328             var param = ts.firstOrUndefined(setAccessorDeclaration.parameters);
132329             if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) {
132330                 var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken);
132331                 if (type === program.getTypeChecker().getAnyType()) {
132332                     type = inferTypeForVariableFromUsage(param.name, program, cancellationToken);
132333                 }
132334                 if (ts.isInJSFile(setAccessorDeclaration)) {
132335                     annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host);
132336                 }
132337                 else {
132338                     annotate(changes, importAdder, sourceFile, param, type, program, host);
132339                 }
132340             }
132341         }
132342         function annotate(changes, importAdder, sourceFile, declaration, type, program, host) {
132343             var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
132344             if (typeNode) {
132345                 if (ts.isInJSFile(sourceFile) && declaration.kind !== 158 /* PropertySignature */) {
132346                     var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
132347                     if (!parent) {
132348                         return;
132349                     }
132350                     var typeExpression = ts.createJSDocTypeExpression(typeNode);
132351                     var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, "");
132352                     addJSDocTags(changes, sourceFile, parent, [typeTag]);
132353                 }
132354                 else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, type, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) {
132355                     changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
132356                 }
132357             }
132358         }
132359         function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, type, sourceFile, changes, importAdder, scriptTarget) {
132360             var importableReference = codefix.tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget);
132361             if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeReference)) {
132362                 ts.forEach(importableReference.symbols, function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); });
132363                 return true;
132364             }
132365             return false;
132366         }
132367         function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) {
132368             var signature = parameterInferences.length && parameterInferences[0].declaration.parent;
132369             if (!signature) {
132370                 return;
132371             }
132372             var paramTags = ts.mapDefined(parameterInferences, function (inference) {
132373                 var param = inference.declaration;
132374                 // only infer parameters that have (1) no type and (2) an accessible inferred type
132375                 if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
132376                     return;
132377                 var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
132378                 var name = ts.getSynthesizedClone(param.name);
132379                 ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
132380                 return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
132381             });
132382             addJSDocTags(changes, sourceFile, signature, paramTags);
132383         }
132384         function addJSDocTags(changes, sourceFile, parent, newTags) {
132385             var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; });
132386             var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; });
132387             var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) {
132388                 var merged = tryMergeJsdocTags(tag, newTag);
132389                 if (merged)
132390                     oldTags[i] = merged;
132391                 return !!merged;
132392             }); });
132393             var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray(__spreadArrays((oldTags || ts.emptyArray), unmergedNewTags)));
132394             var jsDocNode = parent.kind === 202 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
132395             jsDocNode.jsDoc = parent.jsDoc;
132396             jsDocNode.jsDocCache = parent.jsDocCache;
132397             changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
132398         }
132399         codefix.addJSDocTags = addJSDocTags;
132400         function getJsDocNodeForArrowFunction(signature) {
132401             if (signature.parent.kind === 159 /* PropertyDeclaration */) {
132402                 return signature.parent;
132403             }
132404             return signature.parent.parent;
132405         }
132406         function tryMergeJsdocTags(oldTag, newTag) {
132407             if (oldTag.kind !== newTag.kind) {
132408                 return undefined;
132409             }
132410             switch (oldTag.kind) {
132411                 case 317 /* JSDocParameterTag */: {
132412                     var oldParam = oldTag;
132413                     var newParam = newTag;
132414                     return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
132415                         ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
132416                         : undefined;
132417                 }
132418                 case 318 /* JSDocReturnTag */:
132419                     return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
132420             }
132421         }
132422         function getReferences(token, program, cancellationToken) {
132423             // Position shouldn't matter since token is not a SourceFile.
132424             return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
132425                 return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined;
132426             });
132427         }
132428         function inferTypeForVariableFromUsage(token, program, cancellationToken) {
132429             var references = getReferences(token, program, cancellationToken);
132430             return inferTypeFromReferences(program, references, cancellationToken).single();
132431         }
132432         function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) {
132433             var references = getFunctionReferences(func, sourceFile, program, cancellationToken);
132434             return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) ||
132435                 func.parameters.map(function (p) { return ({
132436                     declaration: p,
132437                     type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType()
132438                 }); });
132439         }
132440         function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) {
132441             var searchToken;
132442             switch (containingFunction.kind) {
132443                 case 162 /* Constructor */:
132444                     searchToken = ts.findChildOfKind(containingFunction, 129 /* ConstructorKeyword */, sourceFile);
132445                     break;
132446                 case 202 /* ArrowFunction */:
132447                 case 201 /* FunctionExpression */:
132448                     var parent = containingFunction.parent;
132449                     searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ?
132450                         parent.name :
132451                         containingFunction.name;
132452                     break;
132453                 case 244 /* FunctionDeclaration */:
132454                 case 161 /* MethodDeclaration */:
132455                     searchToken = containingFunction.name;
132456                     break;
132457             }
132458             if (!searchToken) {
132459                 return undefined;
132460             }
132461             return getReferences(searchToken, program, cancellationToken);
132462         }
132463         function inferTypeFromReferences(program, references, cancellationToken) {
132464             var checker = program.getTypeChecker();
132465             var builtinConstructors = {
132466                 string: function () { return checker.getStringType(); },
132467                 number: function () { return checker.getNumberType(); },
132468                 Array: function (t) { return checker.createArrayType(t); },
132469                 Promise: function (t) { return checker.createPromiseType(t); },
132470             };
132471             var builtins = [
132472                 checker.getStringType(),
132473                 checker.getNumberType(),
132474                 checker.createArrayType(checker.getAnyType()),
132475                 checker.createPromiseType(checker.getAnyType()),
132476             ];
132477             return {
132478                 single: single,
132479                 parameters: parameters,
132480                 thisParameter: thisParameter,
132481             };
132482             function createEmptyUsage() {
132483                 return {
132484                     isNumber: undefined,
132485                     isString: undefined,
132486                     isNumberOrString: undefined,
132487                     candidateTypes: undefined,
132488                     properties: undefined,
132489                     calls: undefined,
132490                     constructs: undefined,
132491                     numberIndex: undefined,
132492                     stringIndex: undefined,
132493                     candidateThisTypes: undefined,
132494                     inferredTypes: undefined,
132495                 };
132496             }
132497             function combineUsages(usages) {
132498                 var combinedProperties = ts.createUnderscoreEscapedMap();
132499                 for (var _i = 0, usages_1 = usages; _i < usages_1.length; _i++) {
132500                     var u = usages_1[_i];
132501                     if (u.properties) {
132502                         u.properties.forEach(function (p, name) {
132503                             if (!combinedProperties.has(name)) {
132504                                 combinedProperties.set(name, []);
132505                             }
132506                             combinedProperties.get(name).push(p);
132507                         });
132508                     }
132509                 }
132510                 var properties = ts.createUnderscoreEscapedMap();
132511                 combinedProperties.forEach(function (ps, name) {
132512                     properties.set(name, combineUsages(ps));
132513                 });
132514                 return {
132515                     isNumber: usages.some(function (u) { return u.isNumber; }),
132516                     isString: usages.some(function (u) { return u.isString; }),
132517                     isNumberOrString: usages.some(function (u) { return u.isNumberOrString; }),
132518                     candidateTypes: ts.flatMap(usages, function (u) { return u.candidateTypes; }),
132519                     properties: properties,
132520                     calls: ts.flatMap(usages, function (u) { return u.calls; }),
132521                     constructs: ts.flatMap(usages, function (u) { return u.constructs; }),
132522                     numberIndex: ts.forEach(usages, function (u) { return u.numberIndex; }),
132523                     stringIndex: ts.forEach(usages, function (u) { return u.stringIndex; }),
132524                     candidateThisTypes: ts.flatMap(usages, function (u) { return u.candidateThisTypes; }),
132525                     inferredTypes: undefined,
132526                 };
132527             }
132528             function single() {
132529                 return combineTypes(inferTypesFromReferencesSingle(references));
132530             }
132531             function parameters(declaration) {
132532                 if (references.length === 0 || !declaration.parameters) {
132533                     return undefined;
132534                 }
132535                 var usage = createEmptyUsage();
132536                 for (var _i = 0, references_2 = references; _i < references_2.length; _i++) {
132537                     var reference = references_2[_i];
132538                     cancellationToken.throwIfCancellationRequested();
132539                     calculateUsageOfNode(reference, usage);
132540                 }
132541                 var calls = __spreadArrays(usage.constructs || [], usage.calls || []);
132542                 return declaration.parameters.map(function (parameter, parameterIndex) {
132543                     var types = [];
132544                     var isRest = ts.isRestParameter(parameter);
132545                     var isOptional = false;
132546                     for (var _i = 0, calls_1 = calls; _i < calls_1.length; _i++) {
132547                         var call = calls_1[_i];
132548                         if (call.argumentTypes.length <= parameterIndex) {
132549                             isOptional = ts.isInJSFile(declaration);
132550                             types.push(checker.getUndefinedType());
132551                         }
132552                         else if (isRest) {
132553                             for (var i = parameterIndex; i < call.argumentTypes.length; i++) {
132554                                 types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i]));
132555                             }
132556                         }
132557                         else {
132558                             types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex]));
132559                         }
132560                     }
132561                     if (ts.isIdentifier(parameter.name)) {
132562                         var inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken));
132563                         types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred));
132564                     }
132565                     var type = combineTypes(types);
132566                     return {
132567                         type: isRest ? checker.createArrayType(type) : type,
132568                         isOptional: isOptional && !isRest,
132569                         declaration: parameter
132570                     };
132571                 });
132572             }
132573             function thisParameter() {
132574                 var usage = createEmptyUsage();
132575                 for (var _i = 0, references_3 = references; _i < references_3.length; _i++) {
132576                     var reference = references_3[_i];
132577                     cancellationToken.throwIfCancellationRequested();
132578                     calculateUsageOfNode(reference, usage);
132579                 }
132580                 return combineTypes(usage.candidateThisTypes || ts.emptyArray);
132581             }
132582             function inferTypesFromReferencesSingle(references) {
132583                 var usage = createEmptyUsage();
132584                 for (var _i = 0, references_4 = references; _i < references_4.length; _i++) {
132585                     var reference = references_4[_i];
132586                     cancellationToken.throwIfCancellationRequested();
132587                     calculateUsageOfNode(reference, usage);
132588                 }
132589                 return inferTypes(usage);
132590             }
132591             function calculateUsageOfNode(node, usage) {
132592                 while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
132593                     node = node.parent;
132594                 }
132595                 switch (node.parent.kind) {
132596                     case 226 /* ExpressionStatement */:
132597                         inferTypeFromExpressionStatement(node, usage);
132598                         break;
132599                     case 208 /* PostfixUnaryExpression */:
132600                         usage.isNumber = true;
132601                         break;
132602                     case 207 /* PrefixUnaryExpression */:
132603                         inferTypeFromPrefixUnaryExpression(node.parent, usage);
132604                         break;
132605                     case 209 /* BinaryExpression */:
132606                         inferTypeFromBinaryExpression(node, node.parent, usage);
132607                         break;
132608                     case 277 /* CaseClause */:
132609                     case 278 /* DefaultClause */:
132610                         inferTypeFromSwitchStatementLabel(node.parent, usage);
132611                         break;
132612                     case 196 /* CallExpression */:
132613                     case 197 /* NewExpression */:
132614                         if (node.parent.expression === node) {
132615                             inferTypeFromCallExpression(node.parent, usage);
132616                         }
132617                         else {
132618                             inferTypeFromContextualType(node, usage);
132619                         }
132620                         break;
132621                     case 194 /* PropertyAccessExpression */:
132622                         inferTypeFromPropertyAccessExpression(node.parent, usage);
132623                         break;
132624                     case 195 /* ElementAccessExpression */:
132625                         inferTypeFromPropertyElementExpression(node.parent, node, usage);
132626                         break;
132627                     case 281 /* PropertyAssignment */:
132628                     case 282 /* ShorthandPropertyAssignment */:
132629                         inferTypeFromPropertyAssignment(node.parent, usage);
132630                         break;
132631                     case 159 /* PropertyDeclaration */:
132632                         inferTypeFromPropertyDeclaration(node.parent, usage);
132633                         break;
132634                     case 242 /* VariableDeclaration */: {
132635                         var _a = node.parent, name = _a.name, initializer = _a.initializer;
132636                         if (node === name) {
132637                             if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error.
132638                                 addCandidateType(usage, checker.getTypeAtLocation(initializer));
132639                             }
132640                             break;
132641                         }
132642                     }
132643                     // falls through
132644                     default:
132645                         return inferTypeFromContextualType(node, usage);
132646                 }
132647             }
132648             function inferTypeFromContextualType(node, usage) {
132649                 if (ts.isExpressionNode(node)) {
132650                     addCandidateType(usage, checker.getContextualType(node));
132651                 }
132652             }
132653             function inferTypeFromExpressionStatement(node, usage) {
132654                 addCandidateType(usage, ts.isCallExpression(node) ? checker.getVoidType() : checker.getAnyType());
132655             }
132656             function inferTypeFromPrefixUnaryExpression(node, usage) {
132657                 switch (node.operator) {
132658                     case 45 /* PlusPlusToken */:
132659                     case 46 /* MinusMinusToken */:
132660                     case 40 /* MinusToken */:
132661                     case 54 /* TildeToken */:
132662                         usage.isNumber = true;
132663                         break;
132664                     case 39 /* PlusToken */:
132665                         usage.isNumberOrString = true;
132666                         break;
132667                     // case SyntaxKind.ExclamationToken:
132668                     // no inferences here;
132669                 }
132670             }
132671             function inferTypeFromBinaryExpression(node, parent, usage) {
132672                 switch (parent.operatorToken.kind) {
132673                     // ExponentiationOperator
132674                     case 42 /* AsteriskAsteriskToken */:
132675                     // MultiplicativeOperator
132676                     // falls through
132677                     case 41 /* AsteriskToken */:
132678                     case 43 /* SlashToken */:
132679                     case 44 /* PercentToken */:
132680                     // ShiftOperator
132681                     // falls through
132682                     case 47 /* LessThanLessThanToken */:
132683                     case 48 /* GreaterThanGreaterThanToken */:
132684                     case 49 /* GreaterThanGreaterThanGreaterThanToken */:
132685                     // BitwiseOperator
132686                     // falls through
132687                     case 50 /* AmpersandToken */:
132688                     case 51 /* BarToken */:
132689                     case 52 /* CaretToken */:
132690                     // CompoundAssignmentOperator
132691                     // falls through
132692                     case 64 /* MinusEqualsToken */:
132693                     case 66 /* AsteriskAsteriskEqualsToken */:
132694                     case 65 /* AsteriskEqualsToken */:
132695                     case 67 /* SlashEqualsToken */:
132696                     case 68 /* PercentEqualsToken */:
132697                     case 72 /* AmpersandEqualsToken */:
132698                     case 73 /* BarEqualsToken */:
132699                     case 74 /* CaretEqualsToken */:
132700                     case 69 /* LessThanLessThanEqualsToken */:
132701                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
132702                     case 70 /* GreaterThanGreaterThanEqualsToken */:
132703                     // AdditiveOperator
132704                     // falls through
132705                     case 40 /* MinusToken */:
132706                     // RelationalOperator
132707                     // falls through
132708                     case 29 /* LessThanToken */:
132709                     case 32 /* LessThanEqualsToken */:
132710                     case 31 /* GreaterThanToken */:
132711                     case 33 /* GreaterThanEqualsToken */:
132712                         var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
132713                         if (operandType.flags & 1056 /* EnumLike */) {
132714                             addCandidateType(usage, operandType);
132715                         }
132716                         else {
132717                             usage.isNumber = true;
132718                         }
132719                         break;
132720                     case 63 /* PlusEqualsToken */:
132721                     case 39 /* PlusToken */:
132722                         var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
132723                         if (otherOperandType.flags & 1056 /* EnumLike */) {
132724                             addCandidateType(usage, otherOperandType);
132725                         }
132726                         else if (otherOperandType.flags & 296 /* NumberLike */) {
132727                             usage.isNumber = true;
132728                         }
132729                         else if (otherOperandType.flags & 132 /* StringLike */) {
132730                             usage.isString = true;
132731                         }
132732                         else if (otherOperandType.flags & 1 /* Any */) {
132733                             // do nothing, maybe we'll learn something elsewhere
132734                         }
132735                         else {
132736                             usage.isNumberOrString = true;
132737                         }
132738                         break;
132739                     //  AssignmentOperators
132740                     case 62 /* EqualsToken */:
132741                     case 34 /* EqualsEqualsToken */:
132742                     case 36 /* EqualsEqualsEqualsToken */:
132743                     case 37 /* ExclamationEqualsEqualsToken */:
132744                     case 35 /* ExclamationEqualsToken */:
132745                         addCandidateType(usage, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left));
132746                         break;
132747                     case 97 /* InKeyword */:
132748                         if (node === parent.left) {
132749                             usage.isString = true;
132750                         }
132751                         break;
132752                     // LogicalOperator Or NullishCoalescing
132753                     case 56 /* BarBarToken */:
132754                     case 60 /* QuestionQuestionToken */:
132755                         if (node === parent.left &&
132756                             (node.parent.parent.kind === 242 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) {
132757                             // var x = x || {};
132758                             // TODO: use getFalsyflagsOfType
132759                             addCandidateType(usage, checker.getTypeAtLocation(parent.right));
132760                         }
132761                         break;
132762                     case 55 /* AmpersandAmpersandToken */:
132763                     case 27 /* CommaToken */:
132764                     case 98 /* InstanceOfKeyword */:
132765                         // nothing to infer here
132766                         break;
132767                 }
132768             }
132769             function inferTypeFromSwitchStatementLabel(parent, usage) {
132770                 addCandidateType(usage, checker.getTypeAtLocation(parent.parent.parent.expression));
132771             }
132772             function inferTypeFromCallExpression(parent, usage) {
132773                 var call = {
132774                     argumentTypes: [],
132775                     return_: createEmptyUsage()
132776                 };
132777                 if (parent.arguments) {
132778                     for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) {
132779                         var argument = _a[_i];
132780                         call.argumentTypes.push(checker.getTypeAtLocation(argument));
132781                     }
132782                 }
132783                 calculateUsageOfNode(parent, call.return_);
132784                 if (parent.kind === 196 /* CallExpression */) {
132785                     (usage.calls || (usage.calls = [])).push(call);
132786                 }
132787                 else {
132788                     (usage.constructs || (usage.constructs = [])).push(call);
132789                 }
132790             }
132791             function inferTypeFromPropertyAccessExpression(parent, usage) {
132792                 var name = ts.escapeLeadingUnderscores(parent.name.text);
132793                 if (!usage.properties) {
132794                     usage.properties = ts.createUnderscoreEscapedMap();
132795                 }
132796                 var propertyUsage = usage.properties.get(name) || createEmptyUsage();
132797                 calculateUsageOfNode(parent, propertyUsage);
132798                 usage.properties.set(name, propertyUsage);
132799             }
132800             function inferTypeFromPropertyElementExpression(parent, node, usage) {
132801                 if (node === parent.argumentExpression) {
132802                     usage.isNumberOrString = true;
132803                     return;
132804                 }
132805                 else {
132806                     var indexType = checker.getTypeAtLocation(parent.argumentExpression);
132807                     var indexUsage = createEmptyUsage();
132808                     calculateUsageOfNode(parent, indexUsage);
132809                     if (indexType.flags & 296 /* NumberLike */) {
132810                         usage.numberIndex = indexUsage;
132811                     }
132812                     else {
132813                         usage.stringIndex = indexUsage;
132814                     }
132815                 }
132816             }
132817             function inferTypeFromPropertyAssignment(assignment, usage) {
132818                 var nodeWithRealType = ts.isVariableDeclaration(assignment.parent.parent) ?
132819                     assignment.parent.parent :
132820                     assignment.parent;
132821                 addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType));
132822             }
132823             function inferTypeFromPropertyDeclaration(declaration, usage) {
132824                 addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent));
132825             }
132826             function removeLowPriorityInferences(inferences, priorities) {
132827                 var toRemove = [];
132828                 for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
132829                     var i = inferences_1[_i];
132830                     for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
132831                         var _b = priorities_1[_a], high = _b.high, low = _b.low;
132832                         if (high(i)) {
132833                             ts.Debug.assert(!low(i), "Priority can't have both low and high");
132834                             toRemove.push(low);
132835                         }
132836                     }
132837                 }
132838                 return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); });
132839             }
132840             function combineFromUsage(usage) {
132841                 return combineTypes(inferTypes(usage));
132842             }
132843             function combineTypes(inferences) {
132844                 if (!inferences.length)
132845                     return checker.getAnyType();
132846                 // 1. string or number individually override string | number
132847                 // 2. non-any, non-void overrides any or void
132848                 // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types
132849                 var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
132850                 var priorities = [
132851                     {
132852                         high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); },
132853                         low: function (t) { return t === stringNumber; }
132854                     },
132855                     {
132856                         high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); },
132857                         low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); }
132858                     },
132859                     {
132860                         high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(ts.getObjectFlags(t) & 16 /* Anonymous */); },
132861                         low: function (t) { return !!(ts.getObjectFlags(t) & 16 /* Anonymous */); }
132862                     }
132863                 ];
132864                 var good = removeLowPriorityInferences(inferences, priorities);
132865                 var anons = good.filter(function (i) { return ts.getObjectFlags(i) & 16 /* Anonymous */; });
132866                 if (anons.length) {
132867                     good = good.filter(function (i) { return !(ts.getObjectFlags(i) & 16 /* Anonymous */); });
132868                     good.push(combineAnonymousTypes(anons));
132869                 }
132870                 return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */));
132871             }
132872             function combineAnonymousTypes(anons) {
132873                 if (anons.length === 1) {
132874                     return anons[0];
132875                 }
132876                 var calls = [];
132877                 var constructs = [];
132878                 var stringIndices = [];
132879                 var numberIndices = [];
132880                 var stringIndexReadonly = false;
132881                 var numberIndexReadonly = false;
132882                 var props = ts.createMultiMap();
132883                 for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) {
132884                     var anon = anons_1[_i];
132885                     for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) {
132886                         var p = _b[_a];
132887                         props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration));
132888                     }
132889                     calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */));
132890                     constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */));
132891                     if (anon.stringIndexInfo) {
132892                         stringIndices.push(anon.stringIndexInfo.type);
132893                         stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly;
132894                     }
132895                     if (anon.numberIndexInfo) {
132896                         numberIndices.push(anon.numberIndexInfo.type);
132897                         numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly;
132898                     }
132899                 }
132900                 var members = ts.mapEntries(props, function (name, types) {
132901                     var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0;
132902                     var s = checker.createSymbol(4 /* Property */ | isOptional, name);
132903                     s.type = checker.getUnionType(types);
132904                     return [name, s];
132905                 });
132906                 return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined);
132907             }
132908             function inferTypes(usage) {
132909                 var _a, _b, _c;
132910                 var types = [];
132911                 if (usage.isNumber) {
132912                     types.push(checker.getNumberType());
132913                 }
132914                 if (usage.isString) {
132915                     types.push(checker.getStringType());
132916                 }
132917                 if (usage.isNumberOrString) {
132918                     types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
132919                 }
132920                 if (usage.numberIndex) {
132921                     types.push(checker.createArrayType(combineFromUsage(usage.numberIndex)));
132922                 }
132923                 if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.calls) === null || _b === void 0 ? void 0 : _b.length) || ((_c = usage.constructs) === null || _c === void 0 ? void 0 : _c.length) || usage.stringIndex) {
132924                     types.push(inferStructuralType(usage));
132925                 }
132926                 types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
132927                 types.push.apply(types, inferNamedTypesFromProperties(usage));
132928                 return types;
132929             }
132930             function inferStructuralType(usage) {
132931                 var members = ts.createUnderscoreEscapedMap();
132932                 if (usage.properties) {
132933                     usage.properties.forEach(function (u, name) {
132934                         var symbol = checker.createSymbol(4 /* Property */, name);
132935                         symbol.type = combineFromUsage(u);
132936                         members.set(name, symbol);
132937                     });
132938                 }
132939                 var callSignatures = usage.calls ? [getSignatureFromCalls(usage.calls)] : [];
132940                 var constructSignatures = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : [];
132941                 var stringIndexInfo = usage.stringIndex && checker.createIndexInfo(combineFromUsage(usage.stringIndex), /*isReadonly*/ false);
132942                 return checker.createAnonymousType(/*symbol*/ undefined, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined);
132943             }
132944             function inferNamedTypesFromProperties(usage) {
132945                 if (!usage.properties || !usage.properties.size)
132946                     return [];
132947                 var types = builtins.filter(function (t) { return allPropertiesAreAssignableToUsage(t, usage); });
132948                 if (0 < types.length && types.length < 3) {
132949                     return types.map(function (t) { return inferInstantiationFromUsage(t, usage); });
132950                 }
132951                 return [];
132952             }
132953             function allPropertiesAreAssignableToUsage(type, usage) {
132954                 if (!usage.properties)
132955                     return false;
132956                 return !ts.forEachEntry(usage.properties, function (propUsage, name) {
132957                     var source = checker.getTypeOfPropertyOfType(type, name);
132958                     if (!source) {
132959                         return true;
132960                     }
132961                     if (propUsage.calls) {
132962                         var sigs = checker.getSignaturesOfType(source, 0 /* Call */);
132963                         return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls));
132964                     }
132965                     else {
132966                         return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage));
132967                     }
132968                 });
132969             }
132970             /**
132971              * inference is limited to
132972              * 1. generic types with a single parameter
132973              * 2. inference to/from calls with a single signature
132974              */
132975             function inferInstantiationFromUsage(type, usage) {
132976                 if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !usage.properties) {
132977                     return type;
132978                 }
132979                 var generic = type.target;
132980                 var singleTypeParameter = ts.singleOrUndefined(generic.typeParameters);
132981                 if (!singleTypeParameter)
132982                     return type;
132983                 var types = [];
132984                 usage.properties.forEach(function (propUsage, name) {
132985                     var genericPropertyType = checker.getTypeOfPropertyOfType(generic, name);
132986                     ts.Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference.");
132987                     types.push.apply(types, inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter));
132988                 });
132989                 return builtinConstructors[type.symbol.escapedName](combineTypes(types));
132990             }
132991             function inferTypeParameters(genericType, usageType, typeParameter) {
132992                 if (genericType === typeParameter) {
132993                     return [usageType];
132994                 }
132995                 else if (genericType.flags & 3145728 /* UnionOrIntersection */) {
132996                     return ts.flatMap(genericType.types, function (t) { return inferTypeParameters(t, usageType, typeParameter); });
132997                 }
132998                 else if (ts.getObjectFlags(genericType) & 4 /* Reference */ && ts.getObjectFlags(usageType) & 4 /* Reference */) {
132999                     // this is wrong because we need a reference to the targetType to, so we can check that it's also a reference
133000                     var genericArgs = checker.getTypeArguments(genericType);
133001                     var usageArgs = checker.getTypeArguments(usageType);
133002                     var types = [];
133003                     if (genericArgs && usageArgs) {
133004                         for (var i = 0; i < genericArgs.length; i++) {
133005                             if (usageArgs[i]) {
133006                                 types.push.apply(types, inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter));
133007                             }
133008                         }
133009                     }
133010                     return types;
133011                 }
133012                 var genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */);
133013                 var usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */);
133014                 if (genericSigs.length === 1 && usageSigs.length === 1) {
133015                     return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter);
133016                 }
133017                 return [];
133018             }
133019             function inferFromSignatures(genericSig, usageSig, typeParameter) {
133020                 var types = [];
133021                 for (var i = 0; i < genericSig.parameters.length; i++) {
133022                     var genericParam = genericSig.parameters[i];
133023                     var usageParam = usageSig.parameters[i];
133024                     var isRest = genericSig.declaration && ts.isRestParameter(genericSig.declaration.parameters[i]);
133025                     if (!usageParam) {
133026                         break;
133027                     }
133028                     var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration);
133029                     var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType);
133030                     if (elementType) {
133031                         genericParamType = elementType;
133032                     }
133033                     var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration);
133034                     types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter));
133035                 }
133036                 var genericReturn = checker.getReturnTypeOfSignature(genericSig);
133037                 var usageReturn = checker.getReturnTypeOfSignature(usageSig);
133038                 types.push.apply(types, inferTypeParameters(genericReturn, usageReturn, typeParameter));
133039                 return types;
133040             }
133041             function getFunctionFromCalls(calls) {
133042                 return checker.createAnonymousType(/*symbol*/ undefined, ts.createSymbolTable(), [getSignatureFromCalls(calls)], ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
133043             }
133044             function getSignatureFromCalls(calls) {
133045                 var parameters = [];
133046                 var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; }));
133047                 var _loop_14 = function (i) {
133048                     var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i));
133049                     symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); }));
133050                     if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) {
133051                         symbol.flags |= 16777216 /* Optional */;
133052                     }
133053                     parameters.push(symbol);
133054                 };
133055                 for (var i = 0; i < length; i++) {
133056                     _loop_14(i);
133057                 }
133058                 var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; })));
133059                 // TODO: GH#18217
133060                 return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */);
133061             }
133062             function addCandidateType(usage, type) {
133063                 if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
133064                     (usage.candidateTypes || (usage.candidateTypes = [])).push(type);
133065                 }
133066             }
133067             function addCandidateThisType(usage, type) {
133068                 if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
133069                     (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type);
133070                 }
133071             }
133072         }
133073     })(codefix = ts.codefix || (ts.codefix = {}));
133074 })(ts || (ts = {}));
133075 /* @internal */
133076 var ts;
133077 (function (ts) {
133078     var codefix;
133079     (function (codefix) {
133080         var fixName = "disableJsDiagnostics";
133081         var fixId = "disableJsDiagnostics";
133082         var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) {
133083             var diag = ts.Diagnostics[key];
133084             return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined;
133085         });
133086         codefix.registerCodeFix({
133087             errorCodes: errorCodes,
133088             getCodeActions: function (context) {
133089                 var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext;
133090                 if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
133091                     return undefined;
133092                 }
133093                 var newLineCharacter = sourceFile.checkJsDirective ? "" : ts.getNewLineOrDefaultFromHost(host, formatContext.options);
133094                 var fixes = [
133095                     // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file.
133096                     codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [
133097                             ts.createTextChange(sourceFile.checkJsDirective
133098                                 ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end)
133099                                 : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter),
133100                         ])], ts.Diagnostics.Disable_checking_for_this_file),
133101                 ];
133102                 if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) {
133103                     fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages));
133104                 }
133105                 return fixes;
133106             },
133107             fixIds: [fixId],
133108             getAllCodeActions: function (context) {
133109                 var seenLines = ts.createMap();
133110                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
133111                     if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) {
133112                         makeChange(changes, diag.file, diag.start, seenLines);
133113                     }
133114                 });
133115             },
133116         });
133117         function makeChange(changes, sourceFile, position, seenLines) {
133118             var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line;
133119             // Only need to add `// @ts-ignore` for a line once.
133120             if (!seenLines || ts.addToSeen(seenLines, lineNumber)) {
133121                 changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore");
133122             }
133123         }
133124     })(codefix = ts.codefix || (ts.codefix = {}));
133125 })(ts || (ts = {}));
133126 /* @internal */
133127 var ts;
133128 (function (ts) {
133129     var codefix;
133130     (function (codefix) {
133131         /**
133132          * Finds members of the resolved type that are missing in the class pointed to by class decl
133133          * and generates source code for the missing members.
133134          * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for.
133135          * @param importAdder If provided, type annotations will use identifier type references instead of ImportTypeNodes, and the missing imports will be added to the importAdder.
133136          * @returns Empty string iff there are no member insertions.
133137          */
133138         function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, importAdder, addClassElement) {
133139             var classMembers = classDeclaration.symbol.members;
133140             for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) {
133141                 var symbol = possiblyMissingSymbols_1[_i];
133142                 if (!classMembers.has(symbol.escapedName)) {
133143                     addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, importAdder, addClassElement);
133144                 }
133145             }
133146         }
133147         codefix.createMissingMemberNodes = createMissingMemberNodes;
133148         function getNoopSymbolTrackerWithResolver(context) {
133149             return {
133150                 trackSymbol: ts.noop,
133151                 moduleResolverHost: ts.getModuleSpecifierResolverHost(context.program, context.host),
133152             };
133153         }
133154         codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver;
133155         /**
133156          * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`.
133157          */
133158         function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, importAdder, addClassElement) {
133159             var declarations = symbol.getDeclarations();
133160             if (!(declarations && declarations.length)) {
133161                 return undefined;
133162             }
133163             var checker = context.program.getTypeChecker();
133164             var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions());
133165             var declaration = declarations[0];
133166             var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false);
133167             var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration));
133168             var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined;
133169             var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
133170             var optional = !!(symbol.flags & 16777216 /* Optional */);
133171             var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */);
133172             switch (declaration.kind) {
133173                 case 158 /* PropertySignature */:
133174                 case 159 /* PropertyDeclaration */:
133175                     var flags = preferences.quotePreference === "single" ? 268435456 /* UseSingleQuotesForStringLiteralType */ : undefined;
133176                     var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context));
133177                     if (importAdder) {
133178                         var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget);
133179                         if (importableReference) {
133180                             typeNode = importableReference.typeReference;
133181                             importSymbols(importAdder, importableReference.symbols);
133182                         }
133183                     }
133184                     addClassElement(ts.createProperty(
133185                     /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(57 /* QuestionToken */) : undefined, typeNode, 
133186                     /*initializer*/ undefined));
133187                     break;
133188                 case 163 /* GetAccessor */:
133189                 case 164 /* SetAccessor */: {
133190                     var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context));
133191                     var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration);
133192                     var orderedAccessors = allAccessors.secondAccessor
133193                         ? [allAccessors.firstAccessor, allAccessors.secondAccessor]
133194                         : [allAccessors.firstAccessor];
133195                     if (importAdder) {
133196                         var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode_1, type, scriptTarget);
133197                         if (importableReference) {
133198                             typeNode_1 = importableReference.typeReference;
133199                             importSymbols(importAdder, importableReference.symbols);
133200                         }
133201                     }
133202                     for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) {
133203                         var accessor = orderedAccessors_1[_i];
133204                         if (ts.isGetAccessorDeclaration(accessor)) {
133205                             addClassElement(ts.createGetAccessor(
133206                             /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : createStubbedMethodBody(preferences)));
133207                         }
133208                         else {
133209                             ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter");
133210                             var parameter = ts.getSetAccessorValueParameter(accessor);
133211                             var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined;
133212                             addClassElement(ts.createSetAccessor(
133213                             /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : createStubbedMethodBody(preferences)));
133214                         }
133215                     }
133216                     break;
133217                 }
133218                 case 160 /* MethodSignature */:
133219                 case 161 /* MethodDeclaration */:
133220                     // The signature for the implementation appears as an entry in `signatures` iff
133221                     // there is only one signature.
133222                     // If there are overloads and an implementation signature, it appears as an
133223                     // extra declaration that isn't a signature for `type`.
133224                     // If there is more than one overload but no implementation signature
133225                     // (eg: an abstract method or interface declaration), there is a 1-1
133226                     // correspondence of declarations and signatures.
133227                     var signatures = checker.getSignaturesOfType(type, 0 /* Call */);
133228                     if (!ts.some(signatures)) {
133229                         break;
133230                     }
133231                     if (declarations.length === 1) {
133232                         ts.Debug.assert(signatures.length === 1, "One declaration implies one signature");
133233                         var signature = signatures[0];
133234                         outputMethod(signature, modifiers, name, ambient ? undefined : createStubbedMethodBody(preferences));
133235                         break;
133236                     }
133237                     for (var _a = 0, signatures_1 = signatures; _a < signatures_1.length; _a++) {
133238                         var signature = signatures_1[_a];
133239                         // Need to ensure nodes are fresh each time so they can have different positions.
133240                         outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false));
133241                     }
133242                     if (!ambient) {
133243                         if (declarations.length > signatures.length) {
133244                             var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]);
133245                             outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
133246                         }
133247                         else {
133248                             ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count");
133249                             addClassElement(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences));
133250                         }
133251                     }
133252                     break;
133253             }
133254             function outputMethod(signature, modifiers, name, body) {
133255                 var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body, importAdder);
133256                 if (method)
133257                     addClassElement(method);
133258             }
133259         }
133260         function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body, importAdder) {
133261             var program = context.program;
133262             var checker = program.getTypeChecker();
133263             var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions());
133264             var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 161 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context));
133265             if (!signatureDeclaration) {
133266                 return undefined;
133267             }
133268             if (importAdder) {
133269                 if (signatureDeclaration.typeParameters) {
133270                     ts.forEach(signatureDeclaration.typeParameters, function (typeParameterDecl, i) {
133271                         var typeParameter = signature.typeParameters[i];
133272                         if (typeParameterDecl.constraint) {
133273                             var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeParameterDecl.constraint, typeParameter.constraint, scriptTarget);
133274                             if (importableReference) {
133275                                 typeParameterDecl.constraint = importableReference.typeReference;
133276                                 importSymbols(importAdder, importableReference.symbols);
133277                             }
133278                         }
133279                         if (typeParameterDecl.default) {
133280                             var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeParameterDecl.default, typeParameter.default, scriptTarget);
133281                             if (importableReference) {
133282                                 typeParameterDecl.default = importableReference.typeReference;
133283                                 importSymbols(importAdder, importableReference.symbols);
133284                             }
133285                         }
133286                     });
133287                 }
133288                 ts.forEach(signatureDeclaration.parameters, function (parameterDecl, i) {
133289                     var parameter = signature.parameters[i];
133290                     var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(parameterDecl.type, checker.getTypeAtLocation(parameter.valueDeclaration), scriptTarget);
133291                     if (importableReference) {
133292                         parameterDecl.type = importableReference.typeReference;
133293                         importSymbols(importAdder, importableReference.symbols);
133294                     }
133295                 });
133296                 if (signatureDeclaration.type) {
133297                     var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(signatureDeclaration.type, signature.resolvedReturnType, scriptTarget);
133298                     if (importableReference) {
133299                         signatureDeclaration.type = importableReference.typeReference;
133300                         importSymbols(importAdder, importableReference.symbols);
133301                     }
133302                 }
133303             }
133304             signatureDeclaration.decorators = undefined;
133305             signatureDeclaration.modifiers = modifiers;
133306             signatureDeclaration.name = name;
133307             signatureDeclaration.questionToken = optional ? ts.createToken(57 /* QuestionToken */) : undefined;
133308             signatureDeclaration.body = body;
133309             return signatureDeclaration;
133310         }
133311         function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, contextNode, importAdder) {
133312             var body = !ts.isInterfaceDeclaration(contextNode);
133313             var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent;
133314             var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions());
133315             var checker = context.program.getTypeChecker();
133316             var tracker = getNoopSymbolTrackerWithResolver(context);
133317             var types = ts.map(args, function (arg) {
133318                 return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker);
133319             });
133320             var names = ts.map(args, function (arg) {
133321                 return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined;
133322             });
133323             var contextualType = checker.getContextualType(call);
133324             var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
133325             return ts.createMethod(
133326             /*decorators*/ undefined, 
133327             /*modifiers*/ makeStatic ? [ts.createToken(120 /* StaticKeyword */)] : undefined, 
133328             /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(41 /* AsteriskToken */) : undefined, methodName, 
133329             /*questionToken*/ undefined, 
133330             /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) {
133331                 return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i);
133332             }), 
133333             /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), 
133334             /*type*/ returnType, body ? createStubbedMethodBody(context.preferences) : undefined);
133335         }
133336         codefix.createMethodFromCallExpression = createMethodFromCallExpression;
133337         function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) {
133338             var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker);
133339             if (typeNode && ts.isImportTypeNode(typeNode)) {
133340                 var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget);
133341                 if (importableReference) {
133342                     importSymbols(importAdder, importableReference.symbols);
133343                     return importableReference.typeReference;
133344                 }
133345             }
133346             return typeNode;
133347         }
133348         codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode;
133349         function createDummyParameters(argCount, names, types, minArgumentCount, inJs) {
133350             var parameters = [];
133351             for (var i = 0; i < argCount; i++) {
133352                 var newParameter = ts.createParameter(
133353                 /*decorators*/ undefined, 
133354                 /*modifiers*/ undefined, 
133355                 /*dotDotDotToken*/ undefined, 
133356                 /*name*/ names && names[i] || "arg" + i, 
133357                 /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(57 /* QuestionToken */) : undefined, 
133358                 /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(125 /* AnyKeyword */), 
133359                 /*initializer*/ undefined);
133360                 parameters.push(newParameter);
133361             }
133362             return parameters;
133363         }
133364         function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) {
133365             /** This is *a* signature with the maximal number of arguments,
133366              * such that if there is a "maximal" signature without rest arguments,
133367              * this is one of them.
133368              */
133369             var maxArgsSignature = signatures[0];
133370             var minArgumentCount = signatures[0].minArgumentCount;
133371             var someSigHasRestParameter = false;
133372             for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
133373                 var sig = signatures_2[_i];
133374                 minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
133375                 if (ts.signatureHasRestParameter(sig)) {
133376                     someSigHasRestParameter = true;
133377                 }
133378                 if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) {
133379                     maxArgsSignature = sig;
133380                 }
133381             }
133382             var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0);
133383             var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; });
133384             var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false);
133385             if (someSigHasRestParameter) {
133386                 var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(125 /* AnyKeyword */));
133387                 var restParameter = ts.createParameter(
133388                 /*decorators*/ undefined, 
133389                 /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", 
133390                 /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(57 /* QuestionToken */) : undefined, anyArrayType, 
133391                 /*initializer*/ undefined);
133392                 parameters.push(restParameter);
133393             }
133394             return createStubbedMethod(modifiers, name, optional, 
133395             /*typeParameters*/ undefined, parameters, 
133396             /*returnType*/ undefined, preferences);
133397         }
133398         function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) {
133399             return ts.createMethod(
133400             /*decorators*/ undefined, modifiers, 
133401             /*asteriskToken*/ undefined, name, optional ? ts.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences));
133402         }
133403         function createStubbedMethodBody(preferences) {
133404             return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), 
133405                 /*typeArguments*/ undefined, 
133406                 // TODO Handle auto quote preference.
133407                 [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], 
133408             /*multiline*/ true);
133409         }
133410         function createVisibilityModifier(flags) {
133411             if (flags & 4 /* Public */) {
133412                 return ts.createToken(119 /* PublicKeyword */);
133413             }
133414             else if (flags & 16 /* Protected */) {
133415                 return ts.createToken(118 /* ProtectedKeyword */);
133416             }
133417             return undefined;
133418         }
133419         function setJsonCompilerOptionValues(changeTracker, configFile, options) {
133420             var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile);
133421             if (!tsconfigObjectLiteral)
133422                 return undefined;
133423             var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions");
133424             if (compilerOptionsProperty === undefined) {
133425                 changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral(options.map(function (_a) {
133426                     var optionName = _a[0], optionValue = _a[1];
133427                     return createJsonPropertyAssignment(optionName, optionValue);
133428                 }), /*multiLine*/ true)));
133429                 return;
133430             }
133431             var compilerOptions = compilerOptionsProperty.initializer;
133432             if (!ts.isObjectLiteralExpression(compilerOptions)) {
133433                 return;
133434             }
133435             for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
133436                 var _a = options_1[_i], optionName = _a[0], optionValue = _a[1];
133437                 var optionProperty = findJsonProperty(compilerOptions, optionName);
133438                 if (optionProperty === undefined) {
133439                     changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue));
133440                 }
133441                 else {
133442                     changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue);
133443                 }
133444             }
133445         }
133446         codefix.setJsonCompilerOptionValues = setJsonCompilerOptionValues;
133447         function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) {
133448             setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]);
133449         }
133450         codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue;
133451         function createJsonPropertyAssignment(name, initializer) {
133452             return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer);
133453         }
133454         codefix.createJsonPropertyAssignment = createJsonPropertyAssignment;
133455         function findJsonProperty(obj, name) {
133456             return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; });
133457         }
133458         codefix.findJsonProperty = findJsonProperty;
133459         /**
133460          * Given an ImportTypeNode 'import("./a").SomeType<import("./b").OtherType<...>>',
133461          * returns an equivalent type reference node with any nested ImportTypeNodes also replaced
133462          * with type references, and a list of symbols that must be imported to use the type reference.
133463          */
133464         function tryGetAutoImportableReferenceFromImportTypeNode(importTypeNode, type, scriptTarget) {
133465             if (importTypeNode && ts.isLiteralImportTypeNode(importTypeNode) && importTypeNode.qualifier && (!type || type.symbol)) {
133466                 // Symbol for the left-most thing after the dot
133467                 var firstIdentifier = ts.getFirstIdentifier(importTypeNode.qualifier);
133468                 var name = ts.getNameForExportedSymbol(firstIdentifier.symbol, scriptTarget);
133469                 var qualifier = name !== firstIdentifier.text
133470                     ? replaceFirstIdentifierOfEntityName(importTypeNode.qualifier, ts.createIdentifier(name))
133471                     : importTypeNode.qualifier;
133472                 var symbols_4 = [firstIdentifier.symbol];
133473                 var typeArguments_1 = [];
133474                 if (importTypeNode.typeArguments) {
133475                     importTypeNode.typeArguments.forEach(function (arg) {
133476                         var ref = tryGetAutoImportableReferenceFromImportTypeNode(arg, /*undefined*/ type, scriptTarget);
133477                         if (ref) {
133478                             symbols_4.push.apply(symbols_4, ref.symbols);
133479                             typeArguments_1.push(ref.typeReference);
133480                         }
133481                         else {
133482                             typeArguments_1.push(arg);
133483                         }
133484                     });
133485                 }
133486                 return {
133487                     symbols: symbols_4,
133488                     typeReference: ts.createTypeReferenceNode(qualifier, typeArguments_1)
133489                 };
133490             }
133491         }
133492         codefix.tryGetAutoImportableReferenceFromImportTypeNode = tryGetAutoImportableReferenceFromImportTypeNode;
133493         function replaceFirstIdentifierOfEntityName(name, newIdentifier) {
133494             if (name.kind === 75 /* Identifier */) {
133495                 return newIdentifier;
133496             }
133497             return ts.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right);
133498         }
133499         function importSymbols(importAdder, symbols) {
133500             symbols.forEach(function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); });
133501         }
133502         codefix.importSymbols = importSymbols;
133503     })(codefix = ts.codefix || (ts.codefix = {}));
133504 })(ts || (ts = {}));
133505 /* @internal */
133506 var ts;
133507 (function (ts) {
133508     var codefix;
133509     (function (codefix) {
133510         var fixName = "invalidImportSyntax";
133511         function getCodeFixesForImportDeclaration(context, node) {
133512             var sourceFile = ts.getSourceFileOfNode(node);
133513             var namespace = ts.getNamespaceDeclarationNode(node);
133514             var opts = context.program.getCompilerOptions();
133515             var variations = [];
133516             // import Bluebird from "bluebird";
133517             variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences))));
133518             if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
133519                 // import Bluebird = require("bluebird");
133520                 variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
133521                 /*decorators*/ undefined, 
133522                 /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier))));
133523             }
133524             return variations;
133525         }
133526         function createAction(context, sourceFile, node, replacement) {
133527             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); });
133528             return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]);
133529         }
133530         codefix.registerCodeFix({
133531             errorCodes: [
133532                 ts.Diagnostics.This_expression_is_not_callable.code,
133533                 ts.Diagnostics.This_expression_is_not_constructable.code,
133534             ],
133535             getCodeActions: getActionsForUsageOfInvalidImport
133536         });
133537         function getActionsForUsageOfInvalidImport(context) {
133538             var sourceFile = context.sourceFile;
133539             var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 196 /* CallExpression */ : 197 /* NewExpression */;
133540             var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind; });
133541             if (!node) {
133542                 return [];
133543             }
133544             var expr = node.expression;
133545             return getImportCodeFixesForExpression(context, expr);
133546         }
133547         codefix.registerCodeFix({
133548             errorCodes: [
133549                 // The following error codes cover pretty much all assignability errors that could involve an expression
133550                 ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
133551                 ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code,
133552                 ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code,
133553                 ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code,
133554                 ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code,
133555                 ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code,
133556                 ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code,
133557                 ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code,
133558                 ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code,
133559                 ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code,
133560                 ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code,
133561                 ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code,
133562             ],
133563             getCodeActions: getActionsForInvalidImportLocation
133564         });
133565         function getActionsForInvalidImportLocation(context) {
133566             var sourceFile = context.sourceFile;
133567             var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); });
133568             if (!node) {
133569                 return [];
133570             }
133571             return getImportCodeFixesForExpression(context, node);
133572         }
133573         function getImportCodeFixesForExpression(context, expr) {
133574             var type = context.program.getTypeChecker().getTypeAtLocation(expr);
133575             if (!(type.symbol && type.symbol.originatingImport)) {
133576                 return [];
133577             }
133578             var fixes = [];
133579             var relatedImport = type.symbol.originatingImport; // TODO: GH#18217
133580             if (!ts.isImportCall(relatedImport)) {
133581                 ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
133582             }
133583             if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
133584                 var sourceFile_1 = context.sourceFile;
133585                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
133586                 fixes.push(codefix.createCodeFixActionWithoutFixAll(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
133587             }
133588             return fixes;
133589         }
133590     })(codefix = ts.codefix || (ts.codefix = {}));
133591 })(ts || (ts = {}));
133592 /* @internal */
133593 var ts;
133594 (function (ts) {
133595     var codefix;
133596     (function (codefix) {
133597         var fixName = "strictClassInitialization";
133598         var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
133599         var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
133600         var fixIdAddInitializer = "addMissingPropertyInitializer";
133601         var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
133602         codefix.registerCodeFix({
133603             errorCodes: errorCodes,
133604             getCodeActions: function (context) {
133605                 var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start);
133606                 if (!propertyDeclaration)
133607                     return;
133608                 var result = [
133609                     getActionForAddMissingUndefinedType(context, propertyDeclaration),
133610                     getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration)
133611                 ];
133612                 ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration));
133613                 return result;
133614             },
133615             fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
133616             getAllCodeActions: function (context) {
133617                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
133618                     var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start);
133619                     if (!propertyDeclaration)
133620                         return;
133621                     switch (context.fixId) {
133622                         case fixIdAddDefiniteAssignmentAssertions:
133623                             addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration);
133624                             break;
133625                         case fixIdAddUndefinedType:
133626                             addUndefinedType(changes, diag.file, propertyDeclaration);
133627                             break;
133628                         case fixIdAddInitializer:
133629                             var checker = context.program.getTypeChecker();
133630                             var initializer = getInitializer(checker, propertyDeclaration);
133631                             if (!initializer)
133632                                 return;
133633                             addInitializer(changes, diag.file, propertyDeclaration, initializer);
133634                             break;
133635                         default:
133636                             ts.Debug.fail(JSON.stringify(context.fixId));
133637                     }
133638                 });
133639             },
133640         });
133641         function getPropertyDeclaration(sourceFile, pos) {
133642             var token = ts.getTokenAtPosition(sourceFile, pos);
133643             return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
133644         }
133645         function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) {
133646             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); });
133647             return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties);
133648         }
133649         function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
133650             var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(53 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer);
133651             changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
133652         }
133653         function getActionForAddMissingUndefinedType(context, propertyDeclaration) {
133654             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); });
133655             return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties);
133656         }
133657         function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
133658             var undefinedTypeNode = ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
133659             var type = propertyDeclaration.type; // TODO: GH#18217
133660             var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode];
133661             changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types));
133662         }
133663         function getActionForAddMissingInitializer(context, propertyDeclaration) {
133664             var checker = context.program.getTypeChecker();
133665             var initializer = getInitializer(checker, propertyDeclaration);
133666             if (!initializer)
133667                 return undefined;
133668             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); });
133669             return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties);
133670         }
133671         function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) {
133672             var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer);
133673             changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
133674         }
133675         function getInitializer(checker, propertyDeclaration) {
133676             return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217
133677         }
133678         function getDefaultValueFromType(checker, type) {
133679             if (type.flags & 512 /* BooleanLiteral */) {
133680                 return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue();
133681             }
133682             else if (type.isLiteral()) {
133683                 return ts.createLiteral(type.value);
133684             }
133685             else if (type.isUnion()) {
133686                 return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); });
133687             }
133688             else if (type.isClass()) {
133689                 var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
133690                 if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */))
133691                     return undefined;
133692                 var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration);
133693                 if (constructorDeclaration && constructorDeclaration.parameters.length)
133694                     return undefined;
133695                 return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
133696             }
133697             else if (checker.isArrayLikeType(type)) {
133698                 return ts.createArrayLiteral();
133699             }
133700             return undefined;
133701         }
133702     })(codefix = ts.codefix || (ts.codefix = {}));
133703 })(ts || (ts = {}));
133704 /* @internal */
133705 var ts;
133706 (function (ts) {
133707     var codefix;
133708     (function (codefix) {
133709         var fixId = "requireInTs";
133710         var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code];
133711         codefix.registerCodeFix({
133712             errorCodes: errorCodes,
133713             getCodeActions: function (context) {
133714                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); });
133715                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)];
133716             },
133717             fixIds: [fixId],
133718             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); },
133719         });
133720         function doChange(changes, sourceFile, pos, program) {
133721             var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required;
133722             changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())
133723                 ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required)
133724                 : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required)));
133725         }
133726         function getInfo(sourceFile, pos) {
133727             var parent = ts.getTokenAtPosition(sourceFile, pos).parent;
133728             if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true))
133729                 throw ts.Debug.failBadSyntaxKind(parent);
133730             var decl = ts.cast(parent.parent, ts.isVariableDeclaration);
133731             return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] };
133732         }
133733     })(codefix = ts.codefix || (ts.codefix = {}));
133734 })(ts || (ts = {}));
133735 /* @internal */
133736 var ts;
133737 (function (ts) {
133738     var codefix;
133739     (function (codefix) {
133740         var fixId = "useDefaultImport";
133741         var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code];
133742         codefix.registerCodeFix({
133743             errorCodes: errorCodes,
133744             getCodeActions: function (context) {
133745                 var sourceFile = context.sourceFile, start = context.span.start;
133746                 var info = getInfo(sourceFile, start);
133747                 if (!info)
133748                     return undefined;
133749                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); });
133750                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)];
133751             },
133752             fixIds: [fixId],
133753             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
133754                 var info = getInfo(diag.file, diag.start);
133755                 if (info)
133756                     doChange(changes, diag.file, info, context.preferences);
133757             }); },
133758         });
133759         function getInfo(sourceFile, pos) {
133760             var name = ts.getTokenAtPosition(sourceFile, pos);
133761             if (!ts.isIdentifier(name))
133762                 return undefined; // bad input
133763             var parent = name.parent;
133764             if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) {
133765                 return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression };
133766             }
133767             else if (ts.isNamespaceImport(parent)) {
133768                 var importNode = parent.parent.parent;
133769                 return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier };
133770             }
133771         }
133772         function doChange(changes, sourceFile, info, preferences) {
133773             changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences)));
133774         }
133775     })(codefix = ts.codefix || (ts.codefix = {}));
133776 })(ts || (ts = {}));
133777 /* @internal */
133778 var ts;
133779 (function (ts) {
133780     var codefix;
133781     (function (codefix) {
133782         var fixId = "useBigintLiteral";
133783         var errorCodes = [
133784             ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code,
133785         ];
133786         codefix.registerCodeFix({
133787             errorCodes: errorCodes,
133788             getCodeActions: function (context) {
133789                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); });
133790                 if (changes.length > 0) {
133791                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_a_bigint_numeric_literal, fixId, ts.Diagnostics.Convert_all_to_bigint_numeric_literals)];
133792                 }
133793             },
133794             fixIds: [fixId],
133795             getAllCodeActions: function (context) {
133796                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag); });
133797             },
133798         });
133799         function makeChange(changeTracker, sourceFile, span) {
133800             var numericLiteral = ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start), ts.isNumericLiteral);
133801             if (!numericLiteral) {
133802                 return;
133803             }
133804             // We use .getText to overcome parser inaccuracies: https://github.com/microsoft/TypeScript/issues/33298
133805             var newText = numericLiteral.getText(sourceFile) + "n";
133806             changeTracker.replaceNode(sourceFile, numericLiteral, ts.createBigIntLiteral(newText));
133807         }
133808     })(codefix = ts.codefix || (ts.codefix = {}));
133809 })(ts || (ts = {}));
133810 /* @internal */
133811 var ts;
133812 (function (ts) {
133813     var codefix;
133814     (function (codefix) {
133815         var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof";
133816         var fixId = fixIdAddMissingTypeof;
133817         var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code];
133818         codefix.registerCodeFix({
133819             errorCodes: errorCodes,
133820             getCodeActions: function (context) {
133821                 var sourceFile = context.sourceFile, span = context.span;
133822                 var importType = getImportTypeNode(sourceFile, span.start);
133823                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); });
133824                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)];
133825             },
133826             fixIds: [fixId],
133827             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
133828                 return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start));
133829             }); },
133830         });
133831         function getImportTypeNode(sourceFile, pos) {
133832             var token = ts.getTokenAtPosition(sourceFile, pos);
133833             ts.Debug.assert(token.kind === 96 /* ImportKeyword */, "This token should be an ImportKeyword");
133834             ts.Debug.assert(token.parent.kind === 188 /* ImportType */, "Token parent should be an ImportType");
133835             return token.parent;
133836         }
133837         function doChange(changes, sourceFile, importType) {
133838             var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true);
133839             changes.replaceNode(sourceFile, importType, newTypeNode);
133840         }
133841     })(codefix = ts.codefix || (ts.codefix = {}));
133842 })(ts || (ts = {}));
133843 /* @internal */
133844 var ts;
133845 (function (ts) {
133846     var codefix;
133847     (function (codefix) {
133848         var fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
133849         var fixId = fixIdAddMissingTypeof;
133850         var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
133851         codefix.registerCodeFix({
133852             errorCodes: errorCodes,
133853             getCodeActions: function (context) {
133854                 var sourceFile = context.sourceFile, span = context.span;
133855                 var info = getInfo(sourceFile, span.start);
133856                 if (!info)
133857                     return undefined;
133858                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
133859                 var name = ts.idText(info.container.name);
133860                 return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])];
133861             },
133862             fixIds: [fixId],
133863             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
133864                 var info = getInfo(diag.file, diag.start);
133865                 if (info)
133866                     doChange(changes, diag.file, info);
133867             }); }
133868         });
133869         function getInfo(sourceFile, pos) {
133870             var token = ts.getTokenAtPosition(sourceFile, pos);
133871             var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration);
133872             if (ts.isClassDeclaration(indexSignature.parent))
133873                 return undefined;
133874             var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration);
133875             return { indexSignature: indexSignature, container: container };
133876         }
133877         function createTypeAliasFromInterface(declaration, type) {
133878             return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type);
133879         }
133880         function doChange(changes, sourceFile, _a) {
133881             var indexSignature = _a.indexSignature, container = _a.container;
133882             var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members;
133883             var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); });
133884             var parameter = ts.first(indexSignature.parameters);
133885             var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type);
133886             var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(138 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type);
133887             var intersectionType = ts.createIntersectionTypeNode(__spreadArrays(ts.getAllSuperTypeNodes(container), [
133888                 mappedIntersectionType
133889             ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray)));
133890             changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
133891         }
133892     })(codefix = ts.codefix || (ts.codefix = {}));
133893 })(ts || (ts = {}));
133894 /* @internal */
133895 var ts;
133896 (function (ts) {
133897     var codefix;
133898     (function (codefix) {
133899         var fixId = "removeUnnecessaryAwait";
133900         var errorCodes = [
133901             ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code,
133902         ];
133903         codefix.registerCodeFix({
133904             errorCodes: errorCodes,
133905             getCodeActions: function (context) {
133906                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); });
133907                 if (changes.length > 0) {
133908                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unnecessary_await, fixId, ts.Diagnostics.Remove_all_unnecessary_uses_of_await)];
133909                 }
133910             },
133911             fixIds: [fixId],
133912             getAllCodeActions: function (context) {
133913                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag); });
133914             },
133915         });
133916         function makeChange(changeTracker, sourceFile, span) {
133917             var awaitKeyword = ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start), function (node) { return node.kind === 127 /* AwaitKeyword */; });
133918             var awaitExpression = awaitKeyword && ts.tryCast(awaitKeyword.parent, ts.isAwaitExpression);
133919             if (!awaitExpression) {
133920                 return;
133921             }
133922             var expressionToReplace = awaitExpression;
133923             var hasSurroundingParens = ts.isParenthesizedExpression(awaitExpression.parent);
133924             if (hasSurroundingParens) {
133925                 var leftMostExpression = ts.getLeftmostExpression(awaitExpression.expression, /*stopAtCallExpressions*/ false);
133926                 if (ts.isIdentifier(leftMostExpression)) {
133927                     var precedingToken = ts.findPrecedingToken(awaitExpression.parent.pos, sourceFile);
133928                     if (precedingToken && precedingToken.kind !== 99 /* NewKeyword */) {
133929                         expressionToReplace = awaitExpression.parent;
133930                     }
133931                 }
133932             }
133933             changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression);
133934         }
133935     })(codefix = ts.codefix || (ts.codefix = {}));
133936 })(ts || (ts = {}));
133937 /* @internal */
133938 var ts;
133939 (function (ts) {
133940     var codefix;
133941     (function (codefix) {
133942         var errorCodes = [ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code];
133943         var fixId = "splitTypeOnlyImport";
133944         codefix.registerCodeFix({
133945             errorCodes: errorCodes,
133946             fixIds: [fixId],
133947             getCodeActions: function (context) {
133948                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
133949                     return splitTypeOnlyImport(t, getImportDeclaration(context.sourceFile, context.span), context);
133950                 });
133951                 if (changes.length) {
133952                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Split_into_two_separate_import_declarations, fixId, ts.Diagnostics.Split_all_invalid_type_only_imports)];
133953                 }
133954             },
133955             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, error) {
133956                 splitTypeOnlyImport(changes, getImportDeclaration(context.sourceFile, error), context);
133957             }); },
133958         });
133959         function getImportDeclaration(sourceFile, span) {
133960             return ts.findAncestor(ts.getTokenAtPosition(sourceFile, span.start), ts.isImportDeclaration);
133961         }
133962         function splitTypeOnlyImport(changes, importDeclaration, context) {
133963             if (!importDeclaration) {
133964                 return;
133965             }
133966             var importClause = ts.Debug.checkDefined(importDeclaration.importClause);
133967             changes.replaceNode(context.sourceFile, importDeclaration, ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, importClause.name, /*namedBindings*/ undefined, importClause.isTypeOnly), importDeclaration.moduleSpecifier));
133968             changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.createImportDeclaration(
133969             /*decorators*/ undefined, 
133970             /*modifiers*/ undefined, ts.updateImportClause(importClause, /*name*/ undefined, importClause.namedBindings, importClause.isTypeOnly), importDeclaration.moduleSpecifier));
133971         }
133972     })(codefix = ts.codefix || (ts.codefix = {}));
133973 })(ts || (ts = {}));
133974 /* @internal */
133975 var ts;
133976 (function (ts) {
133977     var codefix;
133978     (function (codefix) {
133979         var fixId = "fixConvertConstToLet";
133980         var errorCodes = [ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code];
133981         codefix.registerCodeFix({
133982             errorCodes: errorCodes,
133983             getCodeActions: function (context) {
133984                 var sourceFile = context.sourceFile, span = context.span, program = context.program;
133985                 var variableStatement = getVariableStatement(sourceFile, span.start, program);
133986                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, variableStatement); });
133987                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_const_to_let, fixId, ts.Diagnostics.Convert_const_to_let)];
133988             },
133989             fixIds: [fixId]
133990         });
133991         function getVariableStatement(sourceFile, pos, program) {
133992             var token = ts.getTokenAtPosition(sourceFile, pos);
133993             var checker = program.getTypeChecker();
133994             var symbol = checker.getSymbolAtLocation(token);
133995             if (symbol) {
133996                 return symbol.valueDeclaration.parent.parent;
133997             }
133998         }
133999         function doChange(changes, sourceFile, variableStatement) {
134000             if (!variableStatement) {
134001                 return;
134002             }
134003             var start = variableStatement.getStart();
134004             changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 5 }, "let");
134005         }
134006     })(codefix = ts.codefix || (ts.codefix = {}));
134007 })(ts || (ts = {}));
134008 /* @internal */
134009 var ts;
134010 (function (ts) {
134011     var codefix;
134012     (function (codefix) {
134013         var fixId = "fixExpectedComma";
134014         var expectedErrorCode = ts.Diagnostics._0_expected.code;
134015         var errorCodes = [expectedErrorCode];
134016         codefix.registerCodeFix({
134017             errorCodes: errorCodes,
134018             getCodeActions: function (context) {
134019                 var sourceFile = context.sourceFile;
134020                 var info = getInfo(sourceFile, context.span.start, context.errorCode);
134021                 if (!info) {
134022                     return undefined;
134023                 }
134024                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
134025                 return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Change_0_to_1, ";", ","], fixId, [ts.Diagnostics.Change_0_to_1, ";", ","])];
134026             },
134027             fixIds: [fixId],
134028             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
134029                 var info = getInfo(diag.file, diag.start, diag.code);
134030                 if (info)
134031                     doChange(changes, context.sourceFile, info);
134032             }); },
134033         });
134034         function getInfo(sourceFile, pos, _) {
134035             var node = ts.getTokenAtPosition(sourceFile, pos);
134036             return (node.kind === 26 /* SemicolonToken */ &&
134037                 node.parent &&
134038                 (ts.isObjectLiteralExpression(node.parent) ||
134039                     ts.isArrayLiteralExpression(node.parent))) ? { node: node } : undefined;
134040         }
134041         function doChange(changes, sourceFile, _a) {
134042             var node = _a.node;
134043             var newNode = ts.createNode(27 /* CommaToken */);
134044             changes.replaceNode(sourceFile, node, newNode);
134045         }
134046     })(codefix = ts.codefix || (ts.codefix = {}));
134047 })(ts || (ts = {}));
134048 /* @internal */
134049 var ts;
134050 (function (ts) {
134051     var refactor;
134052     (function (refactor) {
134053         var refactorName = "Convert export";
134054         var actionNameDefaultToNamed = "Convert default export to named export";
134055         var actionNameNamedToDefault = "Convert named export to default export";
134056         refactor.registerRefactor(refactorName, {
134057             getAvailableActions: function (context) {
134058                 var info = getInfo(context);
134059                 if (!info)
134060                     return ts.emptyArray;
134061                 var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message;
134062                 var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault;
134063                 return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
134064             },
134065             getEditsForAction: function (context, actionName) {
134066                 ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault, "Unexpected action name");
134067                 var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.checkDefined(getInfo(context), "context must have info"), t, context.cancellationToken); });
134068                 return { edits: edits, renameFilename: undefined, renameLocation: undefined };
134069             },
134070         });
134071         function getInfo(context) {
134072             var file = context.file;
134073             var span = ts.getRefactorContextSpan(context);
134074             var token = ts.getTokenAtPosition(file, span.start);
134075             var exportNode = ts.getParentNodeInSpan(token, file, span);
134076             if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) {
134077                 return undefined;
134078             }
134079             var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol;
134080             var flags = ts.getModifierFlags(exportNode);
134081             var wasDefault = !!(flags & 512 /* Default */);
134082             // If source file already has a default export, don't offer refactor.
134083             if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) {
134084                 return undefined;
134085             }
134086             switch (exportNode.kind) {
134087                 case 244 /* FunctionDeclaration */:
134088                 case 245 /* ClassDeclaration */:
134089                 case 246 /* InterfaceDeclaration */:
134090                 case 248 /* EnumDeclaration */:
134091                 case 247 /* TypeAliasDeclaration */:
134092                 case 249 /* ModuleDeclaration */: {
134093                     var node = exportNode;
134094                     return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
134095                 }
134096                 case 225 /* VariableStatement */: {
134097                     var vs = exportNode;
134098                     // Must be `export const x = something;`.
134099                     if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) {
134100                         return undefined;
134101                     }
134102                     var decl = ts.first(vs.declarationList.declarations);
134103                     if (!decl.initializer)
134104                         return undefined;
134105                     ts.Debug.assert(!wasDefault, "Can't have a default flag here");
134106                     return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
134107                 }
134108                 default:
134109                     return undefined;
134110             }
134111         }
134112         function doChange(exportingSourceFile, program, info, changes, cancellationToken) {
134113             changeExport(exportingSourceFile, info, changes, program.getTypeChecker());
134114             changeImports(program, info, changes, cancellationToken);
134115         }
134116         function changeExport(exportingSourceFile, _a, changes, checker) {
134117             var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName;
134118             if (wasDefault) {
134119                 changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 84 /* DefaultKeyword */), "Should find a default keyword in modifier list"));
134120             }
134121             else {
134122                 var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 89 /* ExportKeyword */), "Should find an export keyword in modifier list");
134123                 switch (exportNode.kind) {
134124                     case 244 /* FunctionDeclaration */:
134125                     case 245 /* ClassDeclaration */:
134126                     case 246 /* InterfaceDeclaration */:
134127                         changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(84 /* DefaultKeyword */));
134128                         break;
134129                     case 225 /* VariableStatement */:
134130                         // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;`
134131                         if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) {
134132                             // We checked in `getInfo` that an initializer exists.
134133                             changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.checkDefined(ts.first(exportNode.declarationList.declarations).initializer, "Initializer was previously known to be present")));
134134                             break;
134135                         }
134136                     // falls through
134137                     case 248 /* EnumDeclaration */:
134138                     case 247 /* TypeAliasDeclaration */:
134139                     case 249 /* ModuleDeclaration */:
134140                         // `export type T = number;` -> `type T = number; export default T;`
134141                         changes.deleteModifier(exportingSourceFile, exportKeyword);
134142                         changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text)));
134143                         break;
134144                     default:
134145                         ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind);
134146                 }
134147             }
134148         }
134149         function changeImports(program, _a, changes, cancellationToken) {
134150             var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol;
134151             var checker = program.getTypeChecker();
134152             var exportSymbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol");
134153             ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) {
134154                 var importingSourceFile = ref.getSourceFile();
134155                 if (wasDefault) {
134156                     changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text);
134157                 }
134158                 else {
134159                     changeNamedToDefaultImport(importingSourceFile, ref, changes);
134160                 }
134161             });
134162         }
134163         function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) {
134164             var parent = ref.parent;
134165             switch (parent.kind) {
134166                 case 194 /* PropertyAccessExpression */:
134167                     // `a.default` --> `a.foo`
134168                     changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName));
134169                     break;
134170                 case 258 /* ImportSpecifier */:
134171                 case 263 /* ExportSpecifier */: {
134172                     var spec = parent;
134173                     // `default as foo` --> `foo`, `default as bar` --> `foo as bar`
134174                     changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text));
134175                     break;
134176                 }
134177                 case 255 /* ImportClause */: {
134178                     var clause = parent;
134179                     ts.Debug.assert(clause.name === ref, "Import clause name should match provided ref");
134180                     var spec = makeImportSpecifier(exportName, ref.text);
134181                     var namedBindings = clause.namedBindings;
134182                     if (!namedBindings) {
134183                         // `import foo from "./a";` --> `import { foo } from "./a";`
134184                         changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec]));
134185                     }
134186                     else if (namedBindings.kind === 256 /* NamespaceImport */) {
134187                         // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";`
134188                         changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) });
134189                         var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */;
134190                         var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference);
134191                         changes.insertNodeAfter(importingSourceFile, clause.parent, newImport);
134192                     }
134193                     else {
134194                         // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";`
134195                         changes.delete(importingSourceFile, ref);
134196                         changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec);
134197                     }
134198                     break;
134199                 }
134200                 default:
134201                     ts.Debug.failBadSyntaxKind(parent);
134202             }
134203         }
134204         function changeNamedToDefaultImport(importingSourceFile, ref, changes) {
134205             var parent = ref.parent;
134206             switch (parent.kind) {
134207                 case 194 /* PropertyAccessExpression */:
134208                     // `a.foo` --> `a.default`
134209                     changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default"));
134210                     break;
134211                 case 258 /* ImportSpecifier */: {
134212                     // `import { foo } from "./a";` --> `import foo from "./a";`
134213                     // `import { foo as bar } from "./a";` --> `import bar from "./a";`
134214                     var defaultImport = ts.createIdentifier(parent.name.text);
134215                     if (parent.parent.elements.length === 1) {
134216                         changes.replaceNode(importingSourceFile, parent.parent, defaultImport);
134217                     }
134218                     else {
134219                         changes.delete(importingSourceFile, parent);
134220                         changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport);
134221                     }
134222                     break;
134223                 }
134224                 case 263 /* ExportSpecifier */: {
134225                     // `export { foo } from "./a";` --> `export { default as foo } from "./a";`
134226                     // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";`
134227                     // `export { foo as default } from "./a";` --> `export { default } from "./a";`
134228                     // (Because `export foo from "./a";` isn't valid syntax.)
134229                     changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text));
134230                     break;
134231                 }
134232                 default:
134233                     ts.Debug.assertNever(parent, "Unexpected parent kind " + parent.kind);
134234             }
134235         }
134236         function makeImportSpecifier(propertyName, name) {
134237             return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
134238         }
134239         function makeExportSpecifier(propertyName, name) {
134240             return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
134241         }
134242     })(refactor = ts.refactor || (ts.refactor = {}));
134243 })(ts || (ts = {}));
134244 /* @internal */
134245 var ts;
134246 (function (ts) {
134247     var refactor;
134248     (function (refactor) {
134249         var refactorName = "Convert import";
134250         var actionNameNamespaceToNamed = "Convert namespace import to named imports";
134251         var actionNameNamedToNamespace = "Convert named imports to namespace import";
134252         refactor.registerRefactor(refactorName, {
134253             getAvailableActions: function (context) {
134254                 var i = getImportToConvert(context);
134255                 if (!i)
134256                     return ts.emptyArray;
134257                 var description = i.kind === 256 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message;
134258                 var actionName = i.kind === 256 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace;
134259                 return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
134260             },
134261             getEditsForAction: function (context, actionName) {
134262                 ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace, "Unexpected action name");
134263                 var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.checkDefined(getImportToConvert(context), "Context must provide an import to convert")); });
134264                 return { edits: edits, renameFilename: undefined, renameLocation: undefined };
134265             }
134266         });
134267         // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`.
134268         function getImportToConvert(context) {
134269             var file = context.file;
134270             var span = ts.getRefactorContextSpan(context);
134271             var token = ts.getTokenAtPosition(file, span.start);
134272             var importDecl = ts.getParentNodeInSpan(token, file, span);
134273             if (!importDecl || !ts.isImportDeclaration(importDecl))
134274                 return undefined;
134275             var importClause = importDecl.importClause;
134276             return importClause && importClause.namedBindings;
134277         }
134278         function doChange(sourceFile, program, changes, toConvert) {
134279             var checker = program.getTypeChecker();
134280             if (toConvert.kind === 256 /* NamespaceImport */) {
134281                 doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()));
134282             }
134283             else {
134284                 doChangeNamedToNamespace(sourceFile, checker, changes, toConvert);
134285             }
134286         }
134287         function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) {
134288             var usedAsNamespaceOrDefault = false;
134289             var nodesToReplace = [];
134290             var conflictingNames = ts.createMap();
134291             ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) {
134292                 if (!ts.isPropertyAccessExpression(id.parent)) {
134293                     usedAsNamespaceOrDefault = true;
134294                 }
134295                 else {
134296                     var parent = ts.cast(id.parent, ts.isPropertyAccessExpression);
134297                     var exportName = parent.name.text;
134298                     if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) {
134299                         conflictingNames.set(exportName, true);
134300                     }
134301                     ts.Debug.assert(parent.expression === id, "Parent expression should match id");
134302                     nodesToReplace.push(parent);
134303                 }
134304             });
134305             // We may need to change `mod.x` to `_x` to avoid a name conflict.
134306             var exportNameToImportName = ts.createMap();
134307             for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) {
134308                 var propertyAccess = nodesToReplace_1[_i];
134309                 var exportName = propertyAccess.name.text;
134310                 var importName = exportNameToImportName.get(exportName);
134311                 if (importName === undefined) {
134312                     exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName);
134313                 }
134314                 changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName));
134315             }
134316             var importSpecifiers = [];
134317             exportNameToImportName.forEach(function (name, propertyName) {
134318                 importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)));
134319             });
134320             var importDecl = toConvert.parent.parent;
134321             if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) {
134322                 // Need to leave the namespace import alone
134323                 changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers));
134324             }
134325             else {
134326                 changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers));
134327             }
134328         }
134329         function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) {
134330             var importDecl = toConvert.parent.parent;
134331             var moduleSpecifier = importDecl.moduleSpecifier;
134332             var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module";
134333             var namespaceNameConflicts = toConvert.elements.some(function (element) {
134334                 return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
134335                     return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true);
134336                 }) || false;
134337             });
134338             var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
134339             var neededNamedImports = [];
134340             var _loop_15 = function (element) {
134341                 var propertyName = (element.propertyName || element.name).text;
134342                 ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
134343                     var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
134344                     if (ts.isShorthandPropertyAssignment(id.parent)) {
134345                         changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access));
134346                     }
134347                     else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) {
134348                         if (!neededNamedImports.some(function (n) { return n.name === element.name; })) {
134349                             neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text)));
134350                         }
134351                     }
134352                     else {
134353                         changes.replaceNode(sourceFile, id, access);
134354                     }
134355                 });
134356             };
134357             for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
134358                 var element = _a[_i];
134359                 _loop_15(element);
134360             }
134361             changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
134362             if (neededNamedImports.length) {
134363                 changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports));
134364             }
134365         }
134366         function updateImport(old, defaultImportName, elements) {
134367             return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier);
134368         }
134369     })(refactor = ts.refactor || (ts.refactor = {}));
134370 })(ts || (ts = {}));
134371 /* @internal */
134372 var ts;
134373 (function (ts) {
134374     var refactor;
134375     (function (refactor) {
134376         var extractSymbol;
134377         (function (extractSymbol) {
134378             var refactorName = "Extract Symbol";
134379             refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction });
134380             /**
134381              * Compute the associated code actions
134382              * Exported for tests.
134383              */
134384             function getAvailableActions(context) {
134385                 var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
134386                 var targetRange = rangeToExtract.targetRange;
134387                 if (targetRange === undefined) {
134388                     return ts.emptyArray;
134389                 }
134390                 var extractions = getPossibleExtractions(targetRange, context);
134391                 if (extractions === undefined) {
134392                     // No extractions possible
134393                     return ts.emptyArray;
134394                 }
134395                 var functionActions = [];
134396                 var usedFunctionNames = ts.createMap();
134397                 var constantActions = [];
134398                 var usedConstantNames = ts.createMap();
134399                 var i = 0;
134400                 for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) {
134401                     var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction;
134402                     // Skip these since we don't have a way to report errors yet
134403                     if (functionExtraction.errors.length === 0) {
134404                         // Don't issue refactorings with duplicated names.
134405                         // Scopes come back in "innermost first" order, so extractions will
134406                         // preferentially go into nearer scopes
134407                         var description = functionExtraction.description;
134408                         if (!usedFunctionNames.has(description)) {
134409                             usedFunctionNames.set(description, true);
134410                             functionActions.push({
134411                                 description: description,
134412                                 name: "function_scope_" + i
134413                             });
134414                         }
134415                     }
134416                     // Skip these since we don't have a way to report errors yet
134417                     if (constantExtraction.errors.length === 0) {
134418                         // Don't issue refactorings with duplicated names.
134419                         // Scopes come back in "innermost first" order, so extractions will
134420                         // preferentially go into nearer scopes
134421                         var description = constantExtraction.description;
134422                         if (!usedConstantNames.has(description)) {
134423                             usedConstantNames.set(description, true);
134424                             constantActions.push({
134425                                 description: description,
134426                                 name: "constant_scope_" + i
134427                             });
134428                         }
134429                     }
134430                     // *do* increment i anyway because we'll look for the i-th scope
134431                     // later when actually doing the refactoring if the user requests it
134432                     i++;
134433                 }
134434                 var infos = [];
134435                 if (constantActions.length) {
134436                     infos.push({
134437                         name: refactorName,
134438                         description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant),
134439                         actions: constantActions
134440                     });
134441                 }
134442                 if (functionActions.length) {
134443                     infos.push({
134444                         name: refactorName,
134445                         description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function),
134446                         actions: functionActions
134447                     });
134448                 }
134449                 return infos.length ? infos : ts.emptyArray;
134450             }
134451             extractSymbol.getAvailableActions = getAvailableActions;
134452             /* Exported for tests */
134453             function getEditsForAction(context, actionName) {
134454                 var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
134455                 var targetRange = rangeToExtract.targetRange; // TODO:GH#18217
134456                 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
134457                 if (parsedFunctionIndexMatch) {
134458                     var index = +parsedFunctionIndexMatch[1];
134459                     ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index");
134460                     return getFunctionExtractionAtIndex(targetRange, context, index);
134461                 }
134462                 var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName);
134463                 if (parsedConstantIndexMatch) {
134464                     var index = +parsedConstantIndexMatch[1];
134465                     ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index");
134466                     return getConstantExtractionAtIndex(targetRange, context, index);
134467                 }
134468                 ts.Debug.fail("Unrecognized action name");
134469             }
134470             extractSymbol.getEditsForAction = getEditsForAction;
134471             // Move these into diagnostic messages if they become user-facing
134472             var Messages;
134473             (function (Messages) {
134474                 function createMessage(message) {
134475                     return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message };
134476                 }
134477                 Messages.cannotExtractRange = createMessage("Cannot extract range.");
134478                 Messages.cannotExtractImport = createMessage("Cannot extract import statement.");
134479                 Messages.cannotExtractSuper = createMessage("Cannot extract super call.");
134480                 Messages.cannotExtractJSDoc = createMessage("Cannot extract JSDoc.");
134481                 Messages.cannotExtractEmpty = createMessage("Cannot extract empty range.");
134482                 Messages.expressionExpected = createMessage("expression expected.");
134483                 Messages.uselessConstantType = createMessage("No reason to extract constant of type.");
134484                 Messages.statementOrExpressionExpected = createMessage("Statement or expression expected.");
134485                 Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements.");
134486                 Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement.");
134487                 Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
134488                 Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
134489                 Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
134490                 Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
134491                 Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier.");
134492                 Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
134493                 Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
134494                 Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
134495                 Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
134496                 Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
134497                 Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function");
134498                 Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
134499                 Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
134500             })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {}));
134501             var RangeFacts;
134502             (function (RangeFacts) {
134503                 RangeFacts[RangeFacts["None"] = 0] = "None";
134504                 RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn";
134505                 RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator";
134506                 RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction";
134507                 RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis";
134508                 /**
134509                  * The range is in a function which needs the 'static' modifier in a class
134510                  */
134511                 RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion";
134512             })(RangeFacts || (RangeFacts = {}));
134513             /**
134514              * getRangeToExtract takes a span inside a text file and returns either an expression or an array
134515              * of statements representing the minimum set of nodes needed to extract the entire span. This
134516              * process may fail, in which case a set of errors is returned instead (these are currently
134517              * not shown to the user, but can be used by us diagnostically)
134518              */
134519             // exported only for tests
134520             function getRangeToExtract(sourceFile, span) {
134521                 var length = span.length;
134522                 if (length === 0) {
134523                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] };
134524                 }
134525                 // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span.
134526                 // This may fail (e.g. you select two statements in the root of a source file)
134527                 var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span);
134528                 // Do the same for the ending position
134529                 var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span);
134530                 var declarations = [];
134531                 // We'll modify these flags as we walk the tree to collect data
134532                 // about what things need to be done as part of the extraction.
134533                 var rangeFacts = RangeFacts.None;
134534                 if (!start || !end) {
134535                     // cannot find either start or end node
134536                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
134537                 }
134538                 if (start.parent !== end.parent) {
134539                     // start and end nodes belong to different subtrees
134540                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
134541                 }
134542                 if (start !== end) {
134543                     // start and end should be statements and parent should be either block or a source file
134544                     if (!isBlockLike(start.parent)) {
134545                         return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
134546                     }
134547                     var statements = [];
134548                     var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248
134549                     for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) {
134550                         var statement = _a[_i];
134551                         if (statement === start || statements.length) {
134552                             var errors_1 = checkNode(statement);
134553                             if (errors_1) {
134554                                 return { errors: errors_1 };
134555                             }
134556                             statements.push(statement);
134557                         }
134558                         if (statement === end) {
134559                             break;
134560                         }
134561                     }
134562                     if (!statements.length) {
134563                         // https://github.com/Microsoft/TypeScript/issues/20559
134564                         // Ranges like [|case 1: break;|] will fail to populate `statements` because
134565                         // they will never find `start` in `start.parent.statements`.
134566                         // Consider: We could support ranges like [|case 1:|] by refining them to just
134567                         // the expression.
134568                         return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
134569                     }
134570                     return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } };
134571                 }
134572                 if (ts.isJSDoc(start)) {
134573                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] };
134574                 }
134575                 if (ts.isReturnStatement(start) && !start.expression) {
134576                     // Makes no sense to extract an expression-less return statement.
134577                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
134578                 }
134579                 // We have a single node (start)
134580                 var node = refineNode(start);
134581                 var errors = checkRootNode(node) || checkNode(node);
134582                 if (errors) {
134583                     return { errors: errors };
134584                 }
134585                 return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217
134586                 /**
134587                  * Attempt to refine the extraction node (generally, by shrinking it) to produce better results.
134588                  * @param node The unrefined extraction node.
134589                  */
134590                 function refineNode(node) {
134591                     if (ts.isReturnStatement(node)) {
134592                         if (node.expression) {
134593                             return node.expression;
134594                         }
134595                     }
134596                     else if (ts.isVariableStatement(node)) {
134597                         var numInitializers = 0;
134598                         var lastInitializer = void 0;
134599                         for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
134600                             var declaration = _a[_i];
134601                             if (declaration.initializer) {
134602                                 numInitializers++;
134603                                 lastInitializer = declaration.initializer;
134604                             }
134605                         }
134606                         if (numInitializers === 1) {
134607                             return lastInitializer;
134608                         }
134609                         // No special handling if there are multiple initializers.
134610                     }
134611                     else if (ts.isVariableDeclaration(node)) {
134612                         if (node.initializer) {
134613                             return node.initializer;
134614                         }
134615                     }
134616                     return node;
134617                 }
134618                 function checkRootNode(node) {
134619                     if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) {
134620                         return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)];
134621                     }
134622                     return undefined;
134623                 }
134624                 function checkForStaticContext(nodeToCheck, containingClass) {
134625                     var current = nodeToCheck;
134626                     while (current !== containingClass) {
134627                         if (current.kind === 159 /* PropertyDeclaration */) {
134628                             if (ts.hasModifier(current, 32 /* Static */)) {
134629                                 rangeFacts |= RangeFacts.InStaticRegion;
134630                             }
134631                             break;
134632                         }
134633                         else if (current.kind === 156 /* Parameter */) {
134634                             var ctorOrMethod = ts.getContainingFunction(current);
134635                             if (ctorOrMethod.kind === 162 /* Constructor */) {
134636                                 rangeFacts |= RangeFacts.InStaticRegion;
134637                             }
134638                             break;
134639                         }
134640                         else if (current.kind === 161 /* MethodDeclaration */) {
134641                             if (ts.hasModifier(current, 32 /* Static */)) {
134642                                 rangeFacts |= RangeFacts.InStaticRegion;
134643                             }
134644                         }
134645                         current = current.parent;
134646                     }
134647                 }
134648                 // Verifies whether we can actually extract this node or not.
134649                 function checkNode(nodeToCheck) {
134650                     var PermittedJumps;
134651                     (function (PermittedJumps) {
134652                         PermittedJumps[PermittedJumps["None"] = 0] = "None";
134653                         PermittedJumps[PermittedJumps["Break"] = 1] = "Break";
134654                         PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue";
134655                         PermittedJumps[PermittedJumps["Return"] = 4] = "Return";
134656                     })(PermittedJumps || (PermittedJumps = {}));
134657                     // We believe it's true because the node is from the (unmodified) tree.
134658                     ts.Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)");
134659                     // For understanding how skipTrivia functioned:
134660                     ts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)");
134661                     if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) {
134662                         return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
134663                     }
134664                     if (nodeToCheck.flags & 8388608 /* Ambient */) {
134665                         return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)];
134666                     }
134667                     // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default)
134668                     var containingClass = ts.getContainingClass(nodeToCheck);
134669                     if (containingClass) {
134670                         checkForStaticContext(nodeToCheck, containingClass);
134671                     }
134672                     var errors;
134673                     var permittedJumps = 4 /* Return */;
134674                     var seenLabels;
134675                     visit(nodeToCheck);
134676                     return errors;
134677                     function visit(node) {
134678                         if (errors) {
134679                             // already found an error - can stop now
134680                             return true;
134681                         }
134682                         if (ts.isDeclaration(node)) {
134683                             var declaringNode = (node.kind === 242 /* VariableDeclaration */) ? node.parent.parent : node;
134684                             if (ts.hasModifier(declaringNode, 1 /* Export */)) {
134685                                 // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`)
134686                                 // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`!
134687                                 // Also TODO: GH#19956
134688                                 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity));
134689                                 return true;
134690                             }
134691                             declarations.push(node.symbol);
134692                         }
134693                         // Some things can't be extracted in certain situations
134694                         switch (node.kind) {
134695                             case 254 /* ImportDeclaration */:
134696                                 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport));
134697                                 return true;
134698                             case 102 /* SuperKeyword */:
134699                                 // For a super *constructor call*, we have to be extracting the entire class,
134700                                 // but a super *method call* simply implies a 'this' reference
134701                                 if (node.parent.kind === 196 /* CallExpression */) {
134702                                     // Super constructor call
134703                                     var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217
134704                                     if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) {
134705                                         (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper));
134706                                         return true;
134707                                     }
134708                                 }
134709                                 else {
134710                                     rangeFacts |= RangeFacts.UsesThis;
134711                                 }
134712                                 break;
134713                         }
134714                         if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) {
134715                             switch (node.kind) {
134716                                 case 244 /* FunctionDeclaration */:
134717                                 case 245 /* ClassDeclaration */:
134718                                     if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
134719                                         // You cannot extract global declarations
134720                                         (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
134721                                     }
134722                                     break;
134723                             }
134724                             // do not dive into functions or classes
134725                             return false;
134726                         }
134727                         var savedPermittedJumps = permittedJumps;
134728                         switch (node.kind) {
134729                             case 227 /* IfStatement */:
134730                                 permittedJumps = 0 /* None */;
134731                                 break;
134732                             case 240 /* TryStatement */:
134733                                 // forbid all jumps inside try blocks
134734                                 permittedJumps = 0 /* None */;
134735                                 break;
134736                             case 223 /* Block */:
134737                                 if (node.parent && node.parent.kind === 240 /* TryStatement */ && node.parent.finallyBlock === node) {
134738                                     // allow unconditional returns from finally blocks
134739                                     permittedJumps = 4 /* Return */;
134740                                 }
134741                                 break;
134742                             case 278 /* DefaultClause */:
134743                             case 277 /* CaseClause */:
134744                                 // allow unlabeled break inside case clauses
134745                                 permittedJumps |= 1 /* Break */;
134746                                 break;
134747                             default:
134748                                 if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) {
134749                                     // allow unlabeled break/continue inside loops
134750                                     permittedJumps |= 1 /* Break */ | 2 /* Continue */;
134751                                 }
134752                                 break;
134753                         }
134754                         switch (node.kind) {
134755                             case 183 /* ThisType */:
134756                             case 104 /* ThisKeyword */:
134757                                 rangeFacts |= RangeFacts.UsesThis;
134758                                 break;
134759                             case 238 /* LabeledStatement */: {
134760                                 var label = node.label;
134761                                 (seenLabels || (seenLabels = [])).push(label.escapedText);
134762                                 ts.forEachChild(node, visit);
134763                                 seenLabels.pop();
134764                                 break;
134765                             }
134766                             case 234 /* BreakStatement */:
134767                             case 233 /* ContinueStatement */: {
134768                                 var label = node.label;
134769                                 if (label) {
134770                                     if (!ts.contains(seenLabels, label.escapedText)) {
134771                                         // attempts to jump to label that is not in range to be extracted
134772                                         (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
134773                                     }
134774                                 }
134775                                 else {
134776                                     if (!(permittedJumps & (node.kind === 234 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) {
134777                                         // attempt to break or continue in a forbidden context
134778                                         (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
134779                                     }
134780                                 }
134781                                 break;
134782                             }
134783                             case 206 /* AwaitExpression */:
134784                                 rangeFacts |= RangeFacts.IsAsyncFunction;
134785                                 break;
134786                             case 212 /* YieldExpression */:
134787                                 rangeFacts |= RangeFacts.IsGenerator;
134788                                 break;
134789                             case 235 /* ReturnStatement */:
134790                                 if (permittedJumps & 4 /* Return */) {
134791                                     rangeFacts |= RangeFacts.HasReturn;
134792                                 }
134793                                 else {
134794                                     (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement));
134795                                 }
134796                                 break;
134797                             default:
134798                                 ts.forEachChild(node, visit);
134799                                 break;
134800                         }
134801                         permittedJumps = savedPermittedJumps;
134802                     }
134803                 }
134804             }
134805             extractSymbol.getRangeToExtract = getRangeToExtract;
134806             function getStatementOrExpressionRange(node) {
134807                 if (ts.isStatement(node)) {
134808                     return [node];
134809                 }
134810                 else if (ts.isExpressionNode(node)) {
134811                     // If our selection is the expression in an ExpressionStatement, expand
134812                     // the selection to include the enclosing Statement (this stops us
134813                     // from trying to care about the return value of the extracted function
134814                     // and eliminates double semicolon insertion in certain scenarios)
134815                     return ts.isExpressionStatement(node.parent) ? [node.parent] : node;
134816                 }
134817                 return undefined;
134818             }
134819             function isScope(node) {
134820                 return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node);
134821             }
134822             /**
134823              * Computes possible places we could extract the function into. For example,
134824              * you may be able to extract into a class method *or* local closure *or* namespace function,
134825              * depending on what's in the extracted body.
134826              */
134827             function collectEnclosingScopes(range) {
134828                 var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range;
134829                 if (range.facts & RangeFacts.UsesThis) {
134830                     // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class
134831                     var containingClass = ts.getContainingClass(current);
134832                     if (containingClass) {
134833                         var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration);
134834                         return containingFunction
134835                             ? [containingFunction, containingClass]
134836                             : [containingClass];
134837                     }
134838                 }
134839                 var scopes = [];
134840                 while (true) {
134841                     current = current.parent;
134842                     // A function parameter's initializer is actually in the outer scope, not the function declaration
134843                     if (current.kind === 156 /* Parameter */) {
134844                         // Skip all the way to the outer scope of the function that declared this parameter
134845                         current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent;
134846                     }
134847                     // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of.
134848                     // Walk up to the closest parent of a place where we can logically put a sibling:
134849                     //  * Function declaration
134850                     //  * Class declaration or expression
134851                     //  * Module/namespace or source file
134852                     if (isScope(current)) {
134853                         scopes.push(current);
134854                         if (current.kind === 290 /* SourceFile */) {
134855                             return scopes;
134856                         }
134857                     }
134858                 }
134859             }
134860             function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) {
134861                 var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations;
134862                 ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
134863                 context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217
134864                 return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context);
134865             }
134866             function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) {
134867                 var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations;
134868                 ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
134869                 ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?");
134870                 context.cancellationToken.throwIfCancellationRequested();
134871                 var expression = ts.isExpression(target)
134872                     ? target
134873                     : target.statements[0].expression;
134874                 return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context);
134875             }
134876             /**
134877              * Given a piece of text to extract ('targetRange'), computes a list of possible extractions.
134878              * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes
134879              * or an error explaining why we can't extract into that scope.
134880              */
134881             function getPossibleExtractions(targetRange, context) {
134882                 var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope;
134883                 // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547
134884                 var extractions = scopes.map(function (scope, i) {
134885                     var functionDescriptionPart = getDescriptionForFunctionInScope(scope);
134886                     var constantDescriptionPart = getDescriptionForConstantInScope(scope);
134887                     var scopeDescription = ts.isFunctionLikeDeclaration(scope)
134888                         ? getDescriptionForFunctionLikeDeclaration(scope)
134889                         : ts.isClassLike(scope)
134890                             ? getDescriptionForClassLikeDeclaration(scope)
134891                             : getDescriptionForModuleLikeDeclaration(scope);
134892                     var functionDescription;
134893                     var constantDescription;
134894                     if (scopeDescription === 1 /* Global */) {
134895                         functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]);
134896                         constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]);
134897                     }
134898                     else if (scopeDescription === 0 /* Module */) {
134899                         functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]);
134900                         constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]);
134901                     }
134902                     else {
134903                         functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]);
134904                         constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]);
134905                     }
134906                     // Customize the phrasing for the innermost scope to increase clarity.
134907                     if (i === 0 && !ts.isClassLike(scope)) {
134908                         constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]);
134909                     }
134910                     return {
134911                         functionExtraction: {
134912                             description: functionDescription,
134913                             errors: functionErrorsPerScope[i],
134914                         },
134915                         constantExtraction: {
134916                             description: constantDescription,
134917                             errors: constantErrorsPerScope[i],
134918                         },
134919                     };
134920                 });
134921                 return extractions;
134922             }
134923             function getPossibleExtractionsWorker(targetRange, context) {
134924                 var sourceFile = context.file;
134925                 var scopes = collectEnclosingScopes(targetRange);
134926                 var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile);
134927                 var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken);
134928                 return { scopes: scopes, readsAndWrites: readsAndWrites };
134929             }
134930             function getDescriptionForFunctionInScope(scope) {
134931                 return ts.isFunctionLikeDeclaration(scope)
134932                     ? "inner function"
134933                     : ts.isClassLike(scope)
134934                         ? "method"
134935                         : "function";
134936             }
134937             function getDescriptionForConstantInScope(scope) {
134938                 return ts.isClassLike(scope)
134939                     ? "readonly field"
134940                     : "constant";
134941             }
134942             function getDescriptionForFunctionLikeDeclaration(scope) {
134943                 switch (scope.kind) {
134944                     case 162 /* Constructor */:
134945                         return "constructor";
134946                     case 201 /* FunctionExpression */:
134947                     case 244 /* FunctionDeclaration */:
134948                         return scope.name
134949                             ? "function '" + scope.name.text + "'"
134950                             : ts.ANONYMOUS;
134951                     case 202 /* ArrowFunction */:
134952                         return "arrow function";
134953                     case 161 /* MethodDeclaration */:
134954                         return "method '" + scope.name.getText() + "'";
134955                     case 163 /* GetAccessor */:
134956                         return "'get " + scope.name.getText() + "'";
134957                     case 164 /* SetAccessor */:
134958                         return "'set " + scope.name.getText() + "'";
134959                     default:
134960                         throw ts.Debug.assertNever(scope, "Unexpected scope kind " + scope.kind);
134961                 }
134962             }
134963             function getDescriptionForClassLikeDeclaration(scope) {
134964                 return scope.kind === 245 /* ClassDeclaration */
134965                     ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration"
134966                     : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression";
134967             }
134968             function getDescriptionForModuleLikeDeclaration(scope) {
134969                 return scope.kind === 250 /* ModuleBlock */
134970                     ? "namespace '" + scope.parent.name.getText() + "'"
134971                     : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */;
134972             }
134973             var SpecialScope;
134974             (function (SpecialScope) {
134975                 SpecialScope[SpecialScope["Module"] = 0] = "Module";
134976                 SpecialScope[SpecialScope["Global"] = 1] = "Global";
134977             })(SpecialScope || (SpecialScope = {}));
134978             /**
134979              * Result of 'extractRange' operation for a specific scope.
134980              * Stores either a list of changes that should be applied to extract a range or a list of errors
134981              */
134982             function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) {
134983                 var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions;
134984                 var checker = context.program.getTypeChecker();
134985                 var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions());
134986                 var importAdder = ts.codefix.createImportAdder(context.file, context.program, context.preferences, context.host);
134987                 // Make a unique name for the extracted function
134988                 var file = scope.getSourceFile();
134989                 var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file);
134990                 var isJS = ts.isInJSFile(scope);
134991                 var functionName = ts.createIdentifier(functionNameText);
134992                 var returnType;
134993                 var parameters = [];
134994                 var callArguments = [];
134995                 var writes;
134996                 usagesInScope.forEach(function (usage, name) {
134997                     var typeNode;
134998                     if (!isJS) {
134999                         var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
135000                         // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
135001                         type = checker.getBaseTypeOfLiteralType(type);
135002                         typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */);
135003                     }
135004                     var paramDecl = ts.createParameter(
135005                     /*decorators*/ undefined, 
135006                     /*modifiers*/ undefined, 
135007                     /*dotDotDotToken*/ undefined, 
135008                     /*name*/ name, 
135009                     /*questionToken*/ undefined, typeNode);
135010                     parameters.push(paramDecl);
135011                     if (usage.usage === 2 /* Write */) {
135012                         (writes || (writes = [])).push(usage);
135013                     }
135014                     callArguments.push(ts.createIdentifier(name));
135015                 });
135016                 var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); });
135017                 var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder);
135018                 var typeParameters = sortedTypeParametersAndDeclarations.length === 0
135019                     ? undefined
135020                     : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; });
135021                 // Strictly speaking, we should check whether each name actually binds to the appropriate type
135022                 // parameter.  In cases of shadowing, they may not.
135023                 var callTypeArguments = typeParameters !== undefined
135024                     ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); })
135025                     : undefined;
135026                 // Provide explicit return types for contextually-typed functions
135027                 // to avoid problems when there are literal types present
135028                 if (ts.isExpression(node) && !isJS) {
135029                     var contextualType = checker.getContextualType(node);
135030                     returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217
135031                 }
135032                 var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty;
135033                 ts.suppressLeadingAndTrailingTrivia(body);
135034                 var newFunction;
135035                 if (ts.isClassLike(scope)) {
135036                     // always create private method in TypeScript files
135037                     var modifiers = isJS ? [] : [ts.createToken(117 /* PrivateKeyword */)];
135038                     if (range.facts & RangeFacts.InStaticRegion) {
135039                         modifiers.push(ts.createToken(120 /* StaticKeyword */));
135040                     }
135041                     if (range.facts & RangeFacts.IsAsyncFunction) {
135042                         modifiers.push(ts.createToken(126 /* AsyncKeyword */));
135043                     }
135044                     newFunction = ts.createMethod(
135045                     /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(41 /* AsteriskToken */) : undefined, functionName, 
135046                     /*questionToken*/ undefined, typeParameters, parameters, returnType, body);
135047                 }
135048                 else {
135049                     newFunction = ts.createFunctionDeclaration(
135050                     /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(126 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(41 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body);
135051                 }
135052                 var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
135053                 var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end;
135054                 var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope);
135055                 if (nodeToInsertBefore) {
135056                     changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true);
135057                 }
135058                 else {
135059                     changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction);
135060                 }
135061                 importAdder.writeFixes(changeTracker);
135062                 var newNodes = [];
135063                 // replace range with function call
135064                 var called = getCalledExpression(scope, range, functionNameText);
135065                 var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference
135066                 callArguments);
135067                 if (range.facts & RangeFacts.IsGenerator) {
135068                     call = ts.createYield(ts.createToken(41 /* AsteriskToken */), call);
135069                 }
135070                 if (range.facts & RangeFacts.IsAsyncFunction) {
135071                     call = ts.createAwait(call);
135072                 }
135073                 if (exposedVariableDeclarations.length && !writes) {
135074                     // No need to mix declarations and writes.
135075                     // How could any variables be exposed if there's a return statement?
135076                     ts.Debug.assert(!returnValueProperty, "Expected no returnValueProperty");
135077                     ts.Debug.assert(!(range.facts & RangeFacts.HasReturn), "Expected RangeFacts.HasReturn flag to be unset");
135078                     if (exposedVariableDeclarations.length === 1) {
135079                         // Declaring exactly one variable: let x = newFunction();
135080                         var variableDeclaration = exposedVariableDeclarations[0];
135081                         newNodes.push(ts.createVariableStatement(
135082                         /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns
135083                         variableDeclaration.parent.flags)));
135084                     }
135085                     else {
135086                         // Declaring multiple variables / return properties:
135087                         //   let {x, y} = newFunction();
135088                         var bindingElements = [];
135089                         var typeElements = [];
135090                         var commonNodeFlags = exposedVariableDeclarations[0].parent.flags;
135091                         var sawExplicitType = false;
135092                         for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) {
135093                             var variableDeclaration = exposedVariableDeclarations_1[_i];
135094                             bindingElements.push(ts.createBindingElement(
135095                             /*dotDotDotToken*/ undefined, 
135096                             /*propertyName*/ undefined, 
135097                             /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name)));
135098                             // Being returned through an object literal will have widened the type.
135099                             var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */);
135100                             typeElements.push(ts.createPropertySignature(
135101                             /*modifiers*/ undefined, 
135102                             /*name*/ variableDeclaration.symbol.name, 
135103                             /*questionToken*/ undefined, 
135104                             /*type*/ variableType, 
135105                             /*initializer*/ undefined));
135106                             sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined;
135107                             commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags;
135108                         }
135109                         var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined;
135110                         if (typeLiteral) {
135111                             ts.setEmitFlags(typeLiteral, 1 /* SingleLine */);
135112                         }
135113                         newNodes.push(ts.createVariableStatement(
135114                         /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), 
135115                             /*type*/ typeLiteral, 
135116                             /*initializer*/ call)], commonNodeFlags)));
135117                     }
135118                 }
135119                 else if (exposedVariableDeclarations.length || writes) {
135120                     if (exposedVariableDeclarations.length) {
135121                         // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping.
135122                         for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) {
135123                             var variableDeclaration = exposedVariableDeclarations_2[_c];
135124                             var flags = variableDeclaration.parent.flags;
135125                             if (flags & 2 /* Const */) {
135126                                 flags = (flags & ~2 /* Const */) | 1 /* Let */;
135127                             }
135128                             newNodes.push(ts.createVariableStatement(
135129                             /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags)));
135130                         }
135131                     }
135132                     if (returnValueProperty) {
135133                         // has both writes and return, need to create variable declaration to hold return value;
135134                         newNodes.push(ts.createVariableStatement(
135135                         /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */)));
135136                     }
135137                     var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
135138                     if (returnValueProperty) {
135139                         assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty));
135140                     }
135141                     // propagate writes back
135142                     if (assignments.length === 1) {
135143                         // We would only have introduced a return value property if there had been
135144                         // other assignments to make.
135145                         ts.Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here");
135146                         newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call)));
135147                         if (range.facts & RangeFacts.HasReturn) {
135148                             newNodes.push(ts.createReturn());
135149                         }
135150                     }
135151                     else {
135152                         // emit e.g.
135153                         //   { a, b, __return } = newFunction(a, b);
135154                         //   return __return;
135155                         newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call)));
135156                         if (returnValueProperty) {
135157                             newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty)));
135158                         }
135159                     }
135160                 }
135161                 else {
135162                     if (range.facts & RangeFacts.HasReturn) {
135163                         newNodes.push(ts.createReturn(call));
135164                     }
135165                     else if (isReadonlyArray(range.range)) {
135166                         newNodes.push(ts.createStatement(call));
135167                     }
135168                     else {
135169                         newNodes.push(call);
135170                     }
135171                 }
135172                 if (isReadonlyArray(range.range)) {
135173                     changeTracker.replaceNodeRangeWithNodes(context.file, ts.first(range.range), ts.last(range.range), newNodes);
135174                 }
135175                 else {
135176                     changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes);
135177                 }
135178                 var edits = changeTracker.getChanges();
135179                 var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range;
135180                 var renameFilename = renameRange.getSourceFile().fileName;
135181                 var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false);
135182                 return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
135183                 function getTypeDeepCloneUnionUndefined(typeNode) {
135184                     if (typeNode === undefined) {
135185                         return undefined;
135186                     }
135187                     var clone = ts.getSynthesizedDeepClone(typeNode);
135188                     var withoutParens = clone;
135189                     while (ts.isParenthesizedTypeNode(withoutParens)) {
135190                         withoutParens = withoutParens.type;
135191                     }
135192                     return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 146 /* UndefinedKeyword */; })
135193                         ? clone
135194                         : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
135195                 }
135196             }
135197             /**
135198              * Result of 'extractRange' operation for a specific scope.
135199              * Stores either a list of changes that should be applied to extract a range or a list of errors
135200              */
135201             function extractConstantInScope(node, scope, _a, rangeFacts, context) {
135202                 var _b;
135203                 var substitutions = _a.substitutions;
135204                 var checker = context.program.getTypeChecker();
135205                 // Make a unique name for the extracted variable
135206                 var file = scope.getSourceFile();
135207                 var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file);
135208                 var isJS = ts.isInJSFile(scope);
135209                 var variableType = isJS || !checker.isContextSensitive(node)
135210                     ? undefined
135211                     : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217
135212                 var initializer = transformConstantInitializer(node, substitutions);
135213                 (_b = transformFunctionInitializerAndType(variableType, initializer), variableType = _b.variableType, initializer = _b.initializer);
135214                 ts.suppressLeadingAndTrailingTrivia(initializer);
135215                 var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
135216                 if (ts.isClassLike(scope)) {
135217                     ts.Debug.assert(!isJS, "Cannot extract to a JS class"); // See CannotExtractToJSClass
135218                     var modifiers = [];
135219                     modifiers.push(ts.createToken(117 /* PrivateKeyword */));
135220                     if (rangeFacts & RangeFacts.InStaticRegion) {
135221                         modifiers.push(ts.createToken(120 /* StaticKeyword */));
135222                     }
135223                     modifiers.push(ts.createToken(138 /* ReadonlyKeyword */));
135224                     var newVariable = ts.createProperty(
135225                     /*decorators*/ undefined, modifiers, localNameText, 
135226                     /*questionToken*/ undefined, variableType, initializer);
135227                     var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion
135228                         ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217
135229                         : ts.createThis(), ts.createIdentifier(localNameText));
135230                     // Declare
135231                     var maxInsertionPos = node.pos;
135232                     var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope);
135233                     changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true);
135234                     // Consume
135235                     changeTracker.replaceNode(context.file, node, localReference);
135236                 }
135237                 else {
135238                     var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer);
135239                     // If the node is part of an initializer in a list of variable declarations, insert a new
135240                     // variable declaration into the list (in case it depends on earlier ones).
135241                     // CONSIDER: If the declaration list isn't const, we might want to split it into multiple
135242                     // lists so that the newly extracted one can be const.
135243                     var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope);
135244                     if (oldVariableDeclaration) {
135245                         // Declare
135246                         // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`)
135247                         changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration);
135248                         // Consume
135249                         var localReference = ts.createIdentifier(localNameText);
135250                         changeTracker.replaceNode(context.file, node, localReference);
135251                     }
135252                     else if (node.parent.kind === 226 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) {
135253                         // If the parent is an expression statement and the target scope is the immediately enclosing one,
135254                         // replace the statement with the declaration.
135255                         var newVariableStatement = ts.createVariableStatement(
135256                         /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */));
135257                         changeTracker.replaceNode(context.file, node.parent, newVariableStatement);
135258                     }
135259                     else {
135260                         var newVariableStatement = ts.createVariableStatement(
135261                         /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */));
135262                         // Declare
135263                         var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope);
135264                         if (nodeToInsertBefore.pos === 0) {
135265                             changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false);
135266                         }
135267                         else {
135268                             changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false);
135269                         }
135270                         // Consume
135271                         if (node.parent.kind === 226 /* ExpressionStatement */) {
135272                             // If the parent is an expression statement, delete it.
135273                             changeTracker.delete(context.file, node.parent);
135274                         }
135275                         else {
135276                             var localReference = ts.createIdentifier(localNameText);
135277                             changeTracker.replaceNode(context.file, node, localReference);
135278                         }
135279                     }
135280                 }
135281                 var edits = changeTracker.getChanges();
135282                 var renameFilename = node.getSourceFile().fileName;
135283                 var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true);
135284                 return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
135285                 function transformFunctionInitializerAndType(variableType, initializer) {
135286                     // If no contextual type exists there is nothing to transfer to the function signature
135287                     if (variableType === undefined)
135288                         return { variableType: variableType, initializer: initializer };
135289                     // Only do this for function expressions and arrow functions that are not generic
135290                     if (!ts.isFunctionExpression(initializer) && !ts.isArrowFunction(initializer) || !!initializer.typeParameters)
135291                         return { variableType: variableType, initializer: initializer };
135292                     var functionType = checker.getTypeAtLocation(node);
135293                     var functionSignature = ts.singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */));
135294                     // If no function signature, maybe there was an error, do nothing
135295                     if (!functionSignature)
135296                         return { variableType: variableType, initializer: initializer };
135297                     // If the function signature has generic type parameters we don't attempt to move the parameters
135298                     if (!!functionSignature.getTypeParameters())
135299                         return { variableType: variableType, initializer: initializer };
135300                     // We add parameter types if needed
135301                     var parameters = [];
135302                     var hasAny = false;
135303                     for (var _i = 0, _a = initializer.parameters; _i < _a.length; _i++) {
135304                         var p = _a[_i];
135305                         if (p.type) {
135306                             parameters.push(p);
135307                         }
135308                         else {
135309                             var paramType = checker.getTypeAtLocation(p);
135310                             if (paramType === checker.getAnyType())
135311                                 hasAny = true;
135312                             parameters.push(ts.updateParameter(p, p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */), p.initializer));
135313                         }
135314                     }
135315                     // If a parameter was inferred as any we skip adding function parameters at all.
135316                     // Turning an implicit any (which under common settings is a error) to an explicit
135317                     // is probably actually a worse refactor outcome.
135318                     if (hasAny)
135319                         return { variableType: variableType, initializer: initializer };
135320                     variableType = undefined;
135321                     if (ts.isArrowFunction(initializer)) {
135322                         initializer = ts.updateArrowFunction(initializer, node.modifiers, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer.equalsGreaterThanToken, initializer.body);
135323                     }
135324                     else {
135325                         if (functionSignature && !!functionSignature.thisParameter) {
135326                             var firstParameter = ts.firstOrUndefined(parameters);
135327                             // If the function signature has a this parameter and if the first defined parameter is not the this parameter, we must add it
135328                             // Note: If this parameter was already there, it would have been previously updated with the type if not type was present
135329                             if ((!firstParameter || (ts.isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) {
135330                                 var thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node);
135331                                 parameters.splice(0, 0, ts.createParameter(
135332                                 /* decorators */ undefined, 
135333                                 /* modifiers */ undefined, 
135334                                 /* dotDotDotToken */ undefined, "this", 
135335                                 /* questionToken */ undefined, checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */)));
135336                             }
135337                         }
135338                         initializer = ts.updateFunctionExpression(initializer, node.modifiers, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer.body);
135339                     }
135340                     return { variableType: variableType, initializer: initializer };
135341                 }
135342             }
135343             function getContainingVariableDeclarationIfInList(node, scope) {
135344                 var prevNode;
135345                 while (node !== undefined && node !== scope) {
135346                     if (ts.isVariableDeclaration(node) &&
135347                         node.initializer === prevNode &&
135348                         ts.isVariableDeclarationList(node.parent) &&
135349                         node.parent.declarations.length > 1) {
135350                         return node;
135351                     }
135352                     prevNode = node;
135353                     node = node.parent;
135354                 }
135355             }
135356             function getFirstDeclaration(type) {
135357                 var firstDeclaration;
135358                 var symbol = type.symbol;
135359                 if (symbol && symbol.declarations) {
135360                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
135361                         var declaration = _a[_i];
135362                         if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) {
135363                             firstDeclaration = declaration;
135364                         }
135365                     }
135366                 }
135367                 return firstDeclaration;
135368             }
135369             function compareTypesByDeclarationOrder(_a, _b) {
135370                 var type1 = _a.type, declaration1 = _a.declaration;
135371                 var type2 = _b.type, declaration2 = _b.declaration;
135372                 return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues)
135373                     || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "")
135374                     || ts.compareValues(type1.id, type2.id);
135375             }
135376             function getCalledExpression(scope, range, functionNameText) {
135377                 var functionReference = ts.createIdentifier(functionNameText);
135378                 if (ts.isClassLike(scope)) {
135379                     var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217
135380                     return ts.createPropertyAccess(lhs, functionReference);
135381                 }
135382                 else {
135383                     return functionReference;
135384                 }
135385             }
135386             function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) {
135387                 var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0;
135388                 if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) {
135389                     // already block, no declarations or writes to propagate back, no substitutions - can use node as is
135390                     return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined };
135391                 }
135392                 var returnValueProperty;
135393                 var ignoreReturns = false;
135394                 var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]);
135395                 // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions
135396                 if (hasWritesOrVariableDeclarations || substitutions.size) {
135397                     var rewrittenStatements = ts.visitNodes(statements, visitor).slice();
135398                     if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) {
135399                         // add return at the end to propagate writes back in case if control flow falls out of the function body
135400                         // it is ok to know that range has at least one return since it we only allow unconditional returns
135401                         var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
135402                         if (assignments.length === 1) {
135403                             rewrittenStatements.push(ts.createReturn(assignments[0].name));
135404                         }
135405                         else {
135406                             rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments)));
135407                         }
135408                     }
135409                     return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty };
135410                 }
135411                 else {
135412                     return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined };
135413                 }
135414                 function visitor(node) {
135415                     if (!ignoreReturns && node.kind === 235 /* ReturnStatement */ && hasWritesOrVariableDeclarations) {
135416                         var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
135417                         if (node.expression) {
135418                             if (!returnValueProperty) {
135419                                 returnValueProperty = "__return";
135420                             }
135421                             assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor)));
135422                         }
135423                         if (assignments.length === 1) {
135424                             return ts.createReturn(assignments[0].name);
135425                         }
135426                         else {
135427                             return ts.createReturn(ts.createObjectLiteral(assignments));
135428                         }
135429                     }
135430                     else {
135431                         var oldIgnoreReturns = ignoreReturns;
135432                         ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node);
135433                         var substitution = substitutions.get(ts.getNodeId(node).toString());
135434                         var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext);
135435                         ignoreReturns = oldIgnoreReturns;
135436                         return result;
135437                     }
135438                 }
135439             }
135440             function transformConstantInitializer(initializer, substitutions) {
135441                 return substitutions.size
135442                     ? visitor(initializer)
135443                     : initializer;
135444                 function visitor(node) {
135445                     var substitution = substitutions.get(ts.getNodeId(node).toString());
135446                     return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext);
135447                 }
135448             }
135449             function getStatementsOrClassElements(scope) {
135450                 if (ts.isFunctionLikeDeclaration(scope)) {
135451                     var body = scope.body; // TODO: GH#18217
135452                     if (ts.isBlock(body)) {
135453                         return body.statements;
135454                     }
135455                 }
135456                 else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) {
135457                     return scope.statements;
135458                 }
135459                 else if (ts.isClassLike(scope)) {
135460                     return scope.members;
135461                 }
135462                 else {
135463                     ts.assertType(scope);
135464                 }
135465                 return ts.emptyArray;
135466             }
135467             /**
135468              * If `scope` contains a function after `minPos`, then return the first such function.
135469              * Otherwise, return `undefined`.
135470              */
135471             function getNodeToInsertFunctionBefore(minPos, scope) {
135472                 return ts.find(getStatementsOrClassElements(scope), function (child) {
135473                     return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child);
135474                 });
135475             }
135476             function getNodeToInsertPropertyBefore(maxPos, scope) {
135477                 var members = scope.members;
135478                 ts.Debug.assert(members.length > 0, "Found no members"); // There must be at least one child, since we extracted from one.
135479                 var prevMember;
135480                 var allProperties = true;
135481                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
135482                     var member = members_1[_i];
135483                     if (member.pos > maxPos) {
135484                         return prevMember || members[0];
135485                     }
135486                     if (allProperties && !ts.isPropertyDeclaration(member)) {
135487                         // If it is non-vacuously true that all preceding members are properties,
135488                         // insert before the current member (i.e. at the end of the list of properties).
135489                         if (prevMember !== undefined) {
135490                             return member;
135491                         }
135492                         allProperties = false;
135493                     }
135494                     prevMember = member;
135495                 }
135496                 if (prevMember === undefined)
135497                     return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember.
135498                 return prevMember;
135499             }
135500             function getNodeToInsertConstantBefore(node, scope) {
135501                 ts.Debug.assert(!ts.isClassLike(scope));
135502                 var prevScope;
135503                 for (var curr = node; curr !== scope; curr = curr.parent) {
135504                     if (isScope(curr)) {
135505                         prevScope = curr;
135506                     }
135507                 }
135508                 for (var curr = (prevScope || node).parent;; curr = curr.parent) {
135509                     if (isBlockLike(curr)) {
135510                         var prevStatement = void 0;
135511                         for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) {
135512                             var statement = _a[_i];
135513                             if (statement.pos > node.pos) {
135514                                 break;
135515                             }
135516                             prevStatement = statement;
135517                         }
135518                         if (!prevStatement && ts.isCaseClause(curr)) {
135519                             // We must have been in the expression of the case clause.
135520                             ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement");
135521                             return curr.parent.parent;
135522                         }
135523                         // There must be at least one statement since we started in one.
135524                         return ts.Debug.checkDefined(prevStatement, "prevStatement failed to get set");
135525                     }
135526                     ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope");
135527                 }
135528             }
135529             function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) {
135530                 var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); });
135531                 var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); });
135532                 // TODO: GH#18217 `variableAssignments` not possibly undefined!
135533                 return variableAssignments === undefined
135534                     ? writeAssignments
135535                     : writeAssignments === undefined
135536                         ? variableAssignments
135537                         : variableAssignments.concat(writeAssignments);
135538             }
135539             function isReadonlyArray(v) {
135540                 return ts.isArray(v);
135541             }
135542             /**
135543              * Produces a range that spans the entirety of nodes, given a selection
135544              * that might start/end in the middle of nodes.
135545              *
135546              * For example, when the user makes a selection like this
135547              *                     v---v
135548              *   var someThing = foo + bar;
135549              *  this returns     ^-------^
135550              */
135551             function getEnclosingTextRange(targetRange, sourceFile) {
135552                 return isReadonlyArray(targetRange.range)
135553                     ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() }
135554                     : targetRange.range;
135555             }
135556             var Usage;
135557             (function (Usage) {
135558                 // value should be passed to extracted method
135559                 Usage[Usage["Read"] = 1] = "Read";
135560                 // value should be passed to extracted method and propagated back
135561                 Usage[Usage["Write"] = 2] = "Write";
135562             })(Usage || (Usage = {}));
135563             function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) {
135564                 var allTypeParameterUsages = ts.createMap(); // Key is type ID
135565                 var usagesPerScope = [];
135566                 var substitutionsPerScope = [];
135567                 var functionErrorsPerScope = [];
135568                 var constantErrorsPerScope = [];
135569                 var visibleDeclarationsInExtractedRange = [];
135570                 var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID
135571                 var exposedVariableDeclarations = [];
135572                 var firstExposedNonVariableDeclaration;
135573                 var expression = !isReadonlyArray(targetRange.range)
135574                     ? targetRange.range
135575                     : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0])
135576                         ? targetRange.range[0].expression
135577                         : undefined;
135578                 var expressionDiagnostic;
135579                 if (expression === undefined) {
135580                     var statements = targetRange.range;
135581                     var start = ts.first(statements).getStart();
135582                     var end = ts.last(statements).end;
135583                     expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected);
135584                 }
135585                 else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) {
135586                     expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType);
135587                 }
135588                 // initialize results
135589                 for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) {
135590                     var scope = scopes_1[_i];
135591                     usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() });
135592                     substitutionsPerScope.push(ts.createMap());
135593                     functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 244 /* FunctionDeclaration */
135594                         ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)]
135595                         : []);
135596                     var constantErrors = [];
135597                     if (expressionDiagnostic) {
135598                         constantErrors.push(expressionDiagnostic);
135599                     }
135600                     if (ts.isClassLike(scope) && ts.isInJSFile(scope)) {
135601                         constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass));
135602                     }
135603                     if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) {
135604                         // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this
135605                         constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction));
135606                     }
135607                     constantErrorsPerScope.push(constantErrors);
135608                 }
135609                 var seenUsages = ts.createMap();
135610                 var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range;
135611                 var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range;
135612                 var inGenericContext = isInGenericContext(unmodifiedNode);
135613                 collectUsages(target);
135614                 // Unfortunately, this code takes advantage of the knowledge that the generated method
135615                 // will use the contextual type of an expression as the return type of the extracted
135616                 // method (and will therefore "use" all the types involved).
135617                 if (inGenericContext && !isReadonlyArray(targetRange.range)) {
135618                     var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217
135619                     recordTypeParameterUsages(contextualType);
135620                 }
135621                 if (allTypeParameterUsages.size > 0) {
135622                     var seenTypeParameterUsages = ts.createMap(); // Key is type ID
135623                     var i_1 = 0;
135624                     for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) {
135625                         if (curr === scopes[i_1]) {
135626                             // Copy current contents of seenTypeParameterUsages into scope.
135627                             seenTypeParameterUsages.forEach(function (typeParameter, id) {
135628                                 usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter);
135629                             });
135630                             i_1++;
135631                         }
135632                         // Note that we add the current node's type parameters *after* updating the corresponding scope.
135633                         if (ts.isDeclarationWithTypeParameters(curr)) {
135634                             for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) {
135635                                 var typeParameterDecl = _b[_a];
135636                                 var typeParameter = checker.getTypeAtLocation(typeParameterDecl);
135637                                 if (allTypeParameterUsages.has(typeParameter.id.toString())) {
135638                                     seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter);
135639                                 }
135640                             }
135641                         }
135642                     }
135643                     // If we didn't get through all the scopes, then there were some that weren't in our
135644                     // parent chain (impossible at time of writing).  A conservative solution would be to
135645                     // copy allTypeParameterUsages into all remaining scopes.
135646                     ts.Debug.assert(i_1 === scopes.length, "Should have iterated all scopes");
135647                 }
135648                 // If there are any declarations in the extracted block that are used in the same enclosing
135649                 // lexical scope, we can't move the extraction "up" as those declarations will become unreachable
135650                 if (visibleDeclarationsInExtractedRange.length) {
135651                     var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent)
135652                         ? scopes[0]
135653                         : ts.getEnclosingBlockScopeContainer(scopes[0]);
135654                     ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
135655                 }
135656                 var _loop_16 = function (i) {
135657                     var scopeUsages = usagesPerScope[i];
135658                     // Special case: in the innermost scope, all usages are available.
135659                     // (The computed value reflects the value at the top-level of the scope, but the
135660                     // local will actually be declared at the same level as the extracted expression).
135661                     if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
135662                         var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
135663                         constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
135664                     }
135665                     var hasWrite = false;
135666                     var readonlyClassPropertyWrite;
135667                     usagesPerScope[i].usages.forEach(function (value) {
135668                         if (value.usage === 2 /* Write */) {
135669                             hasWrite = true;
135670                             if (value.symbol.flags & 106500 /* ClassMember */ &&
135671                                 value.symbol.valueDeclaration &&
135672                                 ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) {
135673                                 readonlyClassPropertyWrite = value.symbol.valueDeclaration;
135674                             }
135675                         }
135676                     });
135677                     // If an expression was extracted, then there shouldn't have been any variable declarations.
135678                     ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted");
135679                     if (hasWrite && !isReadonlyArray(targetRange.range)) {
135680                         var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression);
135681                         functionErrorsPerScope[i].push(diag);
135682                         constantErrorsPerScope[i].push(diag);
135683                     }
135684                     else if (readonlyClassPropertyWrite && i > 0) {
135685                         var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor);
135686                         functionErrorsPerScope[i].push(diag);
135687                         constantErrorsPerScope[i].push(diag);
135688                     }
135689                     else if (firstExposedNonVariableDeclaration) {
135690                         var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity);
135691                         functionErrorsPerScope[i].push(diag);
135692                         constantErrorsPerScope[i].push(diag);
135693                     }
135694                 };
135695                 for (var i = 0; i < scopes.length; i++) {
135696                     _loop_16(i);
135697                 }
135698                 return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
135699                 function isInGenericContext(node) {
135700                     return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; });
135701                 }
135702                 function recordTypeParameterUsages(type) {
135703                     // PERF: This is potentially very expensive.  `type` could be a library type with
135704                     // a lot of properties, each of which the walker will visit.  Unfortunately, the
135705                     // solution isn't as trivial as filtering to user types because of (e.g.) Array.
135706                     var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); });
135707                     var visitedTypes = symbolWalker.walkType(type).visitedTypes;
135708                     for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) {
135709                         var visitedType = visitedTypes_1[_i];
135710                         if (visitedType.isTypeParameter()) {
135711                             allTypeParameterUsages.set(visitedType.id.toString(), visitedType);
135712                         }
135713                     }
135714                 }
135715                 function collectUsages(node, valueUsage) {
135716                     if (valueUsage === void 0) { valueUsage = 1 /* Read */; }
135717                     if (inGenericContext) {
135718                         var type = checker.getTypeAtLocation(node);
135719                         recordTypeParameterUsages(type);
135720                     }
135721                     if (ts.isDeclaration(node) && node.symbol) {
135722                         visibleDeclarationsInExtractedRange.push(node);
135723                     }
135724                     if (ts.isAssignmentExpression(node)) {
135725                         // use 'write' as default usage for values
135726                         collectUsages(node.left, 2 /* Write */);
135727                         collectUsages(node.right);
135728                     }
135729                     else if (ts.isUnaryExpressionWithWrite(node)) {
135730                         collectUsages(node.operand, 2 /* Write */);
135731                     }
135732                     else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
135733                         // use 'write' as default usage for values
135734                         ts.forEachChild(node, collectUsages);
135735                     }
135736                     else if (ts.isIdentifier(node)) {
135737                         if (!node.parent) {
135738                             return;
135739                         }
135740                         if (ts.isQualifiedName(node.parent) && node !== node.parent.left) {
135741                             return;
135742                         }
135743                         if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) {
135744                             return;
135745                         }
135746                         recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node));
135747                     }
135748                     else {
135749                         ts.forEachChild(node, collectUsages);
135750                     }
135751                 }
135752                 function recordUsage(n, usage, isTypeNode) {
135753                     var symbolId = recordUsagebySymbol(n, usage, isTypeNode);
135754                     if (symbolId) {
135755                         for (var i = 0; i < scopes.length; i++) {
135756                             // push substitution from map<symbolId, subst> to map<nodeId, subst> to simplify rewriting
135757                             var substitution = substitutionsPerScope[i].get(symbolId);
135758                             if (substitution) {
135759                                 usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution);
135760                             }
135761                         }
135762                     }
135763                 }
135764                 function recordUsagebySymbol(identifier, usage, isTypeName) {
135765                     var symbol = getSymbolReferencedByIdentifier(identifier);
135766                     if (!symbol) {
135767                         // cannot find symbol - do nothing
135768                         return undefined;
135769                     }
135770                     var symbolId = ts.getSymbolId(symbol).toString();
135771                     var lastUsage = seenUsages.get(symbolId);
135772                     // there are two kinds of value usages
135773                     // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter
135774                     // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and
135775                     //   returned as a return value
135776                     // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read'
135777                     // since all information is already recorded
135778                     if (lastUsage && lastUsage >= usage) {
135779                         return symbolId;
135780                     }
135781                     seenUsages.set(symbolId, usage);
135782                     if (lastUsage) {
135783                         // if we get here this means that we are trying to handle 'write' and 'read' was already processed
135784                         // walk scopes and update existing records.
135785                         for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) {
135786                             var perScope = usagesPerScope_1[_i];
135787                             var prevEntry = perScope.usages.get(identifier.text);
135788                             if (prevEntry) {
135789                                 perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier });
135790                             }
135791                         }
135792                         return symbolId;
135793                     }
135794                     // find first declaration in this file
135795                     var decls = symbol.getDeclarations();
135796                     var declInFile = decls && ts.find(decls, function (d) { return d.getSourceFile() === sourceFile; });
135797                     if (!declInFile) {
135798                         return undefined;
135799                     }
135800                     if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) {
135801                         // declaration is located in range to be extracted - do nothing
135802                         return undefined;
135803                     }
135804                     if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) {
135805                         // this is write to a reference located outside of the target scope and range is extracted into generator
135806                         // currently this is unsupported scenario
135807                         var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators);
135808                         for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) {
135809                             var errors = functionErrorsPerScope_1[_a];
135810                             errors.push(diag);
135811                         }
135812                         for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) {
135813                             var errors = constantErrorsPerScope_1[_b];
135814                             errors.push(diag);
135815                         }
135816                     }
135817                     for (var i = 0; i < scopes.length; i++) {
135818                         var scope = scopes[i];
135819                         var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false);
135820                         if (resolvedSymbol === symbol) {
135821                             continue;
135822                         }
135823                         if (!substitutionsPerScope[i].has(symbolId)) {
135824                             var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName);
135825                             if (substitution) {
135826                                 substitutionsPerScope[i].set(symbolId, substitution);
135827                             }
135828                             else if (isTypeName) {
135829                                 // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument
135830                                 // so there's no problem.
135831                                 if (!(symbol.flags & 262144 /* TypeParameter */)) {
135832                                     var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope);
135833                                     functionErrorsPerScope[i].push(diag);
135834                                     constantErrorsPerScope[i].push(diag);
135835                                 }
135836                             }
135837                             else {
135838                                 usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier });
135839                             }
135840                         }
135841                     }
135842                     return symbolId;
135843                 }
135844                 function checkForUsedDeclarations(node) {
135845                     // If this node is entirely within the original extraction range, we don't need to do anything.
135846                     if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) {
135847                         return;
135848                     }
135849                     // Otherwise check and recurse.
135850                     var sym = ts.isIdentifier(node)
135851                         ? getSymbolReferencedByIdentifier(node)
135852                         : checker.getSymbolAtLocation(node);
135853                     if (sym) {
135854                         var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; });
135855                         if (decl) {
135856                             if (ts.isVariableDeclaration(decl)) {
135857                                 var idString = decl.symbol.id.toString();
135858                                 if (!exposedVariableSymbolSet.has(idString)) {
135859                                     exposedVariableDeclarations.push(decl);
135860                                     exposedVariableSymbolSet.set(idString, true);
135861                                 }
135862                             }
135863                             else {
135864                                 // CONSIDER: this includes binding elements, which we could
135865                                 // expose in the same way as variables.
135866                                 firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl;
135867                             }
135868                         }
135869                     }
135870                     ts.forEachChild(node, checkForUsedDeclarations);
135871                 }
135872                 /**
135873                  * Return the symbol referenced by an identifier (even if it declares a different symbol).
135874                  */
135875                 function getSymbolReferencedByIdentifier(identifier) {
135876                     // If the identifier is both a property name and its value, we're only interested in its value
135877                     // (since the name is a declaration and will be included in the extracted range).
135878                     return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier
135879                         ? checker.getShorthandAssignmentValueSymbol(identifier.parent)
135880                         : checker.getSymbolAtLocation(identifier);
135881                 }
135882                 function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) {
135883                     if (!symbol) {
135884                         return undefined;
135885                     }
135886                     var decls = symbol.getDeclarations();
135887                     if (decls && decls.some(function (d) { return d.parent === scopeDecl; })) {
135888                         return ts.createIdentifier(symbol.name);
135889                     }
135890                     var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode);
135891                     if (prefix === undefined) {
135892                         return undefined;
135893                     }
135894                     return isTypeNode
135895                         ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name))
135896                         : ts.createPropertyAccess(prefix, symbol.name);
135897                 }
135898             }
135899             /**
135900              * Computes whether or not a node represents an expression in a position where it could
135901              * be extracted.
135902              * The isExpression() in utilities.ts returns some false positives we need to handle,
135903              * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression
135904              * in the sense of something that you could extract on
135905              */
135906             function isExtractableExpression(node) {
135907                 var parent = node.parent;
135908                 switch (parent.kind) {
135909                     case 284 /* EnumMember */:
135910                         return false;
135911                 }
135912                 switch (node.kind) {
135913                     case 10 /* StringLiteral */:
135914                         return parent.kind !== 254 /* ImportDeclaration */ &&
135915                             parent.kind !== 258 /* ImportSpecifier */;
135916                     case 213 /* SpreadElement */:
135917                     case 189 /* ObjectBindingPattern */:
135918                     case 191 /* BindingElement */:
135919                         return false;
135920                     case 75 /* Identifier */:
135921                         return parent.kind !== 191 /* BindingElement */ &&
135922                             parent.kind !== 258 /* ImportSpecifier */ &&
135923                             parent.kind !== 263 /* ExportSpecifier */;
135924                 }
135925                 return true;
135926             }
135927             function isBlockLike(node) {
135928                 switch (node.kind) {
135929                     case 223 /* Block */:
135930                     case 290 /* SourceFile */:
135931                     case 250 /* ModuleBlock */:
135932                     case 277 /* CaseClause */:
135933                         return true;
135934                     default:
135935                         return false;
135936                 }
135937             }
135938         })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {}));
135939     })(refactor = ts.refactor || (ts.refactor = {}));
135940 })(ts || (ts = {}));
135941 /* @internal */
135942 var ts;
135943 (function (ts) {
135944     var refactor;
135945     (function (refactor) {
135946         var refactorName = "Extract type";
135947         var extractToTypeAlias = "Extract to type alias";
135948         var extractToInterface = "Extract to interface";
135949         var extractToTypeDef = "Extract to typedef";
135950         refactor.registerRefactor(refactorName, {
135951             getAvailableActions: function (context) {
135952                 var info = getRangeToExtract(context);
135953                 if (!info)
135954                     return ts.emptyArray;
135955                 return [{
135956                         name: refactorName,
135957                         description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_type),
135958                         actions: info.isJS ? [{
135959                                 name: extractToTypeDef, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_typedef)
135960                             }] : ts.append([{
135961                                 name: extractToTypeAlias, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_type_alias)
135962                             }], info.typeElements && {
135963                             name: extractToInterface, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_interface)
135964                         })
135965                     }];
135966             },
135967             getEditsForAction: function (context, actionName) {
135968                 var file = context.file;
135969                 var info = ts.Debug.checkDefined(getRangeToExtract(context), "Expected to find a range to extract");
135970                 var name = ts.getUniqueName("NewType", file);
135971                 var edits = ts.textChanges.ChangeTracker.with(context, function (changes) {
135972                     switch (actionName) {
135973                         case extractToTypeAlias:
135974                             ts.Debug.assert(!info.isJS, "Invalid actionName/JS combo");
135975                             return doTypeAliasChange(changes, file, name, info);
135976                         case extractToTypeDef:
135977                             ts.Debug.assert(info.isJS, "Invalid actionName/JS combo");
135978                             return doTypedefChange(changes, file, name, info);
135979                         case extractToInterface:
135980                             ts.Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo");
135981                             return doInterfaceChange(changes, file, name, info);
135982                         default:
135983                             ts.Debug.fail("Unexpected action name");
135984                     }
135985                 });
135986                 var renameFilename = file.fileName;
135987                 var renameLocation = ts.getRenameLocation(edits, renameFilename, name, /*preferLastLocation*/ false);
135988                 return { edits: edits, renameFilename: renameFilename, renameLocation: renameLocation };
135989             }
135990         });
135991         function getRangeToExtract(context) {
135992             var file = context.file, startPosition = context.startPosition;
135993             var isJS = ts.isSourceFileJS(file);
135994             var current = ts.getTokenAtPosition(file, startPosition);
135995             var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
135996             var selection = ts.findAncestor(current, (function (node) { return node.parent && rangeContainsSkipTrivia(range, node, file) && !rangeContainsSkipTrivia(range, node.parent, file); }));
135997             if (!selection || !ts.isTypeNode(selection))
135998                 return undefined;
135999             var checker = context.program.getTypeChecker();
136000             var firstStatement = ts.Debug.checkDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement");
136001             var typeParameters = collectTypeParameters(checker, selection, firstStatement, file);
136002             if (!typeParameters)
136003                 return undefined;
136004             var typeElements = flattenTypeLiteralNodeReference(checker, selection);
136005             return { isJS: isJS, selection: selection, firstStatement: firstStatement, typeParameters: typeParameters, typeElements: typeElements };
136006         }
136007         function flattenTypeLiteralNodeReference(checker, node) {
136008             if (!node)
136009                 return undefined;
136010             if (ts.isIntersectionTypeNode(node)) {
136011                 var result = [];
136012                 var seen_1 = ts.createMap();
136013                 for (var _i = 0, _a = node.types; _i < _a.length; _i++) {
136014                     var type = _a[_i];
136015                     var flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type);
136016                     if (!flattenedTypeMembers || !flattenedTypeMembers.every(function (type) { return type.name && ts.addToSeen(seen_1, ts.getNameFromPropertyName(type.name)); })) {
136017                         return undefined;
136018                     }
136019                     ts.addRange(result, flattenedTypeMembers);
136020                 }
136021                 return result;
136022             }
136023             else if (ts.isParenthesizedTypeNode(node)) {
136024                 return flattenTypeLiteralNodeReference(checker, node.type);
136025             }
136026             else if (ts.isTypeLiteralNode(node)) {
136027                 return node.members;
136028             }
136029             return undefined;
136030         }
136031         function rangeContainsSkipTrivia(r1, node, file) {
136032             return ts.rangeContainsStartEnd(r1, ts.skipTrivia(file.text, node.pos), node.end);
136033         }
136034         function collectTypeParameters(checker, selection, statement, file) {
136035             var result = [];
136036             return visitor(selection) ? undefined : result;
136037             function visitor(node) {
136038                 if (ts.isTypeReferenceNode(node)) {
136039                     if (ts.isIdentifier(node.typeName)) {
136040                         var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true);
136041                         if (symbol) {
136042                             var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration);
136043                             if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) {
136044                                 result.push(declaration);
136045                             }
136046                         }
136047                     }
136048                 }
136049                 else if (ts.isInferTypeNode(node)) {
136050                     var conditionalTypeNode = ts.findAncestor(node, function (n) { return ts.isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file); });
136051                     if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) {
136052                         return true;
136053                     }
136054                 }
136055                 else if ((ts.isTypePredicateNode(node) || ts.isThisTypeNode(node))) {
136056                     var functionLikeNode = ts.findAncestor(node.parent, ts.isFunctionLike);
136057                     if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) {
136058                         return true;
136059                     }
136060                 }
136061                 else if (ts.isTypeQueryNode(node)) {
136062                     if (ts.isIdentifier(node.exprName)) {
136063                         var symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */, /* excludeGlobals */ false);
136064                         if (symbol && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) {
136065                             return true;
136066                         }
136067                     }
136068                     else {
136069                         if (ts.isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) {
136070                             return true;
136071                         }
136072                     }
136073                 }
136074                 return ts.forEachChild(node, visitor);
136075             }
136076         }
136077         function doTypeAliasChange(changes, file, name, info) {
136078             var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters;
136079             var newTypeNode = ts.createTypeAliasDeclaration(
136080             /* decorators */ undefined, 
136081             /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.updateTypeParameterDeclaration(id, id.name, id.constraint, /* defaultType */ undefined); }), selection);
136082             changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true);
136083             changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
136084         }
136085         function doInterfaceChange(changes, file, name, info) {
136086             var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters, typeElements = info.typeElements;
136087             var newTypeNode = ts.createInterfaceDeclaration(
136088             /* decorators */ undefined, 
136089             /* modifiers */ undefined, name, typeParameters, 
136090             /* heritageClauses */ undefined, typeElements);
136091             changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true);
136092             changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
136093         }
136094         function doTypedefChange(changes, file, name, info) {
136095             var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters;
136096             var node = ts.createNode(322 /* JSDocTypedefTag */);
136097             node.tagName = ts.createIdentifier("typedef"); // TODO: jsdoc factory https://github.com/Microsoft/TypeScript/pull/29539
136098             node.fullName = ts.createIdentifier(name);
136099             node.name = node.fullName;
136100             node.typeExpression = ts.createJSDocTypeExpression(selection);
136101             var templates = [];
136102             ts.forEach(typeParameters, function (typeParameter) {
136103                 var constraint = ts.getEffectiveConstraintOfTypeParameter(typeParameter);
136104                 var template = ts.createNode(321 /* JSDocTemplateTag */);
136105                 template.tagName = ts.createIdentifier("template");
136106                 template.constraint = constraint && ts.cast(constraint, ts.isJSDocTypeExpression);
136107                 var parameter = ts.createNode(155 /* TypeParameter */);
136108                 parameter.name = typeParameter.name;
136109                 template.typeParameters = ts.createNodeArray([parameter]);
136110                 templates.push(template);
136111             });
136112             changes.insertNodeBefore(file, firstStatement, ts.createJSDocComment(/* comment */ undefined, ts.createNodeArray(ts.concatenate(templates, [node]))), /* blankLineBetween */ true);
136113             changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
136114         }
136115     })(refactor = ts.refactor || (ts.refactor = {}));
136116 })(ts || (ts = {}));
136117 /* @internal */
136118 var ts;
136119 (function (ts) {
136120     var refactor;
136121     (function (refactor) {
136122         var generateGetAccessorAndSetAccessor;
136123         (function (generateGetAccessorAndSetAccessor) {
136124             var actionName = "Generate 'get' and 'set' accessors";
136125             var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message;
136126             refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
136127             function getAvailableActions(context) {
136128                 if (!getConvertibleFieldAtPosition(context))
136129                     return ts.emptyArray;
136130                 return [{
136131                         name: actionName,
136132                         description: actionDescription,
136133                         actions: [
136134                             {
136135                                 name: actionName,
136136                                 description: actionDescription
136137                             }
136138                         ]
136139                     }];
136140             }
136141             function getEditsForAction(context, _actionName) {
136142                 var file = context.file;
136143                 var fieldInfo = getConvertibleFieldAtPosition(context);
136144                 if (!fieldInfo)
136145                     return undefined;
136146                 var isJS = ts.isSourceFileJS(file);
136147                 var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
136148                 var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor;
136149                 ts.suppressLeadingAndTrailingTrivia(fieldName);
136150                 ts.suppressLeadingAndTrailingTrivia(accessorName);
136151                 ts.suppressLeadingAndTrailingTrivia(declaration);
136152                 ts.suppressLeadingAndTrailingTrivia(container);
136153                 var isInClassLike = ts.isClassLike(container);
136154                 // avoid Readonly modifier because it will convert to get accessor
136155                 var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
136156                 var accessorModifiers = isInClassLike
136157                     ? !modifierFlags || modifierFlags & 8 /* Private */
136158                         ? getModifiers(isJS, isStatic, 119 /* PublicKeyword */)
136159                         : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
136160                     : undefined;
136161                 var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 117 /* PrivateKeyword */) : undefined;
136162                 updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
136163                 var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
136164                 ts.suppressLeadingAndTrailingTrivia(getAccessor);
136165                 insertAccessor(changeTracker, file, getAccessor, declaration, container);
136166                 if (isReadonly) {
136167                     // readonly modifier only existed in classLikeDeclaration
136168                     var constructor = ts.getFirstConstructorWithBody(container);
136169                     if (constructor) {
136170                         updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
136171                     }
136172                 }
136173                 else {
136174                     var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
136175                     ts.suppressLeadingAndTrailingTrivia(setAccessor);
136176                     insertAccessor(changeTracker, file, setAccessor, declaration, container);
136177                 }
136178                 var edits = changeTracker.getChanges();
136179                 var renameFilename = file.fileName;
136180                 var nameNeedRename = renameAccessor ? accessorName : fieldName;
136181                 var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1;
136182                 var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration));
136183                 return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
136184             }
136185             function isConvertibleName(name) {
136186                 return ts.isIdentifier(name) || ts.isStringLiteral(name);
136187             }
136188             function isAcceptedDeclaration(node) {
136189                 return ts.isParameterPropertyDeclaration(node, node.parent) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node);
136190             }
136191             function createPropertyName(name, originalName) {
136192                 return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name);
136193             }
136194             function createAccessorAccessExpression(fieldName, isStatic, container) {
136195                 var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217
136196                 return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName));
136197             }
136198             function getModifiers(isJS, isStatic, accessModifier) {
136199                 var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(120 /* StaticKeyword */) : undefined);
136200                 return modifiers && ts.createNodeArray(modifiers);
136201             }
136202             function getConvertibleFieldAtPosition(context) {
136203                 var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition;
136204                 var node = ts.getTokenAtPosition(file, startPosition);
136205                 var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
136206                 // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier
136207                 var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
136208                 if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217
136209                     || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
136210                     return undefined;
136211                 var name = declaration.name.text;
136212                 var startWithUnderscore = ts.startsWithUnderscore(name);
136213                 var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name);
136214                 var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name);
136215                 return {
136216                     isStatic: ts.hasStaticModifier(declaration),
136217                     isReadonly: ts.hasReadonlyModifier(declaration),
136218                     type: ts.getTypeAnnotationNode(declaration),
136219                     container: declaration.kind === 156 /* Parameter */ ? declaration.parent.parent : declaration.parent,
136220                     originalName: declaration.name.text,
136221                     declaration: declaration,
136222                     fieldName: fieldName,
136223                     accessorName: accessorName,
136224                     renameAccessor: startWithUnderscore
136225                 };
136226             }
136227             function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
136228                 return ts.createGetAccessor(
136229                 /*decorators*/ undefined, modifiers, accessorName, 
136230                 /*parameters*/ undefined, // TODO: GH#18217
136231                 type, ts.createBlock([
136232                     ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container))
136233                 ], /*multiLine*/ true));
136234             }
136235             function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
136236                 return ts.createSetAccessor(
136237                 /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter(
136238                     /*decorators*/ undefined, 
136239                     /*modifiers*/ undefined, 
136240                     /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), 
136241                     /*questionToken*/ undefined, type)], ts.createBlock([
136242                     ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value")))
136243                 ], /*multiLine*/ true));
136244             }
136245             function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
136246                 var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
136247                 changeTracker.replaceNode(file, declaration, property);
136248             }
136249             function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
136250                 var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
136251                 changeTracker.replacePropertyAssignment(file, declaration, assignment);
136252             }
136253             function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
136254                 if (ts.isPropertyDeclaration(declaration)) {
136255                     updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
136256                 }
136257                 else if (ts.isPropertyAssignment(declaration)) {
136258                     updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
136259                 }
136260                 else {
136261                     changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
136262                 }
136263             }
136264             function insertAccessor(changeTracker, file, accessor, declaration, container) {
136265                 ts.isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertNodeAtClassStart(file, container, accessor) :
136266                     ts.isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) :
136267                         changeTracker.insertNodeAfter(file, declaration, accessor);
136268             }
136269             function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
136270                 if (!constructor.body)
136271                     return;
136272                 constructor.body.forEachChild(function recur(node) {
136273                     if (ts.isElementAccessExpression(node) &&
136274                         node.expression.kind === 104 /* ThisKeyword */ &&
136275                         ts.isStringLiteral(node.argumentExpression) &&
136276                         node.argumentExpression.text === originalName &&
136277                         ts.isWriteAccess(node)) {
136278                         changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName));
136279                     }
136280                     if (ts.isPropertyAccessExpression(node) && node.expression.kind === 104 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) {
136281                         changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName));
136282                     }
136283                     if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
136284                         node.forEachChild(recur);
136285                     }
136286                 });
136287             }
136288         })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
136289     })(refactor = ts.refactor || (ts.refactor = {}));
136290 })(ts || (ts = {}));
136291 /* @internal */
136292 var ts;
136293 (function (ts) {
136294     var refactor;
136295     (function (refactor) {
136296         var refactorName = "Move to a new file";
136297         refactor.registerRefactor(refactorName, {
136298             getAvailableActions: function (context) {
136299                 if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined)
136300                     return ts.emptyArray;
136301                 var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
136302                 return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
136303             },
136304             getEditsForAction: function (context, actionName) {
136305                 ts.Debug.assert(actionName === refactorName, "Wrong refactor invoked");
136306                 var statements = ts.Debug.checkDefined(getStatementsToMove(context));
136307                 var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); });
136308                 return { edits: edits, renameFilename: undefined, renameLocation: undefined };
136309             }
136310         });
136311         function getRangeToMove(context) {
136312             var file = context.file;
136313             var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
136314             var statements = file.statements;
136315             var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
136316             if (startNodeIndex === -1)
136317                 return undefined;
136318             var startStatement = statements[startNodeIndex];
136319             if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) {
136320                 return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] };
136321             }
136322             // Can't only partially include the start node or be partially into the next node
136323             if (range.pos > startStatement.getStart(file))
136324                 return undefined;
136325             var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
136326             // Can't be partially into the next node
136327             if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
136328                 return undefined;
136329             return {
136330                 toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex),
136331                 afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex],
136332             };
136333         }
136334         function doChange(oldFile, program, toMove, changes, host, preferences) {
136335             var checker = program.getTypeChecker();
136336             var usage = getUsageInfo(oldFile, toMove.all, checker);
136337             var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
136338             var extension = ts.extensionFromPath(oldFile.fileName);
136339             var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
136340             var newFileNameWithExtension = newModuleName + extension;
136341             // If previous file was global, this is easy.
136342             changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences));
136343             addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
136344         }
136345         // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file.
136346         function getStatementsToMove(context) {
136347             var rangeToMove = getRangeToMove(context);
136348             if (rangeToMove === undefined)
136349                 return undefined;
136350             var all = [];
136351             var ranges = [];
136352             var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast;
136353             ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) {
136354                 for (var i = start; i < afterEndIndex; i++)
136355                     all.push(toMove[i]);
136356                 ranges.push({ first: toMove[start], afterLast: afterLast });
136357             });
136358             return all.length === 0 ? undefined : { all: all, ranges: ranges };
136359         }
136360         function isPureImport(node) {
136361             switch (node.kind) {
136362                 case 254 /* ImportDeclaration */:
136363                     return true;
136364                 case 253 /* ImportEqualsDeclaration */:
136365                     return !ts.hasModifier(node, 1 /* Export */);
136366                 case 225 /* VariableStatement */:
136367                     return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
136368                 default:
136369                     return false;
136370             }
136371         }
136372         function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
136373             var cfg = program.getCompilerOptions().configFile;
136374             if (!cfg)
136375                 return;
136376             var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
136377             var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
136378             var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
136379             var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
136380                 return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
136381             });
136382             if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
136383                 changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
136384             }
136385         }
136386         function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) {
136387             var checker = program.getTypeChecker();
136388             if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
136389                 deleteMovedStatements(oldFile, toMove.ranges, changes);
136390                 return toMove.all;
136391             }
136392             var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
136393             var quotePreference = ts.getQuotePreference(oldFile, preferences);
136394             var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference);
136395             if (importsFromNewFile) {
136396                 ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true);
136397             }
136398             deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
136399             deleteMovedStatements(oldFile, toMove.ranges, changes);
136400             updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
136401             return __spreadArrays(getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference), addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
136402         }
136403         function deleteMovedStatements(sourceFile, moved, changes) {
136404             for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) {
136405                 var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast;
136406                 changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast);
136407             }
136408         }
136409         function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
136410             for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
136411                 var statement = _a[_i];
136412                 if (ts.contains(toMove, statement))
136413                     continue;
136414                 forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
136415             }
136416         }
136417         function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
136418             var checker = program.getTypeChecker();
136419             var _loop_17 = function (sourceFile) {
136420                 if (sourceFile === oldFile)
136421                     return "continue";
136422                 var _loop_18 = function (statement) {
136423                     forEachImportInStatement(statement, function (importNode) {
136424                         if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
136425                             return;
136426                         var shouldMove = function (name) {
136427                             var symbol = ts.isBindingElement(name.parent)
136428                                 ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
136429                                 : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217
136430                             return !!symbol && movedSymbols.has(symbol);
136431                         };
136432                         deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
136433                         var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
136434                         var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
136435                         if (newImportDeclaration)
136436                             changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
136437                         var ns = getNamespaceLikeImport(importNode);
136438                         if (ns)
136439                             updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode);
136440                     });
136441                 };
136442                 for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
136443                     var statement = _a[_i];
136444                     _loop_18(statement);
136445                 }
136446             };
136447             for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
136448                 var sourceFile = _a[_i];
136449                 _loop_17(sourceFile);
136450             }
136451         }
136452         function getNamespaceLikeImport(node) {
136453             switch (node.kind) {
136454                 case 254 /* ImportDeclaration */:
136455                     return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 256 /* NamespaceImport */ ?
136456                         node.importClause.namedBindings.name : undefined;
136457                 case 253 /* ImportEqualsDeclaration */:
136458                     return node.name;
136459                 case 242 /* VariableDeclaration */:
136460                     return ts.tryCast(node.name, ts.isIdentifier);
136461                 default:
136462                     return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind);
136463             }
136464         }
136465         function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
136466             var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 99 /* ESNext */);
136467             var needUniqueName = false;
136468             var toChange = [];
136469             ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
136470                 if (!ts.isPropertyAccessExpression(ref.parent))
136471                     return;
136472                 needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true);
136473                 if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) {
136474                     toChange.push(ref);
136475                 }
136476             });
136477             if (toChange.length) {
136478                 var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName;
136479                 for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) {
136480                     var ref = toChange_1[_i];
136481                     changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName));
136482                 }
136483                 changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier));
136484             }
136485         }
136486         function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) {
136487             var newNamespaceId = ts.createIdentifier(newNamespaceName);
136488             var newModuleString = ts.createLiteral(newModuleSpecifier);
136489             switch (node.kind) {
136490                 case 254 /* ImportDeclaration */:
136491                     return ts.createImportDeclaration(
136492                     /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString);
136493                 case 253 /* ImportEqualsDeclaration */:
136494                     return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString));
136495                 case 242 /* VariableDeclaration */:
136496                     return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString));
136497                 default:
136498                     return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind);
136499             }
136500         }
136501         function moduleSpecifierFromImport(i) {
136502             return (i.kind === 254 /* ImportDeclaration */ ? i.moduleSpecifier
136503                 : i.kind === 253 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
136504                     : i.initializer.arguments[0]);
136505         }
136506         function forEachImportInStatement(statement, cb) {
136507             if (ts.isImportDeclaration(statement)) {
136508                 if (ts.isStringLiteral(statement.moduleSpecifier))
136509                     cb(statement);
136510             }
136511             else if (ts.isImportEqualsDeclaration(statement)) {
136512                 if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
136513                     cb(statement);
136514                 }
136515             }
136516             else if (ts.isVariableStatement(statement)) {
136517                 for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
136518                     var decl = _a[_i];
136519                     if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
136520                         cb(decl);
136521                     }
136522                 }
136523             }
136524         }
136525         function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) {
136526             var defaultImport;
136527             var imports = [];
136528             newFileNeedExport.forEach(function (symbol) {
136529                 if (symbol.escapedName === "default" /* Default */) {
136530                     defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217
136531                 }
136532                 else {
136533                     imports.push(symbol.name);
136534                 }
136535             });
136536             return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference);
136537         }
136538         function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) {
136539             path = ts.ensurePathIsNonModuleName(path);
136540             if (useEs6Imports) {
136541                 var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
136542                 return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference);
136543             }
136544             else {
136545                 ts.Debug.assert(!defaultImport, "No default import should exist"); // If there's a default export, it should have been an es6 module.
136546                 var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
136547                 return bindingElements.length
136548                     ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
136549                     : undefined;
136550             }
136551         }
136552         function makeVariableStatement(name, type, initializer, flags) {
136553             if (flags === void 0) { flags = 2 /* Const */; }
136554             return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
136555         }
136556         function createRequireCall(moduleSpecifier) {
136557             return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
136558         }
136559         function addExports(sourceFile, toMove, needExport, useEs6Exports) {
136560             return ts.flatMap(toMove, function (statement) {
136561                 if (isTopLevelDeclarationStatement(statement) &&
136562                     !isExported(sourceFile, statement, useEs6Exports) &&
136563                     forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.checkDefined(d.symbol)); })) {
136564                     var exports = addExport(statement, useEs6Exports);
136565                     if (exports)
136566                         return exports;
136567                 }
136568                 return statement;
136569             });
136570         }
136571         function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
136572             switch (importDecl.kind) {
136573                 case 254 /* ImportDeclaration */:
136574                     deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
136575                     break;
136576                 case 253 /* ImportEqualsDeclaration */:
136577                     if (isUnused(importDecl.name)) {
136578                         changes.delete(sourceFile, importDecl);
136579                     }
136580                     break;
136581                 case 242 /* VariableDeclaration */:
136582                     deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
136583                     break;
136584                 default:
136585                     ts.Debug.assertNever(importDecl, "Unexpected import decl kind " + importDecl.kind);
136586             }
136587         }
136588         function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
136589             if (!importDecl.importClause)
136590                 return;
136591             var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
136592             var defaultUnused = !name || isUnused(name);
136593             var namedBindingsUnused = !namedBindings ||
136594                 (namedBindings.kind === 256 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); }));
136595             if (defaultUnused && namedBindingsUnused) {
136596                 changes.delete(sourceFile, importDecl);
136597             }
136598             else {
136599                 if (name && defaultUnused) {
136600                     changes.delete(sourceFile, name);
136601                 }
136602                 if (namedBindings) {
136603                     if (namedBindingsUnused) {
136604                         changes.replaceNode(sourceFile, importDecl.importClause, ts.updateImportClause(importDecl.importClause, name, /*namedBindings*/ undefined, importDecl.importClause.isTypeOnly));
136605                     }
136606                     else if (namedBindings.kind === 257 /* NamedImports */) {
136607                         for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
136608                             var element = _b[_i];
136609                             if (isUnused(element.name))
136610                                 changes.delete(sourceFile, element);
136611                         }
136612                     }
136613                 }
136614             }
136615         }
136616         function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
136617             var name = varDecl.name;
136618             switch (name.kind) {
136619                 case 75 /* Identifier */:
136620                     if (isUnused(name)) {
136621                         changes.delete(sourceFile, name);
136622                     }
136623                     break;
136624                 case 190 /* ArrayBindingPattern */:
136625                     break;
136626                 case 189 /* ObjectBindingPattern */:
136627                     if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) {
136628                         changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
136629                     }
136630                     else {
136631                         for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
136632                             var element = _a[_i];
136633                             if (ts.isIdentifier(element.name) && isUnused(element.name)) {
136634                                 changes.delete(sourceFile, element.name);
136635                             }
136636                         }
136637                     }
136638                     break;
136639             }
136640         }
136641         function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) {
136642             var copiedOldImports = [];
136643             for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
136644                 var oldStatement = _a[_i];
136645                 forEachImportInStatement(oldStatement, function (i) {
136646                     ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
136647                 });
136648             }
136649             // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
136650             var oldFileDefault;
136651             var oldFileNamedImports = [];
136652             var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
136653             newFileImportsFromOldFile.forEach(function (symbol) {
136654                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
136655                     var decl = _a[_i];
136656                     if (!isTopLevelDeclaration(decl))
136657                         continue;
136658                     var name = nameOfTopLevelDeclaration(decl);
136659                     if (!name)
136660                         continue;
136661                     var top = getTopLevelDeclarationStatement(decl);
136662                     if (markSeenTop(top)) {
136663                         addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
136664                     }
136665                     if (ts.hasModifier(decl, 512 /* Default */)) {
136666                         oldFileDefault = name;
136667                     }
136668                     else {
136669                         oldFileNamedImports.push(name.text);
136670                     }
136671                 }
136672             });
136673             ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference));
136674             return copiedOldImports;
136675         }
136676         function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
136677             var newModuleName = moduleName;
136678             for (var i = 1;; i++) {
136679                 var name = ts.combinePaths(inDirectory, newModuleName + extension);
136680                 if (!host.fileExists(name))
136681                     return newModuleName; // TODO: GH#18217
136682                 newModuleName = moduleName + "." + i;
136683             }
136684         }
136685         function getNewModuleName(movedSymbols) {
136686             return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
136687         }
136688         function getUsageInfo(oldFile, toMove, checker) {
136689             var movedSymbols = new SymbolSet();
136690             var oldImportsNeededByNewFile = new SymbolSet();
136691             var newFileImportsFromOldFile = new SymbolSet();
136692             var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); });
136693             var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
136694             if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
136695                 oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
136696             }
136697             for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
136698                 var statement = toMove_1[_i];
136699                 forEachTopLevelDeclaration(statement, function (decl) {
136700                     movedSymbols.add(ts.Debug.checkDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here"));
136701                 });
136702             }
136703             for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
136704                 var statement = toMove_2[_a];
136705                 forEachReference(statement, checker, function (symbol) {
136706                     if (!symbol.declarations)
136707                         return;
136708                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
136709                         var decl = _a[_i];
136710                         if (isInImport(decl)) {
136711                             oldImportsNeededByNewFile.add(symbol);
136712                         }
136713                         else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) {
136714                             newFileImportsFromOldFile.add(symbol);
136715                         }
136716                     }
136717                 });
136718             }
136719             var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
136720             var oldFileImportsFromNewFile = new SymbolSet();
136721             for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
136722                 var statement = _c[_b];
136723                 if (ts.contains(toMove, statement))
136724                     continue;
136725                 // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
136726                 if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
136727                     unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
136728                 }
136729                 forEachReference(statement, checker, function (symbol) {
136730                     if (movedSymbols.has(symbol))
136731                         oldFileImportsFromNewFile.add(symbol);
136732                     unusedImportsFromOldFile.delete(symbol);
136733                 });
136734             }
136735             return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
136736             function getJsxNamespaceSymbol(containsJsx) {
136737                 if (containsJsx === undefined) {
136738                     return undefined;
136739                 }
136740                 var jsxNamespace = checker.getJsxNamespace(containsJsx);
136741                 // Strictly speaking, this could resolve to a symbol other than the JSX namespace.
136742                 // This will produce erroneous output (probably, an incorrectly copied import) but
136743                 // is expected to be very rare and easily reversible.
136744                 var jsxNamespaceSymbol = checker.resolveName(jsxNamespace, containsJsx, 1920 /* Namespace */, /*excludeGlobals*/ true);
136745                 return !!jsxNamespaceSymbol && ts.some(jsxNamespaceSymbol.declarations, isInImport)
136746                     ? jsxNamespaceSymbol
136747                     : undefined;
136748             }
136749         }
136750         // Below should all be utilities
136751         function isInImport(decl) {
136752             switch (decl.kind) {
136753                 case 253 /* ImportEqualsDeclaration */:
136754                 case 258 /* ImportSpecifier */:
136755                 case 255 /* ImportClause */:
136756                 case 256 /* NamespaceImport */:
136757                     return true;
136758                 case 242 /* VariableDeclaration */:
136759                     return isVariableDeclarationInImport(decl);
136760                 case 191 /* BindingElement */:
136761                     return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
136762                 default:
136763                     return false;
136764             }
136765         }
136766         function isVariableDeclarationInImport(decl) {
136767             return ts.isSourceFile(decl.parent.parent.parent) &&
136768                 !!decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
136769         }
136770         function filterImport(i, moduleSpecifier, keep) {
136771             switch (i.kind) {
136772                 case 254 /* ImportDeclaration */: {
136773                     var clause = i.importClause;
136774                     if (!clause)
136775                         return undefined;
136776                     var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
136777                     var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
136778                     return defaultImport || namedBindings
136779                         ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
136780                         : undefined;
136781                 }
136782                 case 253 /* ImportEqualsDeclaration */:
136783                     return keep(i.name) ? i : undefined;
136784                 case 242 /* VariableDeclaration */: {
136785                     var name = filterBindingName(i.name, keep);
136786                     return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
136787                 }
136788                 default:
136789                     return ts.Debug.assertNever(i, "Unexpected import kind " + i.kind);
136790             }
136791         }
136792         function filterNamedBindings(namedBindings, keep) {
136793             if (namedBindings.kind === 256 /* NamespaceImport */) {
136794                 return keep(namedBindings.name) ? namedBindings : undefined;
136795             }
136796             else {
136797                 var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
136798                 return newElements.length ? ts.createNamedImports(newElements) : undefined;
136799             }
136800         }
136801         function filterBindingName(name, keep) {
136802             switch (name.kind) {
136803                 case 75 /* Identifier */:
136804                     return keep(name) ? name : undefined;
136805                 case 190 /* ArrayBindingPattern */:
136806                     return name;
136807                 case 189 /* ObjectBindingPattern */: {
136808                     // We can't handle nested destructurings or property names well here, so just copy them all.
136809                     var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); });
136810                     return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined;
136811                 }
136812             }
136813         }
136814         function forEachReference(node, checker, onReference) {
136815             node.forEachChild(function cb(node) {
136816                 if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
136817                     var sym = checker.getSymbolAtLocation(node);
136818                     if (sym)
136819                         onReference(sym);
136820                 }
136821                 else {
136822                     node.forEachChild(cb);
136823                 }
136824             });
136825         }
136826         var SymbolSet = /** @class */ (function () {
136827             function SymbolSet() {
136828                 this.map = ts.createMap();
136829             }
136830             SymbolSet.prototype.add = function (symbol) {
136831                 this.map.set(String(ts.getSymbolId(symbol)), symbol);
136832             };
136833             SymbolSet.prototype.has = function (symbol) {
136834                 return this.map.has(String(ts.getSymbolId(symbol)));
136835             };
136836             SymbolSet.prototype.delete = function (symbol) {
136837                 this.map.delete(String(ts.getSymbolId(symbol)));
136838             };
136839             SymbolSet.prototype.forEach = function (cb) {
136840                 this.map.forEach(cb);
136841             };
136842             SymbolSet.prototype.forEachEntry = function (cb) {
136843                 return ts.forEachEntry(this.map, cb);
136844             };
136845             SymbolSet.prototype.clone = function () {
136846                 var clone = new SymbolSet();
136847                 ts.copyEntries(this.map, clone.map);
136848                 return clone;
136849             };
136850             return SymbolSet;
136851         }());
136852         function isTopLevelDeclaration(node) {
136853             return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
136854         }
136855         function sourceFileOfTopLevelDeclaration(node) {
136856             return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent;
136857         }
136858         function isTopLevelDeclarationStatement(node) {
136859             ts.Debug.assert(ts.isSourceFile(node.parent), "Node parent should be a SourceFile");
136860             return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
136861         }
136862         function isNonVariableTopLevelDeclaration(node) {
136863             switch (node.kind) {
136864                 case 244 /* FunctionDeclaration */:
136865                 case 245 /* ClassDeclaration */:
136866                 case 249 /* ModuleDeclaration */:
136867                 case 248 /* EnumDeclaration */:
136868                 case 247 /* TypeAliasDeclaration */:
136869                 case 246 /* InterfaceDeclaration */:
136870                 case 253 /* ImportEqualsDeclaration */:
136871                     return true;
136872                 default:
136873                     return false;
136874             }
136875         }
136876         function forEachTopLevelDeclaration(statement, cb) {
136877             switch (statement.kind) {
136878                 case 244 /* FunctionDeclaration */:
136879                 case 245 /* ClassDeclaration */:
136880                 case 249 /* ModuleDeclaration */:
136881                 case 248 /* EnumDeclaration */:
136882                 case 247 /* TypeAliasDeclaration */:
136883                 case 246 /* InterfaceDeclaration */:
136884                 case 253 /* ImportEqualsDeclaration */:
136885                     return cb(statement);
136886                 case 225 /* VariableStatement */:
136887                     return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); });
136888                 case 226 /* ExpressionStatement */: {
136889                     var expression = statement.expression;
136890                     return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */
136891                         ? cb(statement)
136892                         : undefined;
136893                 }
136894             }
136895         }
136896         function forEachTopLevelDeclarationInBindingName(name, cb) {
136897             switch (name.kind) {
136898                 case 75 /* Identifier */:
136899                     return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); }));
136900                 case 190 /* ArrayBindingPattern */:
136901                 case 189 /* ObjectBindingPattern */:
136902                     return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); });
136903                 default:
136904                     return ts.Debug.assertNever(name, "Unexpected name kind " + name.kind);
136905             }
136906         }
136907         function nameOfTopLevelDeclaration(d) {
136908             return ts.isExpressionStatement(d) ? ts.tryCast(d.expression.left.name, ts.isIdentifier) : ts.tryCast(d.name, ts.isIdentifier);
136909         }
136910         function getTopLevelDeclarationStatement(d) {
136911             switch (d.kind) {
136912                 case 242 /* VariableDeclaration */:
136913                     return d.parent.parent;
136914                 case 191 /* BindingElement */:
136915                     return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); }));
136916                 default:
136917                     return d;
136918             }
136919         }
136920         function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
136921             if (isExported(sourceFile, decl, useEs6Exports))
136922                 return;
136923             if (useEs6Exports) {
136924                 if (!ts.isExpressionStatement(decl))
136925                     changes.insertExportModifier(sourceFile, decl);
136926             }
136927             else {
136928                 var names = getNamesToExportInCommonJS(decl);
136929                 if (names.length !== 0)
136930                     changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
136931             }
136932         }
136933         function isExported(sourceFile, decl, useEs6Exports) {
136934             if (useEs6Exports) {
136935                 return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
136936             }
136937             else {
136938                 return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
136939             }
136940         }
136941         function addExport(decl, useEs6Exports) {
136942             return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
136943         }
136944         function addEs6Export(d) {
136945             var modifiers = ts.concatenate([ts.createModifier(89 /* ExportKeyword */)], d.modifiers);
136946             switch (d.kind) {
136947                 case 244 /* FunctionDeclaration */:
136948                     return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
136949                 case 245 /* ClassDeclaration */:
136950                     return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
136951                 case 225 /* VariableStatement */:
136952                     return ts.updateVariableStatement(d, modifiers, d.declarationList);
136953                 case 249 /* ModuleDeclaration */:
136954                     return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
136955                 case 248 /* EnumDeclaration */:
136956                     return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
136957                 case 247 /* TypeAliasDeclaration */:
136958                     return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
136959                 case 246 /* InterfaceDeclaration */:
136960                     return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
136961                 case 253 /* ImportEqualsDeclaration */:
136962                     return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
136963                 case 226 /* ExpressionStatement */:
136964                     return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
136965                 default:
136966                     return ts.Debug.assertNever(d, "Unexpected declaration kind " + d.kind);
136967             }
136968         }
136969         function addCommonjsExport(decl) {
136970             return __spreadArrays([decl], getNamesToExportInCommonJS(decl).map(createExportAssignment));
136971         }
136972         function getNamesToExportInCommonJS(decl) {
136973             switch (decl.kind) {
136974                 case 244 /* FunctionDeclaration */:
136975                 case 245 /* ClassDeclaration */:
136976                     return [decl.name.text]; // TODO: GH#18217
136977                 case 225 /* VariableStatement */:
136978                     return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
136979                 case 249 /* ModuleDeclaration */:
136980                 case 248 /* EnumDeclaration */:
136981                 case 247 /* TypeAliasDeclaration */:
136982                 case 246 /* InterfaceDeclaration */:
136983                 case 253 /* ImportEqualsDeclaration */:
136984                     return ts.emptyArray;
136985                 case 226 /* ExpressionStatement */:
136986                     return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...`
136987                 default:
136988                     return ts.Debug.assertNever(decl, "Unexpected decl kind " + decl.kind);
136989             }
136990         }
136991         /** Creates `exports.x = x;` */
136992         function createExportAssignment(name) {
136993             return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 62 /* EqualsToken */, ts.createIdentifier(name)));
136994         }
136995     })(refactor = ts.refactor || (ts.refactor = {}));
136996 })(ts || (ts = {}));
136997 /* @internal */
136998 var ts;
136999 (function (ts) {
137000     var refactor;
137001     (function (refactor) {
137002         var addOrRemoveBracesToArrowFunction;
137003         (function (addOrRemoveBracesToArrowFunction) {
137004             var refactorName = "Add or remove braces in an arrow function";
137005             var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message;
137006             var addBracesActionName = "Add braces to arrow function";
137007             var removeBracesActionName = "Remove braces from arrow function";
137008             var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message;
137009             var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message;
137010             refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
137011             function getAvailableActions(context) {
137012                 var file = context.file, startPosition = context.startPosition;
137013                 var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
137014                 if (!info)
137015                     return ts.emptyArray;
137016                 return [{
137017                         name: refactorName,
137018                         description: refactorDescription,
137019                         actions: [
137020                             info.addBraces ?
137021                                 {
137022                                     name: addBracesActionName,
137023                                     description: addBracesActionDescription
137024                                 } : {
137025                                 name: removeBracesActionName,
137026                                 description: removeBracesActionDescription
137027                             }
137028                         ]
137029                     }];
137030             }
137031             function getEditsForAction(context, actionName) {
137032                 var file = context.file, startPosition = context.startPosition;
137033                 var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
137034                 if (!info)
137035                     return undefined;
137036                 var expression = info.expression, returnStatement = info.returnStatement, func = info.func;
137037                 var body;
137038                 if (actionName === addBracesActionName) {
137039                     var returnStatement_1 = ts.createReturn(expression);
137040                     body = ts.createBlock([returnStatement_1], /* multiLine */ true);
137041                     ts.suppressLeadingAndTrailingTrivia(body);
137042                     ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
137043                 }
137044                 else if (actionName === removeBracesActionName && returnStatement) {
137045                     var actualExpression = expression || ts.createVoidZero();
137046                     body = ts.needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
137047                     ts.suppressLeadingAndTrailingTrivia(body);
137048                     ts.copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137049                     ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137050                     ts.copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137051                 }
137052                 else {
137053                     ts.Debug.fail("invalid action");
137054                 }
137055                 var edits = ts.textChanges.ChangeTracker.with(context, function (t) {
137056                     t.replaceNode(file, func.body, body);
137057                 });
137058                 return { renameFilename: undefined, renameLocation: undefined, edits: edits };
137059             }
137060             function getConvertibleArrowFunctionAtPosition(file, startPosition) {
137061                 var node = ts.getTokenAtPosition(file, startPosition);
137062                 var func = ts.getContainingFunction(node);
137063                 if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node)))
137064                     return undefined;
137065                 if (ts.isExpression(func.body)) {
137066                     return {
137067                         func: func,
137068                         addBraces: true,
137069                         expression: func.body
137070                     };
137071                 }
137072                 else if (func.body.statements.length === 1) {
137073                     var firstStatement = ts.first(func.body.statements);
137074                     if (ts.isReturnStatement(firstStatement)) {
137075                         return {
137076                             func: func,
137077                             addBraces: false,
137078                             expression: firstStatement.expression,
137079                             returnStatement: firstStatement
137080                         };
137081                     }
137082                 }
137083                 return undefined;
137084             }
137085         })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
137086     })(refactor = ts.refactor || (ts.refactor = {}));
137087 })(ts || (ts = {}));
137088 /* @internal */
137089 var ts;
137090 (function (ts) {
137091     var refactor;
137092     (function (refactor) {
137093         var convertParamsToDestructuredObject;
137094         (function (convertParamsToDestructuredObject) {
137095             var refactorName = "Convert parameters to destructured object";
137096             var minimumParameterLength = 2;
137097             refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
137098             function getAvailableActions(context) {
137099                 var file = context.file, startPosition = context.startPosition;
137100                 var isJSFile = ts.isSourceFileJS(file);
137101                 if (isJSFile)
137102                     return ts.emptyArray; // TODO: GH#30113
137103                 var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
137104                 if (!functionDeclaration)
137105                     return ts.emptyArray;
137106                 var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
137107                 return [{
137108                         name: refactorName,
137109                         description: description,
137110                         actions: [{
137111                                 name: refactorName,
137112                                 description: description
137113                             }]
137114                     }];
137115             }
137116             function getEditsForAction(context, actionName) {
137117                 ts.Debug.assert(actionName === refactorName, "Unexpected action name");
137118                 var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
137119                 var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
137120                 if (!functionDeclaration || !cancellationToken)
137121                     return undefined;
137122                 var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
137123                 if (groupedReferences.valid) {
137124                     var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
137125                     return { renameFilename: undefined, renameLocation: undefined, edits: edits };
137126                 }
137127                 return { edits: [] }; // TODO: GH#30113
137128             }
137129             function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
137130                 var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
137131                 changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
137132                     // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
137133                     indentation: 0,
137134                     leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
137135                     trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
137136                 });
137137                 var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
137138                 for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
137139                     var call = functionCalls_1[_i];
137140                     if (call.arguments && call.arguments.length) {
137141                         var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
137142                         changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
137143                     }
137144                 }
137145             }
137146             function getGroupedReferences(functionDeclaration, program, cancellationToken) {
137147                 var functionNames = getFunctionNames(functionDeclaration);
137148                 var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
137149                 var names = ts.deduplicate(__spreadArrays(functionNames, classNames), ts.equateValues);
137150                 var checker = program.getTypeChecker();
137151                 var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
137152                 var groupedReferences = groupReferences(references);
137153                 if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) {
137154                     groupedReferences.valid = false;
137155                 }
137156                 return groupedReferences;
137157                 function groupReferences(referenceEntries) {
137158                     var classReferences = { accessExpressions: [], typeUsages: [] };
137159                     var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
137160                     var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation);
137161                     var classSymbols = ts.map(classNames, getSymbolTargetAtLocation);
137162                     var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
137163                     for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
137164                         var entry = referenceEntries_1[_i];
137165                         if (entry.kind !== 1 /* Node */) {
137166                             groupedReferences.valid = false;
137167                             continue;
137168                         }
137169                         /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
137170                         Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
137171                             class A { foo(a: number, b: number) { return a + b; } }
137172                             class B { foo(c: number, d: number) { return c + d; } }
137173                             declare const ab: A | B;
137174                             ab.foo(1, 2);
137175                         Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`.
137176                         When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol.
137177                         So we need to add a special case for this because when calling a constructor of a class through one of its subclasses,
137178                         the symbols are going to be different.
137179                         */
137180                         if (ts.contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || ts.isNewExpressionTarget(entry.node)) {
137181                             var importOrExportReference = entryToImportOrExport(entry);
137182                             if (importOrExportReference) {
137183                                 continue;
137184                             }
137185                             var decl = entryToDeclaration(entry);
137186                             if (decl) {
137187                                 groupedReferences.declarations.push(decl);
137188                                 continue;
137189                             }
137190                             var call = entryToFunctionCall(entry);
137191                             if (call) {
137192                                 groupedReferences.functionCalls.push(call);
137193                                 continue;
137194                             }
137195                         }
137196                         // if the refactored function is a constructor, we must also check if the references to its class are valid
137197                         if (isConstructor && ts.contains(classSymbols, getSymbolTargetAtLocation(entry.node))) {
137198                             var importOrExportReference = entryToImportOrExport(entry);
137199                             if (importOrExportReference) {
137200                                 continue;
137201                             }
137202                             var decl = entryToDeclaration(entry);
137203                             if (decl) {
137204                                 groupedReferences.declarations.push(decl);
137205                                 continue;
137206                             }
137207                             var accessExpression = entryToAccessExpression(entry);
137208                             if (accessExpression) {
137209                                 classReferences.accessExpressions.push(accessExpression);
137210                                 continue;
137211                             }
137212                             // Only class declarations are allowed to be used as a type (in a heritage clause),
137213                             // otherwise `findAllReferences` might not be able to track constructor calls.
137214                             if (ts.isClassDeclaration(functionDeclaration.parent)) {
137215                                 var type = entryToType(entry);
137216                                 if (type) {
137217                                     classReferences.typeUsages.push(type);
137218                                     continue;
137219                                 }
137220                             }
137221                         }
137222                         groupedReferences.valid = false;
137223                     }
137224                     return groupedReferences;
137225                 }
137226                 function getSymbolTargetAtLocation(node) {
137227                     var symbol = checker.getSymbolAtLocation(node);
137228                     return symbol && ts.getSymbolTarget(symbol, checker);
137229                 }
137230             }
137231             function entryToImportOrExport(entry) {
137232                 var node = entry.node;
137233                 if (ts.isImportSpecifier(node.parent)
137234                     || ts.isImportClause(node.parent)
137235                     || ts.isImportEqualsDeclaration(node.parent)
137236                     || ts.isNamespaceImport(node.parent)) {
137237                     return node;
137238                 }
137239                 if (ts.isExportSpecifier(node.parent) || ts.isExportAssignment(node.parent)) {
137240                     return node;
137241                 }
137242                 return undefined;
137243             }
137244             function entryToDeclaration(entry) {
137245                 if (ts.isDeclaration(entry.node.parent)) {
137246                     return entry.node;
137247                 }
137248                 return undefined;
137249             }
137250             function entryToFunctionCall(entry) {
137251                 if (entry.node.parent) {
137252                     var functionReference = entry.node;
137253                     var parent = functionReference.parent;
137254                     switch (parent.kind) {
137255                         // foo(...) or super(...) or new Foo(...)
137256                         case 196 /* CallExpression */:
137257                         case 197 /* NewExpression */:
137258                             var callOrNewExpression = ts.tryCast(parent, ts.isCallOrNewExpression);
137259                             if (callOrNewExpression && callOrNewExpression.expression === functionReference) {
137260                                 return callOrNewExpression;
137261                             }
137262                             break;
137263                         // x.foo(...)
137264                         case 194 /* PropertyAccessExpression */:
137265                             var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
137266                             if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
137267                                 var callOrNewExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallOrNewExpression);
137268                                 if (callOrNewExpression_1 && callOrNewExpression_1.expression === propertyAccessExpression) {
137269                                     return callOrNewExpression_1;
137270                                 }
137271                             }
137272                             break;
137273                         // x["foo"](...)
137274                         case 195 /* ElementAccessExpression */:
137275                             var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
137276                             if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
137277                                 var callOrNewExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallOrNewExpression);
137278                                 if (callOrNewExpression_2 && callOrNewExpression_2.expression === elementAccessExpression) {
137279                                     return callOrNewExpression_2;
137280                                 }
137281                             }
137282                             break;
137283                     }
137284                 }
137285                 return undefined;
137286             }
137287             function entryToAccessExpression(entry) {
137288                 if (entry.node.parent) {
137289                     var reference = entry.node;
137290                     var parent = reference.parent;
137291                     switch (parent.kind) {
137292                         // `C.foo`
137293                         case 194 /* PropertyAccessExpression */:
137294                             var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
137295                             if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
137296                                 return propertyAccessExpression;
137297                             }
137298                             break;
137299                         // `C["foo"]`
137300                         case 195 /* ElementAccessExpression */:
137301                             var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
137302                             if (elementAccessExpression && elementAccessExpression.expression === reference) {
137303                                 return elementAccessExpression;
137304                             }
137305                             break;
137306                     }
137307                 }
137308                 return undefined;
137309             }
137310             function entryToType(entry) {
137311                 var reference = entry.node;
137312                 if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
137313                     return reference;
137314                 }
137315                 return undefined;
137316             }
137317             function getFunctionDeclarationAtPosition(file, startPosition, checker) {
137318                 var node = ts.getTouchingToken(file, startPosition);
137319                 var functionDeclaration = ts.getContainingFunctionDeclaration(node);
137320                 // don't offer refactor on top-level JSDoc
137321                 if (isTopLevelJSDoc(node))
137322                     return undefined;
137323                 if (functionDeclaration
137324                     && isValidFunctionDeclaration(functionDeclaration, checker)
137325                     && ts.rangeContainsRange(functionDeclaration, node)
137326                     && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
137327                     return functionDeclaration;
137328                 return undefined;
137329             }
137330             function isTopLevelJSDoc(node) {
137331                 var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode);
137332                 if (containingJSDoc) {
137333                     var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); });
137334                     return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc);
137335                 }
137336                 return false;
137337             }
137338             function isValidFunctionDeclaration(functionDeclaration, checker) {
137339                 if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
137340                     return false;
137341                 switch (functionDeclaration.kind) {
137342                     case 244 /* FunctionDeclaration */:
137343                         return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker);
137344                     case 161 /* MethodDeclaration */:
137345                         return isSingleImplementation(functionDeclaration, checker);
137346                     case 162 /* Constructor */:
137347                         if (ts.isClassDeclaration(functionDeclaration.parent)) {
137348                             return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker);
137349                         }
137350                         else {
137351                             return isValidVariableDeclaration(functionDeclaration.parent.parent)
137352                                 && isSingleImplementation(functionDeclaration, checker);
137353                         }
137354                     case 201 /* FunctionExpression */:
137355                     case 202 /* ArrowFunction */:
137356                         return isValidVariableDeclaration(functionDeclaration.parent);
137357                 }
137358                 return false;
137359             }
137360             function isSingleImplementation(functionDeclaration, checker) {
137361                 return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
137362             }
137363             function hasNameOrDefault(functionOrClassDeclaration) {
137364                 if (!functionOrClassDeclaration.name) {
137365                     var defaultKeyword = ts.findModifier(functionOrClassDeclaration, 84 /* DefaultKeyword */);
137366                     return !!defaultKeyword;
137367                 }
137368                 return true;
137369             }
137370             function isValidParameterNodeArray(parameters, checker) {
137371                 return getRefactorableParametersLength(parameters) >= minimumParameterLength
137372                     && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); });
137373             }
137374             function isValidParameterDeclaration(parameterDeclaration, checker) {
137375                 if (ts.isRestParameter(parameterDeclaration)) {
137376                     var type = checker.getTypeAtLocation(parameterDeclaration);
137377                     if (!checker.isArrayType(type) && !checker.isTupleType(type))
137378                         return false;
137379                 }
137380                 return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name);
137381             }
137382             function isValidVariableDeclaration(node) {
137383                 return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
137384             }
137385             function hasThisParameter(parameters) {
137386                 return parameters.length > 0 && ts.isThis(parameters[0].name);
137387             }
137388             function getRefactorableParametersLength(parameters) {
137389                 if (hasThisParameter(parameters)) {
137390                     return parameters.length - 1;
137391                 }
137392                 return parameters.length;
137393             }
137394             function getRefactorableParameters(parameters) {
137395                 if (hasThisParameter(parameters)) {
137396                     parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
137397                 }
137398                 return parameters;
137399             }
137400             function createPropertyOrShorthandAssignment(name, initializer) {
137401                 if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) {
137402                     return ts.createShorthandPropertyAssignment(name);
137403                 }
137404                 return ts.createPropertyAssignment(name, initializer);
137405             }
137406             function createNewArgument(functionDeclaration, functionArguments) {
137407                 var parameters = getRefactorableParameters(functionDeclaration.parameters);
137408                 var hasRestParameter = ts.isRestParameter(ts.last(parameters));
137409                 var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
137410                 var properties = ts.map(nonRestArguments, function (arg, i) {
137411                     var parameterName = getParameterName(parameters[i]);
137412                     var property = createPropertyOrShorthandAssignment(parameterName, arg);
137413                     ts.suppressLeadingAndTrailingTrivia(property.name);
137414                     if (ts.isPropertyAssignment(property))
137415                         ts.suppressLeadingAndTrailingTrivia(property.initializer);
137416                     ts.copyComments(arg, property);
137417                     return property;
137418                 });
137419                 if (hasRestParameter && functionArguments.length >= parameters.length) {
137420                     var restArguments = functionArguments.slice(parameters.length - 1);
137421                     var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
137422                     properties.push(restProperty);
137423                 }
137424                 var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
137425                 return objectLiteral;
137426             }
137427             function createNewParameters(functionDeclaration, program, host) {
137428                 var checker = program.getTypeChecker();
137429                 var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
137430                 var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
137431                 var objectParameterName = ts.createObjectBindingPattern(bindingElements);
137432                 var objectParameterType = createParameterTypeNode(refactorableParameters);
137433                 var objectInitializer;
137434                 // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
137435                 if (ts.every(refactorableParameters, isOptionalParameter)) {
137436                     objectInitializer = ts.createObjectLiteral();
137437                 }
137438                 var objectParameter = ts.createParameter(
137439                 /*decorators*/ undefined, 
137440                 /*modifiers*/ undefined, 
137441                 /*dotDotDotToken*/ undefined, objectParameterName, 
137442                 /*questionToken*/ undefined, objectParameterType, objectInitializer);
137443                 if (hasThisParameter(functionDeclaration.parameters)) {
137444                     var thisParameter = functionDeclaration.parameters[0];
137445                     var newThisParameter = ts.createParameter(
137446                     /*decorators*/ undefined, 
137447                     /*modifiers*/ undefined, 
137448                     /*dotDotDotToken*/ undefined, thisParameter.name, 
137449                     /*questionToken*/ undefined, thisParameter.type);
137450                     ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
137451                     ts.copyComments(thisParameter.name, newThisParameter.name);
137452                     if (thisParameter.type) {
137453                         ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
137454                         ts.copyComments(thisParameter.type, newThisParameter.type);
137455                     }
137456                     return ts.createNodeArray([newThisParameter, objectParameter]);
137457                 }
137458                 return ts.createNodeArray([objectParameter]);
137459                 function createBindingElementFromParameterDeclaration(parameterDeclaration) {
137460                     var element = ts.createBindingElement(
137461                     /*dotDotDotToken*/ undefined, 
137462                     /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
137463                     ts.suppressLeadingAndTrailingTrivia(element);
137464                     if (parameterDeclaration.initializer && element.initializer) {
137465                         ts.copyComments(parameterDeclaration.initializer, element.initializer);
137466                     }
137467                     return element;
137468                 }
137469                 function createParameterTypeNode(parameters) {
137470                     var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
137471                     var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
137472                     return typeNode;
137473                 }
137474                 function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
137475                     var parameterType = parameterDeclaration.type;
137476                     if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
137477                         parameterType = getTypeNode(parameterDeclaration);
137478                     }
137479                     var propertySignature = ts.createPropertySignature(
137480                     /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(57 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, 
137481                     /*initializer*/ undefined);
137482                     ts.suppressLeadingAndTrailingTrivia(propertySignature);
137483                     ts.copyComments(parameterDeclaration.name, propertySignature.name);
137484                     if (parameterDeclaration.type && propertySignature.type) {
137485                         ts.copyComments(parameterDeclaration.type, propertySignature.type);
137486                     }
137487                     return propertySignature;
137488                 }
137489                 function getTypeNode(node) {
137490                     var type = checker.getTypeAtLocation(node);
137491                     return ts.getTypeNodeIfAccessible(type, node, program, host);
137492                 }
137493                 function isOptionalParameter(parameterDeclaration) {
137494                     if (ts.isRestParameter(parameterDeclaration)) {
137495                         var type = checker.getTypeAtLocation(parameterDeclaration);
137496                         return !checker.isTupleType(type);
137497                     }
137498                     return checker.isOptionalParameter(parameterDeclaration);
137499                 }
137500             }
137501             function getParameterName(paramDeclaration) {
137502                 return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
137503             }
137504             function getClassNames(constructorDeclaration) {
137505                 switch (constructorDeclaration.parent.kind) {
137506                     case 245 /* ClassDeclaration */:
137507                         var classDeclaration = constructorDeclaration.parent;
137508                         if (classDeclaration.name)
137509                             return [classDeclaration.name];
137510                         // If the class declaration doesn't have a name, it should have a default modifier.
137511                         // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
137512                         var defaultModifier = ts.Debug.checkDefined(ts.findModifier(classDeclaration, 84 /* DefaultKeyword */), "Nameless class declaration should be a default export");
137513                         return [defaultModifier];
137514                     case 214 /* ClassExpression */:
137515                         var classExpression = constructorDeclaration.parent;
137516                         var variableDeclaration = constructorDeclaration.parent.parent;
137517                         var className = classExpression.name;
137518                         if (className)
137519                             return [className, variableDeclaration.name];
137520                         return [variableDeclaration.name];
137521                 }
137522             }
137523             function getFunctionNames(functionDeclaration) {
137524                 switch (functionDeclaration.kind) {
137525                     case 244 /* FunctionDeclaration */:
137526                         if (functionDeclaration.name)
137527                             return [functionDeclaration.name];
137528                         // If the function declaration doesn't have a name, it should have a default modifier.
137529                         // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
137530                         var defaultModifier = ts.Debug.checkDefined(ts.findModifier(functionDeclaration, 84 /* DefaultKeyword */), "Nameless function declaration should be a default export");
137531                         return [defaultModifier];
137532                     case 161 /* MethodDeclaration */:
137533                         return [functionDeclaration.name];
137534                     case 162 /* Constructor */:
137535                         var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 129 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword");
137536                         if (functionDeclaration.parent.kind === 214 /* ClassExpression */) {
137537                             var variableDeclaration = functionDeclaration.parent.parent;
137538                             return [variableDeclaration.name, ctrKeyword];
137539                         }
137540                         return [ctrKeyword];
137541                     case 202 /* ArrowFunction */:
137542                         return [functionDeclaration.parent.name];
137543                     case 201 /* FunctionExpression */:
137544                         if (functionDeclaration.name)
137545                             return [functionDeclaration.name, functionDeclaration.parent.name];
137546                         return [functionDeclaration.parent.name];
137547                     default:
137548                         return ts.Debug.assertNever(functionDeclaration, "Unexpected function declaration kind " + functionDeclaration.kind);
137549                 }
137550             }
137551         })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {}));
137552     })(refactor = ts.refactor || (ts.refactor = {}));
137553 })(ts || (ts = {}));
137554 /* @internal */
137555 var ts;
137556 (function (ts) {
137557     var refactor;
137558     (function (refactor) {
137559         var convertStringOrTemplateLiteral;
137560         (function (convertStringOrTemplateLiteral) {
137561             var refactorName = "Convert to template string";
137562             var refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_template_string);
137563             refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
137564             function getAvailableActions(context) {
137565                 var file = context.file, startPosition = context.startPosition;
137566                 var node = getNodeOrParentOfParentheses(file, startPosition);
137567                 var maybeBinary = getParentBinaryExpression(node);
137568                 var refactorInfo = { name: refactorName, description: refactorDescription, actions: [] };
137569                 if (ts.isBinaryExpression(maybeBinary) && isStringConcatenationValid(maybeBinary)) {
137570                     refactorInfo.actions.push({ name: refactorName, description: refactorDescription });
137571                     return [refactorInfo];
137572                 }
137573                 return ts.emptyArray;
137574             }
137575             function getNodeOrParentOfParentheses(file, startPosition) {
137576                 var node = ts.getTokenAtPosition(file, startPosition);
137577                 var nestedBinary = getParentBinaryExpression(node);
137578                 var isNonStringBinary = !isStringConcatenationValid(nestedBinary);
137579                 if (isNonStringBinary &&
137580                     ts.isParenthesizedExpression(nestedBinary.parent) &&
137581                     ts.isBinaryExpression(nestedBinary.parent.parent)) {
137582                     return nestedBinary.parent.parent;
137583                 }
137584                 return node;
137585             }
137586             function getEditsForAction(context, actionName) {
137587                 var file = context.file, startPosition = context.startPosition;
137588                 var node = getNodeOrParentOfParentheses(file, startPosition);
137589                 switch (actionName) {
137590                     case refactorDescription:
137591                         return { edits: getEditsForToTemplateLiteral(context, node) };
137592                     default:
137593                         return ts.Debug.fail("invalid action");
137594                 }
137595             }
137596             function getEditsForToTemplateLiteral(context, node) {
137597                 var maybeBinary = getParentBinaryExpression(node);
137598                 var file = context.file;
137599                 var templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file);
137600                 var trailingCommentRanges = ts.getTrailingCommentRanges(file.text, maybeBinary.end);
137601                 if (trailingCommentRanges) {
137602                     var lastComment = trailingCommentRanges[trailingCommentRanges.length - 1];
137603                     var trailingRange_1 = { pos: trailingCommentRanges[0].pos, end: lastComment.end };
137604                     // since suppressTrailingTrivia(maybeBinary) does not work, the trailing comment is removed manually
137605                     // otherwise it would have the trailing comment twice
137606                     return ts.textChanges.ChangeTracker.with(context, function (t) {
137607                         t.deleteRange(file, trailingRange_1);
137608                         t.replaceNode(file, maybeBinary, templateLiteral);
137609                     });
137610                 }
137611                 else {
137612                     return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, maybeBinary, templateLiteral); });
137613                 }
137614             }
137615             function isNotEqualsOperator(node) {
137616                 return node.operatorToken.kind !== 62 /* EqualsToken */;
137617             }
137618             function getParentBinaryExpression(expr) {
137619                 while (ts.isBinaryExpression(expr.parent) && isNotEqualsOperator(expr.parent)) {
137620                     expr = expr.parent;
137621                 }
137622                 return expr;
137623             }
137624             function isStringConcatenationValid(node) {
137625                 var _a = treeToArray(node), containsString = _a.containsString, areOperatorsValid = _a.areOperatorsValid;
137626                 return containsString && areOperatorsValid;
137627             }
137628             function treeToArray(current) {
137629                 if (ts.isBinaryExpression(current)) {
137630                     var _a = treeToArray(current.left), nodes = _a.nodes, operators = _a.operators, leftHasString = _a.containsString, leftOperatorValid = _a.areOperatorsValid;
137631                     if (!leftHasString && !ts.isStringLiteral(current.right)) {
137632                         return { nodes: [current], operators: [], containsString: false, areOperatorsValid: true };
137633                     }
137634                     var currentOperatorValid = current.operatorToken.kind === 39 /* PlusToken */;
137635                     var areOperatorsValid = leftOperatorValid && currentOperatorValid;
137636                     nodes.push(current.right);
137637                     operators.push(current.operatorToken);
137638                     return { nodes: nodes, operators: operators, containsString: true, areOperatorsValid: areOperatorsValid };
137639                 }
137640                 return { nodes: [current], operators: [], containsString: ts.isStringLiteral(current), areOperatorsValid: true };
137641             }
137642             // to copy comments following the operator
137643             // "foo" + /* comment */ "bar"
137644             var copyTrailingOperatorComments = function (operators, file) { return function (index, targetNode) {
137645                 if (index < operators.length) {
137646                     ts.copyTrailingComments(operators[index], targetNode, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137647                 }
137648             }; };
137649             // to copy comments following the string
137650             // "foo" /* comment */ + "bar" /* comment */ + "bar2"
137651             var copyCommentFromMultiNode = function (nodes, file, copyOperatorComments) {
137652                 return function (indexes, targetNode) {
137653                     while (indexes.length > 0) {
137654                         var index = indexes.shift();
137655                         ts.copyTrailingComments(nodes[index], targetNode, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137656                         copyOperatorComments(index, targetNode);
137657                     }
137658                 };
137659             };
137660             function concatConsecutiveString(index, nodes) {
137661                 var text = "";
137662                 var indexes = [];
137663                 while (index < nodes.length && ts.isStringLiteral(nodes[index])) {
137664                     var stringNode = nodes[index];
137665                     text = text + stringNode.text;
137666                     indexes.push(index);
137667                     index++;
137668                 }
137669                 return [index, text, indexes];
137670             }
137671             function nodesToTemplate(_a, file) {
137672                 var nodes = _a.nodes, operators = _a.operators;
137673                 var copyOperatorComments = copyTrailingOperatorComments(operators, file);
137674                 var copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments);
137675                 var _b = concatConsecutiveString(0, nodes), begin = _b[0], headText = _b[1], headIndexes = _b[2];
137676                 if (begin === nodes.length) {
137677                     var noSubstitutionTemplateLiteral = ts.createNoSubstitutionTemplateLiteral(headText);
137678                     copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral);
137679                     return noSubstitutionTemplateLiteral;
137680                 }
137681                 var templateSpans = [];
137682                 var templateHead = ts.createTemplateHead(headText);
137683                 copyCommentFromStringLiterals(headIndexes, templateHead);
137684                 for (var i = begin; i < nodes.length; i++) {
137685                     var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]);
137686                     copyOperatorComments(i, currentNode);
137687                     var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], stringIndexes = _c[2];
137688                     i = newIndex - 1;
137689                     var templatePart = i === nodes.length - 1 ? ts.createTemplateTail(subsequentText) : ts.createTemplateMiddle(subsequentText);
137690                     copyCommentFromStringLiterals(stringIndexes, templatePart);
137691                     templateSpans.push(ts.createTemplateSpan(currentNode, templatePart));
137692                 }
137693                 return ts.createTemplateExpression(templateHead, templateSpans);
137694             }
137695             // to copy comments following the opening & closing parentheses
137696             // "foo" + ( /* comment */ 5 + 5 ) /* comment */ + "bar"
137697             function copyCommentsWhenParenthesized(node) {
137698                 var file = node.getSourceFile();
137699                 ts.copyTrailingComments(node, node.expression, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137700                 ts.copyTrailingAsLeadingComments(node.expression, node.expression, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137701             }
137702             function getExpressionFromParenthesesOrExpression(node) {
137703                 if (ts.isParenthesizedExpression(node)) {
137704                     copyCommentsWhenParenthesized(node);
137705                     node = node.expression;
137706                 }
137707                 return node;
137708             }
137709         })(convertStringOrTemplateLiteral = refactor.convertStringOrTemplateLiteral || (refactor.convertStringOrTemplateLiteral = {}));
137710     })(refactor = ts.refactor || (ts.refactor = {}));
137711 })(ts || (ts = {}));
137712 var ts;
137713 (function (ts) {
137714     /** The version of the language service API */
137715     ts.servicesVersion = "0.8";
137716     function createNode(kind, pos, end, parent) {
137717         var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) :
137718             kind === 75 /* Identifier */ ? new IdentifierObject(75 /* Identifier */, pos, end) :
137719                 kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierObject(76 /* PrivateIdentifier */, pos, end) :
137720                     new TokenObject(kind, pos, end);
137721         node.parent = parent;
137722         node.flags = parent.flags & 25358336 /* ContextFlags */;
137723         return node;
137724     }
137725     var NodeObject = /** @class */ (function () {
137726         function NodeObject(kind, pos, end) {
137727             this.pos = pos;
137728             this.end = end;
137729             this.flags = 0 /* None */;
137730             this.modifierFlagsCache = 0 /* None */;
137731             this.transformFlags = 0 /* None */;
137732             this.parent = undefined;
137733             this.kind = kind;
137734         }
137735         NodeObject.prototype.assertHasRealPosition = function (message) {
137736             // eslint-disable-next-line debug-assert
137737             ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation");
137738         };
137739         NodeObject.prototype.getSourceFile = function () {
137740             return ts.getSourceFileOfNode(this);
137741         };
137742         NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
137743             this.assertHasRealPosition();
137744             return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
137745         };
137746         NodeObject.prototype.getFullStart = function () {
137747             this.assertHasRealPosition();
137748             return this.pos;
137749         };
137750         NodeObject.prototype.getEnd = function () {
137751             this.assertHasRealPosition();
137752             return this.end;
137753         };
137754         NodeObject.prototype.getWidth = function (sourceFile) {
137755             this.assertHasRealPosition();
137756             return this.getEnd() - this.getStart(sourceFile);
137757         };
137758         NodeObject.prototype.getFullWidth = function () {
137759             this.assertHasRealPosition();
137760             return this.end - this.pos;
137761         };
137762         NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
137763             this.assertHasRealPosition();
137764             return this.getStart(sourceFile) - this.pos;
137765         };
137766         NodeObject.prototype.getFullText = function (sourceFile) {
137767             this.assertHasRealPosition();
137768             return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
137769         };
137770         NodeObject.prototype.getText = function (sourceFile) {
137771             this.assertHasRealPosition();
137772             if (!sourceFile) {
137773                 sourceFile = this.getSourceFile();
137774             }
137775             return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
137776         };
137777         NodeObject.prototype.getChildCount = function (sourceFile) {
137778             return this.getChildren(sourceFile).length;
137779         };
137780         NodeObject.prototype.getChildAt = function (index, sourceFile) {
137781             return this.getChildren(sourceFile)[index];
137782         };
137783         NodeObject.prototype.getChildren = function (sourceFile) {
137784             this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine");
137785             return this._children || (this._children = createChildren(this, sourceFile));
137786         };
137787         NodeObject.prototype.getFirstToken = function (sourceFile) {
137788             this.assertHasRealPosition();
137789             var children = this.getChildren(sourceFile);
137790             if (!children.length) {
137791                 return undefined;
137792             }
137793             var child = ts.find(children, function (kid) { return kid.kind < 294 /* FirstJSDocNode */ || kid.kind > 323 /* LastJSDocNode */; });
137794             return child.kind < 153 /* FirstNode */ ?
137795                 child :
137796                 child.getFirstToken(sourceFile);
137797         };
137798         NodeObject.prototype.getLastToken = function (sourceFile) {
137799             this.assertHasRealPosition();
137800             var children = this.getChildren(sourceFile);
137801             var child = ts.lastOrUndefined(children);
137802             if (!child) {
137803                 return undefined;
137804             }
137805             return child.kind < 153 /* FirstNode */ ? child : child.getLastToken(sourceFile);
137806         };
137807         NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) {
137808             return ts.forEachChild(this, cbNode, cbNodeArray);
137809         };
137810         return NodeObject;
137811     }());
137812     function createChildren(node, sourceFile) {
137813         if (!ts.isNodeKind(node.kind)) {
137814             return ts.emptyArray;
137815         }
137816         var children = [];
137817         if (ts.isJSDocCommentContainingNode(node)) {
137818             /** Don't add trivia for "tokens" since this is in a comment. */
137819             node.forEachChild(function (child) { children.push(child); });
137820             return children;
137821         }
137822         ts.scanner.setText((sourceFile || node.getSourceFile()).text);
137823         var pos = node.pos;
137824         var processNode = function (child) {
137825             addSyntheticNodes(children, pos, child.pos, node);
137826             children.push(child);
137827             pos = child.end;
137828         };
137829         var processNodes = function (nodes) {
137830             addSyntheticNodes(children, pos, nodes.pos, node);
137831             children.push(createSyntaxList(nodes, node));
137832             pos = nodes.end;
137833         };
137834         // jsDocComments need to be the first children
137835         ts.forEach(node.jsDoc, processNode);
137836         // For syntactic classifications, all trivia are classified together, including jsdoc comments.
137837         // For that to work, the jsdoc comments should still be the leading trivia of the first child.
137838         // Restoring the scanner position ensures that.
137839         pos = node.pos;
137840         node.forEachChild(processNode, processNodes);
137841         addSyntheticNodes(children, pos, node.end, node);
137842         ts.scanner.setText(undefined);
137843         return children;
137844     }
137845     function addSyntheticNodes(nodes, pos, end, parent) {
137846         ts.scanner.setTextPos(pos);
137847         while (pos < end) {
137848             var token = ts.scanner.scan();
137849             var textPos = ts.scanner.getTextPos();
137850             if (textPos <= end) {
137851                 if (token === 75 /* Identifier */) {
137852                     ts.Debug.fail("Did not expect " + ts.Debug.formatSyntaxKind(parent.kind) + " to have an Identifier in its trivia");
137853                 }
137854                 nodes.push(createNode(token, pos, textPos, parent));
137855             }
137856             pos = textPos;
137857             if (token === 1 /* EndOfFileToken */) {
137858                 break;
137859             }
137860         }
137861     }
137862     function createSyntaxList(nodes, parent) {
137863         var list = createNode(324 /* SyntaxList */, nodes.pos, nodes.end, parent);
137864         list._children = [];
137865         var pos = nodes.pos;
137866         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
137867             var node = nodes_1[_i];
137868             addSyntheticNodes(list._children, pos, node.pos, parent);
137869             list._children.push(node);
137870             pos = node.end;
137871         }
137872         addSyntheticNodes(list._children, pos, nodes.end, parent);
137873         return list;
137874     }
137875     var TokenOrIdentifierObject = /** @class */ (function () {
137876         function TokenOrIdentifierObject(pos, end) {
137877             // Set properties in same order as NodeObject
137878             this.pos = pos;
137879             this.end = end;
137880             this.flags = 0 /* None */;
137881             this.modifierFlagsCache = 0 /* None */;
137882             this.transformFlags = 0 /* None */;
137883             this.parent = undefined;
137884         }
137885         TokenOrIdentifierObject.prototype.getSourceFile = function () {
137886             return ts.getSourceFileOfNode(this);
137887         };
137888         TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
137889             return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
137890         };
137891         TokenOrIdentifierObject.prototype.getFullStart = function () {
137892             return this.pos;
137893         };
137894         TokenOrIdentifierObject.prototype.getEnd = function () {
137895             return this.end;
137896         };
137897         TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
137898             return this.getEnd() - this.getStart(sourceFile);
137899         };
137900         TokenOrIdentifierObject.prototype.getFullWidth = function () {
137901             return this.end - this.pos;
137902         };
137903         TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
137904             return this.getStart(sourceFile) - this.pos;
137905         };
137906         TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
137907             return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
137908         };
137909         TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
137910             if (!sourceFile) {
137911                 sourceFile = this.getSourceFile();
137912             }
137913             return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
137914         };
137915         TokenOrIdentifierObject.prototype.getChildCount = function () {
137916             return 0;
137917         };
137918         TokenOrIdentifierObject.prototype.getChildAt = function () {
137919             return undefined; // TODO: GH#18217
137920         };
137921         TokenOrIdentifierObject.prototype.getChildren = function () {
137922             return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray;
137923         };
137924         TokenOrIdentifierObject.prototype.getFirstToken = function () {
137925             return undefined;
137926         };
137927         TokenOrIdentifierObject.prototype.getLastToken = function () {
137928             return undefined;
137929         };
137930         TokenOrIdentifierObject.prototype.forEachChild = function () {
137931             return undefined;
137932         };
137933         return TokenOrIdentifierObject;
137934     }());
137935     var SymbolObject = /** @class */ (function () {
137936         function SymbolObject(flags, name) {
137937             this.flags = flags;
137938             this.escapedName = name;
137939         }
137940         SymbolObject.prototype.getFlags = function () {
137941             return this.flags;
137942         };
137943         Object.defineProperty(SymbolObject.prototype, "name", {
137944             get: function () {
137945                 return ts.symbolName(this);
137946             },
137947             enumerable: false,
137948             configurable: true
137949         });
137950         SymbolObject.prototype.getEscapedName = function () {
137951             return this.escapedName;
137952         };
137953         SymbolObject.prototype.getName = function () {
137954             return this.name;
137955         };
137956         SymbolObject.prototype.getDeclarations = function () {
137957             return this.declarations;
137958         };
137959         SymbolObject.prototype.getDocumentationComment = function (checker) {
137960             if (!this.documentationComment) {
137961                 this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs
137962                 this.documentationComment = getDocumentationComment(this.declarations, checker);
137963             }
137964             return this.documentationComment;
137965         };
137966         SymbolObject.prototype.getJsDocTags = function () {
137967             if (this.tags === undefined) {
137968                 this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations);
137969             }
137970             return this.tags;
137971         };
137972         return SymbolObject;
137973     }());
137974     var TokenObject = /** @class */ (function (_super) {
137975         __extends(TokenObject, _super);
137976         function TokenObject(kind, pos, end) {
137977             var _this = _super.call(this, pos, end) || this;
137978             _this.kind = kind;
137979             return _this;
137980         }
137981         return TokenObject;
137982     }(TokenOrIdentifierObject));
137983     var IdentifierObject = /** @class */ (function (_super) {
137984         __extends(IdentifierObject, _super);
137985         function IdentifierObject(_kind, pos, end) {
137986             var _this = _super.call(this, pos, end) || this;
137987             _this.kind = 75 /* Identifier */;
137988             return _this;
137989         }
137990         Object.defineProperty(IdentifierObject.prototype, "text", {
137991             get: function () {
137992                 return ts.idText(this);
137993             },
137994             enumerable: false,
137995             configurable: true
137996         });
137997         return IdentifierObject;
137998     }(TokenOrIdentifierObject));
137999     IdentifierObject.prototype.kind = 75 /* Identifier */;
138000     var PrivateIdentifierObject = /** @class */ (function (_super) {
138001         __extends(PrivateIdentifierObject, _super);
138002         function PrivateIdentifierObject(_kind, pos, end) {
138003             return _super.call(this, pos, end) || this;
138004         }
138005         Object.defineProperty(PrivateIdentifierObject.prototype, "text", {
138006             get: function () {
138007                 return ts.idText(this);
138008             },
138009             enumerable: false,
138010             configurable: true
138011         });
138012         return PrivateIdentifierObject;
138013     }(TokenOrIdentifierObject));
138014     PrivateIdentifierObject.prototype.kind = 76 /* PrivateIdentifier */;
138015     var TypeObject = /** @class */ (function () {
138016         function TypeObject(checker, flags) {
138017             this.checker = checker;
138018             this.flags = flags;
138019         }
138020         TypeObject.prototype.getFlags = function () {
138021             return this.flags;
138022         };
138023         TypeObject.prototype.getSymbol = function () {
138024             return this.symbol;
138025         };
138026         TypeObject.prototype.getProperties = function () {
138027             return this.checker.getPropertiesOfType(this);
138028         };
138029         TypeObject.prototype.getProperty = function (propertyName) {
138030             return this.checker.getPropertyOfType(this, propertyName);
138031         };
138032         TypeObject.prototype.getApparentProperties = function () {
138033             return this.checker.getAugmentedPropertiesOfType(this);
138034         };
138035         TypeObject.prototype.getCallSignatures = function () {
138036             return this.checker.getSignaturesOfType(this, 0 /* Call */);
138037         };
138038         TypeObject.prototype.getConstructSignatures = function () {
138039             return this.checker.getSignaturesOfType(this, 1 /* Construct */);
138040         };
138041         TypeObject.prototype.getStringIndexType = function () {
138042             return this.checker.getIndexTypeOfType(this, 0 /* String */);
138043         };
138044         TypeObject.prototype.getNumberIndexType = function () {
138045             return this.checker.getIndexTypeOfType(this, 1 /* Number */);
138046         };
138047         TypeObject.prototype.getBaseTypes = function () {
138048             return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined;
138049         };
138050         TypeObject.prototype.isNullableType = function () {
138051             return this.checker.isNullableType(this);
138052         };
138053         TypeObject.prototype.getNonNullableType = function () {
138054             return this.checker.getNonNullableType(this);
138055         };
138056         TypeObject.prototype.getNonOptionalType = function () {
138057             return this.checker.getNonOptionalType(this);
138058         };
138059         TypeObject.prototype.getConstraint = function () {
138060             return this.checker.getBaseConstraintOfType(this);
138061         };
138062         TypeObject.prototype.getDefault = function () {
138063             return this.checker.getDefaultFromTypeParameter(this);
138064         };
138065         TypeObject.prototype.isUnion = function () {
138066             return !!(this.flags & 1048576 /* Union */);
138067         };
138068         TypeObject.prototype.isIntersection = function () {
138069             return !!(this.flags & 2097152 /* Intersection */);
138070         };
138071         TypeObject.prototype.isUnionOrIntersection = function () {
138072             return !!(this.flags & 3145728 /* UnionOrIntersection */);
138073         };
138074         TypeObject.prototype.isLiteral = function () {
138075             return !!(this.flags & 384 /* StringOrNumberLiteral */);
138076         };
138077         TypeObject.prototype.isStringLiteral = function () {
138078             return !!(this.flags & 128 /* StringLiteral */);
138079         };
138080         TypeObject.prototype.isNumberLiteral = function () {
138081             return !!(this.flags & 256 /* NumberLiteral */);
138082         };
138083         TypeObject.prototype.isTypeParameter = function () {
138084             return !!(this.flags & 262144 /* TypeParameter */);
138085         };
138086         TypeObject.prototype.isClassOrInterface = function () {
138087             return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */);
138088         };
138089         TypeObject.prototype.isClass = function () {
138090             return !!(ts.getObjectFlags(this) & 1 /* Class */);
138091         };
138092         Object.defineProperty(TypeObject.prototype, "typeArguments", {
138093             /**
138094              * This polyfills `referenceType.typeArguments` for API consumers
138095              */
138096             get: function () {
138097                 if (ts.getObjectFlags(this) & 4 /* Reference */) {
138098                     return this.checker.getTypeArguments(this);
138099                 }
138100                 return undefined;
138101             },
138102             enumerable: false,
138103             configurable: true
138104         });
138105         return TypeObject;
138106     }());
138107     var SignatureObject = /** @class */ (function () {
138108         function SignatureObject(checker, flags) {
138109             this.checker = checker;
138110             this.flags = flags;
138111         }
138112         SignatureObject.prototype.getDeclaration = function () {
138113             return this.declaration;
138114         };
138115         SignatureObject.prototype.getTypeParameters = function () {
138116             return this.typeParameters;
138117         };
138118         SignatureObject.prototype.getParameters = function () {
138119             return this.parameters;
138120         };
138121         SignatureObject.prototype.getReturnType = function () {
138122             return this.checker.getReturnTypeOfSignature(this);
138123         };
138124         SignatureObject.prototype.getDocumentationComment = function () {
138125             return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker));
138126         };
138127         SignatureObject.prototype.getJsDocTags = function () {
138128             if (this.jsDocTags === undefined) {
138129                 this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : [];
138130             }
138131             return this.jsDocTags;
138132         };
138133         return SignatureObject;
138134     }());
138135     /**
138136      * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it.
138137      * @param node the Node in question.
138138      * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`.
138139      */
138140     function hasJSDocInheritDocTag(node) {
138141         return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; });
138142     }
138143     function getDocumentationComment(declarations, checker) {
138144         if (!declarations)
138145             return ts.emptyArray;
138146         var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
138147         if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
138148             ts.forEachUnique(declarations, function (declaration) {
138149                 var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
138150                 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
138151                 if (inheritedDocs)
138152                     doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc);
138153             });
138154         }
138155         return doc;
138156     }
138157     /**
138158      * Attempts to find JSDoc comments for possibly-inherited properties.  Checks superclasses then traverses
138159      * implemented interfaces until a symbol is found with the same name and with documentation.
138160      * @param declaration The possibly-inherited declaration to find comments for.
138161      * @param propertyName The name of the possibly-inherited property.
138162      * @param typeChecker A TypeChecker, used to find inherited properties.
138163      * @returns A filled array of documentation comments if any were found, otherwise an empty array.
138164      */
138165     function findInheritedJSDocComments(declaration, propertyName, typeChecker) {
138166         return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) {
138167             var superType = typeChecker.getTypeAtLocation(superTypeNode);
138168             var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName);
138169             var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker);
138170             return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined;
138171         });
138172     }
138173     var SourceFileObject = /** @class */ (function (_super) {
138174         __extends(SourceFileObject, _super);
138175         function SourceFileObject(kind, pos, end) {
138176             var _this = _super.call(this, kind, pos, end) || this;
138177             _this.kind = 290 /* SourceFile */;
138178             return _this;
138179         }
138180         SourceFileObject.prototype.update = function (newText, textChangeRange) {
138181             return ts.updateSourceFile(this, newText, textChangeRange);
138182         };
138183         SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) {
138184             return ts.getLineAndCharacterOfPosition(this, position);
138185         };
138186         SourceFileObject.prototype.getLineStarts = function () {
138187             return ts.getLineStarts(this);
138188         };
138189         SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character, allowEdits) {
138190             return ts.computePositionOfLineAndCharacter(ts.getLineStarts(this), line, character, this.text, allowEdits);
138191         };
138192         SourceFileObject.prototype.getLineEndOfPosition = function (pos) {
138193             var line = this.getLineAndCharacterOfPosition(pos).line;
138194             var lineStarts = this.getLineStarts();
138195             var lastCharPos;
138196             if (line + 1 >= lineStarts.length) {
138197                 lastCharPos = this.getEnd();
138198             }
138199             if (!lastCharPos) {
138200                 lastCharPos = lineStarts[line + 1] - 1;
138201             }
138202             var fullText = this.getFullText();
138203             // if the new line is "\r\n", we should return the last non-new-line-character position
138204             return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos;
138205         };
138206         SourceFileObject.prototype.getNamedDeclarations = function () {
138207             if (!this.namedDeclarations) {
138208                 this.namedDeclarations = this.computeNamedDeclarations();
138209             }
138210             return this.namedDeclarations;
138211         };
138212         SourceFileObject.prototype.computeNamedDeclarations = function () {
138213             var result = ts.createMultiMap();
138214             this.forEachChild(visit);
138215             return result;
138216             function addDeclaration(declaration) {
138217                 var name = getDeclarationName(declaration);
138218                 if (name) {
138219                     result.add(name, declaration);
138220                 }
138221             }
138222             function getDeclarations(name) {
138223                 var declarations = result.get(name);
138224                 if (!declarations) {
138225                     result.set(name, declarations = []);
138226                 }
138227                 return declarations;
138228             }
138229             function getDeclarationName(declaration) {
138230                 var name = ts.getNonAssignedNameOfDeclaration(declaration);
138231                 return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text
138232                     : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined);
138233             }
138234             function visit(node) {
138235                 switch (node.kind) {
138236                     case 244 /* FunctionDeclaration */:
138237                     case 201 /* FunctionExpression */:
138238                     case 161 /* MethodDeclaration */:
138239                     case 160 /* MethodSignature */:
138240                         var functionDeclaration = node;
138241                         var declarationName = getDeclarationName(functionDeclaration);
138242                         if (declarationName) {
138243                             var declarations = getDeclarations(declarationName);
138244                             var lastDeclaration = ts.lastOrUndefined(declarations);
138245                             // Check whether this declaration belongs to an "overload group".
138246                             if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) {
138247                                 // Overwrite the last declaration if it was an overload
138248                                 // and this one is an implementation.
138249                                 if (functionDeclaration.body && !lastDeclaration.body) {
138250                                     declarations[declarations.length - 1] = functionDeclaration;
138251                                 }
138252                             }
138253                             else {
138254                                 declarations.push(functionDeclaration);
138255                             }
138256                         }
138257                         ts.forEachChild(node, visit);
138258                         break;
138259                     case 245 /* ClassDeclaration */:
138260                     case 214 /* ClassExpression */:
138261                     case 246 /* InterfaceDeclaration */:
138262                     case 247 /* TypeAliasDeclaration */:
138263                     case 248 /* EnumDeclaration */:
138264                     case 249 /* ModuleDeclaration */:
138265                     case 253 /* ImportEqualsDeclaration */:
138266                     case 263 /* ExportSpecifier */:
138267                     case 258 /* ImportSpecifier */:
138268                     case 255 /* ImportClause */:
138269                     case 256 /* NamespaceImport */:
138270                     case 163 /* GetAccessor */:
138271                     case 164 /* SetAccessor */:
138272                     case 173 /* TypeLiteral */:
138273                         addDeclaration(node);
138274                         ts.forEachChild(node, visit);
138275                         break;
138276                     case 156 /* Parameter */:
138277                         // Only consider parameter properties
138278                         if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
138279                             break;
138280                         }
138281                     // falls through
138282                     case 242 /* VariableDeclaration */:
138283                     case 191 /* BindingElement */: {
138284                         var decl = node;
138285                         if (ts.isBindingPattern(decl.name)) {
138286                             ts.forEachChild(decl.name, visit);
138287                             break;
138288                         }
138289                         if (decl.initializer) {
138290                             visit(decl.initializer);
138291                         }
138292                     }
138293                     // falls through
138294                     case 284 /* EnumMember */:
138295                     case 159 /* PropertyDeclaration */:
138296                     case 158 /* PropertySignature */:
138297                         addDeclaration(node);
138298                         break;
138299                     case 260 /* ExportDeclaration */:
138300                         // Handle named exports case e.g.:
138301                         //    export {a, b as B} from "mod";
138302                         var exportDeclaration = node;
138303                         if (exportDeclaration.exportClause) {
138304                             if (ts.isNamedExports(exportDeclaration.exportClause)) {
138305                                 ts.forEach(exportDeclaration.exportClause.elements, visit);
138306                             }
138307                             else {
138308                                 visit(exportDeclaration.exportClause.name);
138309                             }
138310                         }
138311                         break;
138312                     case 254 /* ImportDeclaration */:
138313                         var importClause = node.importClause;
138314                         if (importClause) {
138315                             // Handle default import case e.g.:
138316                             //    import d from "mod";
138317                             if (importClause.name) {
138318                                 addDeclaration(importClause.name);
138319                             }
138320                             // Handle named bindings in imports e.g.:
138321                             //    import * as NS from "mod";
138322                             //    import {a, b as B} from "mod";
138323                             if (importClause.namedBindings) {
138324                                 if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
138325                                     addDeclaration(importClause.namedBindings);
138326                                 }
138327                                 else {
138328                                     ts.forEach(importClause.namedBindings.elements, visit);
138329                                 }
138330                             }
138331                         }
138332                         break;
138333                     case 209 /* BinaryExpression */:
138334                         if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) {
138335                             addDeclaration(node);
138336                         }
138337                     // falls through
138338                     default:
138339                         ts.forEachChild(node, visit);
138340                 }
138341             }
138342         };
138343         return SourceFileObject;
138344     }(NodeObject));
138345     var SourceMapSourceObject = /** @class */ (function () {
138346         function SourceMapSourceObject(fileName, text, skipTrivia) {
138347             this.fileName = fileName;
138348             this.text = text;
138349             this.skipTrivia = skipTrivia;
138350         }
138351         SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) {
138352             return ts.getLineAndCharacterOfPosition(this, pos);
138353         };
138354         return SourceMapSourceObject;
138355     }());
138356     function getServicesObjectAllocator() {
138357         return {
138358             getNodeConstructor: function () { return NodeObject; },
138359             getTokenConstructor: function () { return TokenObject; },
138360             getIdentifierConstructor: function () { return IdentifierObject; },
138361             getPrivateIdentifierConstructor: function () { return PrivateIdentifierObject; },
138362             getSourceFileConstructor: function () { return SourceFileObject; },
138363             getSymbolConstructor: function () { return SymbolObject; },
138364             getTypeConstructor: function () { return TypeObject; },
138365             getSignatureConstructor: function () { return SignatureObject; },
138366             getSourceMapSourceConstructor: function () { return SourceMapSourceObject; },
138367         };
138368     }
138369     function toEditorSettings(optionsAsMap) {
138370         var allPropertiesAreCamelCased = true;
138371         for (var key in optionsAsMap) {
138372             if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) {
138373                 allPropertiesAreCamelCased = false;
138374                 break;
138375             }
138376         }
138377         if (allPropertiesAreCamelCased) {
138378             return optionsAsMap;
138379         }
138380         var settings = {};
138381         for (var key in optionsAsMap) {
138382             if (ts.hasProperty(optionsAsMap, key)) {
138383                 var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1);
138384                 settings[newKey] = optionsAsMap[key];
138385             }
138386         }
138387         return settings;
138388     }
138389     ts.toEditorSettings = toEditorSettings;
138390     function isCamelCase(s) {
138391         return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
138392     }
138393     function displayPartsToString(displayParts) {
138394         if (displayParts) {
138395             return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
138396         }
138397         return "";
138398     }
138399     ts.displayPartsToString = displayPartsToString;
138400     function getDefaultCompilerOptions() {
138401         // Always default to "ScriptTarget.ES5" for the language service
138402         return {
138403             target: 1 /* ES5 */,
138404             jsx: 1 /* Preserve */
138405         };
138406     }
138407     ts.getDefaultCompilerOptions = getDefaultCompilerOptions;
138408     function getSupportedCodeFixes() {
138409         return ts.codefix.getSupportedErrorCodes();
138410     }
138411     ts.getSupportedCodeFixes = getSupportedCodeFixes;
138412     // Cache host information about script Should be refreshed
138413     // at each language service public entry point, since we don't know when
138414     // the set of scripts handled by the host changes.
138415     var HostCache = /** @class */ (function () {
138416         function HostCache(host, getCanonicalFileName) {
138417             this.host = host;
138418             // script id => script index
138419             this.currentDirectory = host.getCurrentDirectory();
138420             this.fileNameToEntry = ts.createMap();
138421             // Initialize the list with the root file names
138422             var rootFileNames = host.getScriptFileNames();
138423             for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) {
138424                 var fileName = rootFileNames_1[_i];
138425                 this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName));
138426             }
138427             // store the compilation settings
138428             this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions();
138429         }
138430         HostCache.prototype.compilationSettings = function () {
138431             return this._compilationSettings;
138432         };
138433         HostCache.prototype.getProjectReferences = function () {
138434             return this.host.getProjectReferences && this.host.getProjectReferences();
138435         };
138436         HostCache.prototype.createEntry = function (fileName, path) {
138437             var entry;
138438             var scriptSnapshot = this.host.getScriptSnapshot(fileName);
138439             if (scriptSnapshot) {
138440                 entry = {
138441                     hostFileName: fileName,
138442                     version: this.host.getScriptVersion(fileName),
138443                     scriptSnapshot: scriptSnapshot,
138444                     scriptKind: ts.getScriptKind(fileName, this.host)
138445                 };
138446             }
138447             else {
138448                 entry = fileName;
138449             }
138450             this.fileNameToEntry.set(path, entry);
138451             return entry;
138452         };
138453         HostCache.prototype.getEntryByPath = function (path) {
138454             return this.fileNameToEntry.get(path);
138455         };
138456         HostCache.prototype.getHostFileInformation = function (path) {
138457             var entry = this.fileNameToEntry.get(path);
138458             return !ts.isString(entry) ? entry : undefined;
138459         };
138460         HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) {
138461             var info = this.getEntryByPath(path) || this.createEntry(fileName, path);
138462             return ts.isString(info) ? undefined : info; // TODO: GH#18217
138463         };
138464         HostCache.prototype.getRootFileNames = function () {
138465             var names = [];
138466             this.fileNameToEntry.forEach(function (entry) {
138467                 if (ts.isString(entry)) {
138468                     names.push(entry);
138469                 }
138470                 else {
138471                     names.push(entry.hostFileName);
138472                 }
138473             });
138474             return names;
138475         };
138476         HostCache.prototype.getScriptSnapshot = function (path) {
138477             var file = this.getHostFileInformation(path);
138478             return (file && file.scriptSnapshot); // TODO: GH#18217
138479         };
138480         return HostCache;
138481     }());
138482     var SyntaxTreeCache = /** @class */ (function () {
138483         function SyntaxTreeCache(host) {
138484             this.host = host;
138485         }
138486         SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) {
138487             var scriptSnapshot = this.host.getScriptSnapshot(fileName);
138488             if (!scriptSnapshot) {
138489                 // The host does not know about this file.
138490                 throw new Error("Could not find file: '" + fileName + "'.");
138491             }
138492             var scriptKind = ts.getScriptKind(fileName, this.host);
138493             var version = this.host.getScriptVersion(fileName);
138494             var sourceFile;
138495             if (this.currentFileName !== fileName) {
138496                 // This is a new file, just parse it
138497                 sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 99 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
138498             }
138499             else if (this.currentFileVersion !== version) {
138500                 // This is the same file, just a newer version. Incrementally parse the file.
138501                 var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot);
138502                 sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange);
138503             }
138504             if (sourceFile) {
138505                 // All done, ensure state is up to date
138506                 this.currentFileVersion = version;
138507                 this.currentFileName = fileName;
138508                 this.currentFileScriptSnapshot = scriptSnapshot;
138509                 this.currentSourceFile = sourceFile;
138510             }
138511             return this.currentSourceFile;
138512         };
138513         return SyntaxTreeCache;
138514     }());
138515     function setSourceFileFields(sourceFile, scriptSnapshot, version) {
138516         sourceFile.version = version;
138517         sourceFile.scriptSnapshot = scriptSnapshot;
138518     }
138519     function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) {
138520         var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind);
138521         setSourceFileFields(sourceFile, scriptSnapshot, version);
138522         return sourceFile;
138523     }
138524     ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile;
138525     function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) {
138526         // If we were given a text change range, and our version or open-ness changed, then
138527         // incrementally parse this file.
138528         if (textChangeRange) {
138529             if (version !== sourceFile.version) {
138530                 var newText = void 0;
138531                 // grab the fragment from the beginning of the original text to the beginning of the span
138532                 var prefix = textChangeRange.span.start !== 0
138533                     ? sourceFile.text.substr(0, textChangeRange.span.start)
138534                     : "";
138535                 // grab the fragment from the end of the span till the end of the original text
138536                 var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length
138537                     ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span))
138538                     : "";
138539                 if (textChangeRange.newLength === 0) {
138540                     // edit was a deletion - just combine prefix and suffix
138541                     newText = prefix && suffix ? prefix + suffix : prefix || suffix;
138542                 }
138543                 else {
138544                     // it was actual edit, fetch the fragment of new text that correspond to new span
138545                     var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength);
138546                     // combine prefix, changed text and suffix
138547                     newText = prefix && suffix
138548                         ? prefix + changedText + suffix
138549                         : prefix
138550                             ? (prefix + changedText)
138551                             : (changedText + suffix);
138552                 }
138553                 var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
138554                 setSourceFileFields(newSourceFile, scriptSnapshot, version);
138555                 // after incremental parsing nameTable might not be up-to-date
138556                 // drop it so it can be lazily recreated later
138557                 newSourceFile.nameTable = undefined;
138558                 // dispose all resources held by old script snapshot
138559                 if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) {
138560                     if (sourceFile.scriptSnapshot.dispose) {
138561                         sourceFile.scriptSnapshot.dispose();
138562                     }
138563                     sourceFile.scriptSnapshot = undefined;
138564                 }
138565                 return newSourceFile;
138566             }
138567         }
138568         // Otherwise, just create a new source file.
138569         return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind);
138570     }
138571     ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile;
138572     var CancellationTokenObject = /** @class */ (function () {
138573         function CancellationTokenObject(cancellationToken) {
138574             this.cancellationToken = cancellationToken;
138575         }
138576         CancellationTokenObject.prototype.isCancellationRequested = function () {
138577             return !!this.cancellationToken && this.cancellationToken.isCancellationRequested();
138578         };
138579         CancellationTokenObject.prototype.throwIfCancellationRequested = function () {
138580             if (this.isCancellationRequested()) {
138581                 throw new ts.OperationCanceledException();
138582             }
138583         };
138584         return CancellationTokenObject;
138585     }());
138586     /* @internal */
138587     /** A cancellation that throttles calls to the host */
138588     var ThrottledCancellationToken = /** @class */ (function () {
138589         function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) {
138590             if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; }
138591             this.hostCancellationToken = hostCancellationToken;
138592             this.throttleWaitMilliseconds = throttleWaitMilliseconds;
138593             // Store when we last tried to cancel.  Checking cancellation can be expensive (as we have
138594             // to marshall over to the host layer).  So we only bother actually checking once enough
138595             // time has passed.
138596             this.lastCancellationCheckTime = 0;
138597         }
138598         ThrottledCancellationToken.prototype.isCancellationRequested = function () {
138599             var time = ts.timestamp();
138600             var duration = Math.abs(time - this.lastCancellationCheckTime);
138601             if (duration >= this.throttleWaitMilliseconds) {
138602                 // Check no more than once every throttle wait milliseconds
138603                 this.lastCancellationCheckTime = time;
138604                 return this.hostCancellationToken.isCancellationRequested();
138605             }
138606             return false;
138607         };
138608         ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () {
138609             if (this.isCancellationRequested()) {
138610                 throw new ts.OperationCanceledException();
138611             }
138612         };
138613         return ThrottledCancellationToken;
138614     }());
138615     ts.ThrottledCancellationToken = ThrottledCancellationToken;
138616     function createLanguageService(host, documentRegistry, syntaxOnly) {
138617         var _a;
138618         if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
138619         if (syntaxOnly === void 0) { syntaxOnly = false; }
138620         var syntaxTreeCache = new SyntaxTreeCache(host);
138621         var program;
138622         var lastProjectVersion;
138623         var lastTypesRootVersion = 0;
138624         var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken());
138625         var currentDirectory = host.getCurrentDirectory();
138626         // Check if the localized messages json is set, otherwise query the host for it
138627         if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) {
138628             ts.setLocalizedDiagnosticMessages(host.getLocalizedDiagnosticMessages());
138629         }
138630         function log(message) {
138631             if (host.log) {
138632                 host.log(message);
138633             }
138634         }
138635         var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
138636         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
138637         var sourceMapper = ts.getSourceMapper({
138638             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
138639             getCurrentDirectory: function () { return currentDirectory; },
138640             getProgram: getProgram,
138641             fileExists: ts.maybeBind(host, host.fileExists),
138642             readFile: ts.maybeBind(host, host.readFile),
138643             getDocumentPositionMapper: ts.maybeBind(host, host.getDocumentPositionMapper),
138644             getSourceFileLike: ts.maybeBind(host, host.getSourceFileLike),
138645             log: log
138646         });
138647         function getValidSourceFile(fileName) {
138648             var sourceFile = program.getSourceFile(fileName);
138649             if (!sourceFile) {
138650                 var error = new Error("Could not find source file: '" + fileName + "'.");
138651                 // We've been having trouble debugging this, so attach sidecar data for the tsserver log.
138652                 // See https://github.com/microsoft/TypeScript/issues/30180.
138653                 error.ProgramFiles = program.getSourceFiles().map(function (f) { return f.fileName; });
138654                 throw error;
138655             }
138656             return sourceFile;
138657         }
138658         function synchronizeHostData() {
138659             var _a;
138660             ts.Debug.assert(!syntaxOnly);
138661             // perform fast check if host supports it
138662             if (host.getProjectVersion) {
138663                 var hostProjectVersion = host.getProjectVersion();
138664                 if (hostProjectVersion) {
138665                     if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) {
138666                         return;
138667                     }
138668                     lastProjectVersion = hostProjectVersion;
138669                 }
138670             }
138671             var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0;
138672             if (lastTypesRootVersion !== typeRootsVersion) {
138673                 log("TypeRoots version has changed; provide new program");
138674                 program = undefined; // TODO: GH#18217
138675                 lastTypesRootVersion = typeRootsVersion;
138676             }
138677             // Get a fresh cache of the host information
138678             var hostCache = new HostCache(host, getCanonicalFileName);
138679             var rootFileNames = hostCache.getRootFileNames();
138680             var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
138681             var projectReferences = hostCache.getProjectReferences();
138682             // If the program is already up-to-date, we can reuse it
138683             if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
138684                 return;
138685             }
138686             // IMPORTANT - It is critical from this moment onward that we do not check
138687             // cancellation tokens.  We are about to mutate source files from a previous program
138688             // instance.  If we cancel midway through, we may end up in an inconsistent state where
138689             // the program points to old source files that have been invalidated because of
138690             // incremental parsing.
138691             var newSettings = hostCache.compilationSettings();
138692             // Now create a new compiler
138693             var compilerHost = {
138694                 getSourceFile: getOrCreateSourceFile,
138695                 getSourceFileByPath: getOrCreateSourceFileByPath,
138696                 getCancellationToken: function () { return cancellationToken; },
138697                 getCanonicalFileName: getCanonicalFileName,
138698                 useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
138699                 getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); },
138700                 getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
138701                 writeFile: ts.noop,
138702                 getCurrentDirectory: function () { return currentDirectory; },
138703                 fileExists: fileExists,
138704                 readFile: readFile,
138705                 realpath: host.realpath && (function (path) { return host.realpath(path); }),
138706                 directoryExists: function (directoryName) {
138707                     return ts.directoryProbablyExists(directoryName, host);
138708                 },
138709                 getDirectories: function (path) {
138710                     return host.getDirectories ? host.getDirectories(path) : [];
138711                 },
138712                 readDirectory: function (path, extensions, exclude, include, depth) {
138713                     ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'");
138714                     return host.readDirectory(path, extensions, exclude, include, depth);
138715                 },
138716                 onReleaseOldSourceFile: onReleaseOldSourceFile,
138717                 hasInvalidatedResolution: hasInvalidatedResolution,
138718                 hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames
138719             };
138720             if (host.trace) {
138721                 compilerHost.trace = function (message) { return host.trace(message); };
138722             }
138723             if (host.resolveModuleNames) {
138724                 compilerHost.resolveModuleNames = function () {
138725                     var args = [];
138726                     for (var _i = 0; _i < arguments.length; _i++) {
138727                         args[_i] = arguments[_i];
138728                     }
138729                     return host.resolveModuleNames.apply(host, args);
138730                 };
138731             }
138732             if (host.resolveTypeReferenceDirectives) {
138733                 compilerHost.resolveTypeReferenceDirectives = function () {
138734                     var args = [];
138735                     for (var _i = 0; _i < arguments.length; _i++) {
138736                         args[_i] = arguments[_i];
138737                     }
138738                     return host.resolveTypeReferenceDirectives.apply(host, args);
138739                 };
138740             }
138741             if (host.useSourceOfProjectReferenceRedirect) {
138742                 compilerHost.useSourceOfProjectReferenceRedirect = function () { return host.useSourceOfProjectReferenceRedirect(); };
138743             }
138744             (_a = host.setCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host, compilerHost);
138745             var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
138746             var options = {
138747                 rootNames: rootFileNames,
138748                 options: newSettings,
138749                 host: compilerHost,
138750                 oldProgram: program,
138751                 projectReferences: projectReferences
138752             };
138753             program = ts.createProgram(options);
138754             // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
138755             // It needs to be cleared to allow all collected snapshots to be released
138756             hostCache = undefined;
138757             // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above,
138758             // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during
138759             // the course of whatever called `synchronizeHostData`
138760             sourceMapper.clearCache();
138761             // Make sure all the nodes in the program are both bound, and have their parent
138762             // pointers set property.
138763             program.getTypeChecker();
138764             return;
138765             function fileExists(fileName) {
138766                 var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
138767                 var entry = hostCache && hostCache.getEntryByPath(path);
138768                 return entry ?
138769                     !ts.isString(entry) :
138770                     (!!host.fileExists && host.fileExists(fileName));
138771             }
138772             function readFile(fileName) {
138773                 // stub missing host functionality
138774                 var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
138775                 var entry = hostCache && hostCache.getEntryByPath(path);
138776                 if (entry) {
138777                     return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot);
138778                 }
138779                 return host.readFile && host.readFile(fileName);
138780             }
138781             // Release any files we have acquired in the old program but are
138782             // not part of the new program.
138783             function onReleaseOldSourceFile(oldSourceFile, oldOptions) {
138784                 var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions);
138785                 documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey);
138786             }
138787             function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
138788                 return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile);
138789             }
138790             function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) {
138791                 ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host.");
138792                 // The program is asking for this file, check first if the host can locate it.
138793                 // If the host can not locate the file, then it does not exist. return undefined
138794                 // to the program to allow reporting of errors for missing files.
138795                 var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path);
138796                 if (!hostFileInformation) {
138797                     return undefined;
138798                 }
138799                 // Check if the language version has changed since we last created a program; if they are the same,
138800                 // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile
138801                 // can not be reused. we have to dump all syntax trees and create new ones.
138802                 if (!shouldCreateNewSourceFile) {
138803                     // Check if the old program had this file already
138804                     var oldSourceFile = program && program.getSourceFileByPath(path);
138805                     if (oldSourceFile) {
138806                         // We already had a source file for this file name.  Go to the registry to
138807                         // ensure that we get the right up to date version of it.  We need this to
138808                         // address the following race-condition.  Specifically, say we have the following:
138809                         //
138810                         //      LS1
138811                         //          \
138812                         //           DocumentRegistry
138813                         //          /
138814                         //      LS2
138815                         //
138816                         // Each LS has a reference to file 'foo.ts' at version 1.  LS2 then updates
138817                         // it's version of 'foo.ts' to version 2.  This will cause LS2 and the
138818                         // DocumentRegistry to have version 2 of the document.  HOwever, LS1 will
138819                         // have version 1.  And *importantly* this source file will be *corrupt*.
138820                         // The act of creating version 2 of the file irrevocably damages the version
138821                         // 1 file.
138822                         //
138823                         // So, later when we call into LS1, we need to make sure that it doesn't use
138824                         // it's source file any more, and instead defers to DocumentRegistry to get
138825                         // either version 1, version 2 (or some other version) depending on what the
138826                         // host says should be used.
138827                         // We do not support the scenario where a host can modify a registered
138828                         // file's script kind, i.e. in one project some file is treated as ".ts"
138829                         // and in another as ".js"
138830                         ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.");
138831                         return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
138832                     }
138833                     // We didn't already have the file.  Fall through and acquire it from the registry.
138834                 }
138835                 // Could not find this file in the old program, create a new SourceFile for it.
138836                 return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
138837             }
138838         }
138839         // TODO: GH#18217 frequently asserted as defined
138840         function getProgram() {
138841             if (syntaxOnly) {
138842                 ts.Debug.assert(program === undefined);
138843                 return undefined;
138844             }
138845             synchronizeHostData();
138846             return program;
138847         }
138848         function cleanupSemanticCache() {
138849             program = undefined; // TODO: GH#18217
138850         }
138851         function dispose() {
138852             if (program) {
138853                 // Use paths to ensure we are using correct key and paths as document registry could bre created with different current directory than host
138854                 var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions());
138855                 ts.forEach(program.getSourceFiles(), function (f) {
138856                     return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1);
138857                 });
138858                 program = undefined; // TODO: GH#18217
138859             }
138860             host = undefined;
138861         }
138862         /// Diagnostics
138863         function getSyntacticDiagnostics(fileName) {
138864             synchronizeHostData();
138865             return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice();
138866         }
138867         /**
138868          * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors
138869          * If '-d' enabled, report both semantic and emitter errors
138870          */
138871         function getSemanticDiagnostics(fileName) {
138872             synchronizeHostData();
138873             var targetSourceFile = getValidSourceFile(fileName);
138874             // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.
138875             // Therefore only get diagnostics for given file.
138876             var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);
138877             if (!ts.getEmitDeclarations(program.getCompilerOptions())) {
138878                 return semanticDiagnostics.slice();
138879             }
138880             // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface
138881             var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
138882             return __spreadArrays(semanticDiagnostics, declarationDiagnostics);
138883         }
138884         function getSuggestionDiagnostics(fileName) {
138885             synchronizeHostData();
138886             return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken);
138887         }
138888         function getCompilerOptionsDiagnostics() {
138889             synchronizeHostData();
138890             return __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken));
138891         }
138892         function getCompletionsAtPosition(fileName, position, options) {
138893             if (options === void 0) { options = ts.emptyOptions; }
138894             // Convert from deprecated options names to new names
138895             var fullPreferences = __assign(__assign({}, ts.identity(options)), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions });
138896             synchronizeHostData();
138897             return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter);
138898         }
138899         function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) {
138900             if (preferences === void 0) { preferences = ts.emptyOptions; }
138901             synchronizeHostData();
138902             return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217
138903             preferences, cancellationToken);
138904         }
138905         function getCompletionEntrySymbol(fileName, position, name, source, preferences) {
138906             if (preferences === void 0) { preferences = ts.emptyOptions; }
138907             synchronizeHostData();
138908             return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, preferences);
138909         }
138910         function getQuickInfoAtPosition(fileName, position) {
138911             synchronizeHostData();
138912             var sourceFile = getValidSourceFile(fileName);
138913             var node = ts.getTouchingPropertyName(sourceFile, position);
138914             if (node === sourceFile) {
138915                 // Avoid giving quickInfo for the sourceFile as a whole.
138916                 return undefined;
138917             }
138918             var typeChecker = program.getTypeChecker();
138919             var nodeForQuickInfo = getNodeForQuickInfo(node);
138920             var symbol = getSymbolAtLocationForQuickInfo(nodeForQuickInfo, typeChecker);
138921             if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
138922                 var type_2 = shouldGetType(sourceFile, nodeForQuickInfo, position) ? typeChecker.getTypeAtLocation(nodeForQuickInfo) : undefined;
138923                 return type_2 && {
138924                     kind: "" /* unknown */,
138925                     kindModifiers: "" /* none */,
138926                     textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile),
138927                     displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(nodeForQuickInfo)); }),
138928                     documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined,
138929                     tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined
138930                 };
138931             }
138932             var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
138933                 return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(nodeForQuickInfo), nodeForQuickInfo);
138934             }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
138935             return {
138936                 kind: symbolKind,
138937                 kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
138938                 textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile),
138939                 displayParts: displayParts,
138940                 documentation: documentation,
138941                 tags: tags,
138942             };
138943         }
138944         function getNodeForQuickInfo(node) {
138945             if (ts.isNewExpression(node.parent) && node.pos === node.parent.pos) {
138946                 return node.parent.expression;
138947             }
138948             return node;
138949         }
138950         function shouldGetType(sourceFile, node, position) {
138951             switch (node.kind) {
138952                 case 75 /* Identifier */:
138953                     return !ts.isLabelName(node) && !ts.isTagName(node);
138954                 case 194 /* PropertyAccessExpression */:
138955                 case 153 /* QualifiedName */:
138956                     // Don't return quickInfo if inside the comment in `a/**/.b`
138957                     return !ts.isInComment(sourceFile, position);
138958                 case 104 /* ThisKeyword */:
138959                 case 183 /* ThisType */:
138960                 case 102 /* SuperKeyword */:
138961                     return true;
138962                 default:
138963                     return false;
138964             }
138965         }
138966         /// Goto definition
138967         function getDefinitionAtPosition(fileName, position) {
138968             synchronizeHostData();
138969             return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position);
138970         }
138971         function getDefinitionAndBoundSpan(fileName, position) {
138972             synchronizeHostData();
138973             return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position);
138974         }
138975         function getTypeDefinitionAtPosition(fileName, position) {
138976             synchronizeHostData();
138977             return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position);
138978         }
138979         /// Goto implementation
138980         function getImplementationAtPosition(fileName, position) {
138981             synchronizeHostData();
138982             return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
138983         }
138984         /// References and Occurrences
138985         function getOccurrencesAtPosition(fileName, position) {
138986             return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { return (__assign(__assign({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, isDefinition: false }, highlightSpan.isInString && { isInString: true }), highlightSpan.contextSpan && { contextSpan: highlightSpan.contextSpan })); }); });
138987         }
138988         function getDocumentHighlights(fileName, position, filesToSearch) {
138989             var normalizedFileName = ts.normalizePath(fileName);
138990             ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; }));
138991             synchronizeHostData();
138992             var sourceFilesToSearch = ts.mapDefined(filesToSearch, function (fileName) { return program.getSourceFile(fileName); });
138993             var sourceFile = getValidSourceFile(fileName);
138994             return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
138995         }
138996         function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) {
138997             synchronizeHostData();
138998             var sourceFile = getValidSourceFile(fileName);
138999             var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position));
139000             if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) {
139001                 var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
139002                 return [openingElement, closingElement].map(function (node) {
139003                     var textSpan = ts.createTextSpanFromNode(node.tagName, sourceFile);
139004                     return __assign({ fileName: sourceFile.fileName, textSpan: textSpan }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, node.parent));
139005                 });
139006             }
139007             else {
139008                 return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, providePrefixAndSuffixTextForRename: providePrefixAndSuffixTextForRename, use: 2 /* Rename */ }, function (entry, originalNode, checker) { return ts.FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false); });
139009             }
139010         }
139011         function getReferencesAtPosition(fileName, position) {
139012             synchronizeHostData();
139013             return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: 1 /* References */ }, ts.FindAllReferences.toReferenceEntry);
139014         }
139015         function getReferencesWorker(node, position, options, cb) {
139016             synchronizeHostData();
139017             // Exclude default library when renaming as commonly user don't want to change that file.
139018             var sourceFiles = options && options.use === 2 /* Rename */
139019                 ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); })
139020                 : program.getSourceFiles();
139021             return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb);
139022         }
139023         function findReferences(fileName, position) {
139024             synchronizeHostData();
139025             return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
139026         }
139027         function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
139028             if (excludeDtsFiles === void 0) { excludeDtsFiles = false; }
139029             synchronizeHostData();
139030             var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
139031             return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
139032         }
139033         function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) {
139034             synchronizeHostData();
139035             var sourceFile = getValidSourceFile(fileName);
139036             var customTransformers = host.getCustomTransformers && host.getCustomTransformers();
139037             return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit);
139038         }
139039         // Signature help
139040         /**
139041          * This is a semantic operation.
139042          */
139043         function getSignatureHelpItems(fileName, position, _a) {
139044             var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason;
139045             synchronizeHostData();
139046             var sourceFile = getValidSourceFile(fileName);
139047             return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken);
139048         }
139049         /// Syntactic features
139050         function getNonBoundSourceFile(fileName) {
139051             return syntaxTreeCache.getCurrentSourceFile(fileName);
139052         }
139053         function getNameOrDottedNameSpan(fileName, startPos, _endPos) {
139054             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139055             // Get node at the location
139056             var node = ts.getTouchingPropertyName(sourceFile, startPos);
139057             if (node === sourceFile) {
139058                 return undefined;
139059             }
139060             switch (node.kind) {
139061                 case 194 /* PropertyAccessExpression */:
139062                 case 153 /* QualifiedName */:
139063                 case 10 /* StringLiteral */:
139064                 case 91 /* FalseKeyword */:
139065                 case 106 /* TrueKeyword */:
139066                 case 100 /* NullKeyword */:
139067                 case 102 /* SuperKeyword */:
139068                 case 104 /* ThisKeyword */:
139069                 case 183 /* ThisType */:
139070                 case 75 /* Identifier */:
139071                     break;
139072                 // Cant create the text span
139073                 default:
139074                     return undefined;
139075             }
139076             var nodeForStartPos = node;
139077             while (true) {
139078                 if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) {
139079                     // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node
139080                     nodeForStartPos = nodeForStartPos.parent;
139081                 }
139082                 else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) {
139083                     // If this is name of a module declarations, check if this is right side of dotted module name
139084                     // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of
139085                     // Then this name is name from dotted module
139086                     if (nodeForStartPos.parent.parent.kind === 249 /* ModuleDeclaration */ &&
139087                         nodeForStartPos.parent.parent.body === nodeForStartPos.parent) {
139088                         // Use parent module declarations name for start pos
139089                         nodeForStartPos = nodeForStartPos.parent.parent.name;
139090                     }
139091                     else {
139092                         // We have to use this name for start pos
139093                         break;
139094                     }
139095                 }
139096                 else {
139097                     // Is not a member expression so we have found the node for start pos
139098                     break;
139099                 }
139100             }
139101             return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd());
139102         }
139103         function getBreakpointStatementAtPosition(fileName, position) {
139104             // doesn't use compiler - no need to synchronize with host
139105             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139106             return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position);
139107         }
139108         function getNavigationBarItems(fileName) {
139109             return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
139110         }
139111         function getNavigationTree(fileName) {
139112             return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
139113         }
139114         function isTsOrTsxFile(fileName) {
139115             var kind = ts.getScriptKind(fileName, host);
139116             return kind === 3 /* TS */ || kind === 4 /* TSX */;
139117         }
139118         function getSemanticClassifications(fileName, span) {
139119             if (!isTsOrTsxFile(fileName)) {
139120                 // do not run semantic classification on non-ts-or-tsx files
139121                 return [];
139122             }
139123             synchronizeHostData();
139124             return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
139125         }
139126         function getEncodedSemanticClassifications(fileName, span) {
139127             if (!isTsOrTsxFile(fileName)) {
139128                 // do not run semantic classification on non-ts-or-tsx files
139129                 return { spans: [], endOfLineState: 0 /* None */ };
139130             }
139131             synchronizeHostData();
139132             return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
139133         }
139134         function getSyntacticClassifications(fileName, span) {
139135             // doesn't use compiler - no need to synchronize with host
139136             return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
139137         }
139138         function getEncodedSyntacticClassifications(fileName, span) {
139139             // doesn't use compiler - no need to synchronize with host
139140             return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
139141         }
139142         function getOutliningSpans(fileName) {
139143             // doesn't use compiler - no need to synchronize with host
139144             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139145             return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken);
139146         }
139147         var braceMatching = ts.createMapFromTemplate((_a = {},
139148             _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */,
139149             _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */,
139150             _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */,
139151             _a[31 /* GreaterThanToken */] = 29 /* LessThanToken */,
139152             _a));
139153         braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); });
139154         function getBraceMatchingAtPosition(fileName, position) {
139155             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139156             var token = ts.getTouchingToken(sourceFile, position);
139157             var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined;
139158             var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile);
139159             // We want to order the braces when we return the result.
139160             return match ? [ts.createTextSpanFromNode(token, sourceFile), ts.createTextSpanFromNode(match, sourceFile)].sort(function (a, b) { return a.start - b.start; }) : ts.emptyArray;
139161         }
139162         function getIndentationAtPosition(fileName, position, editorOptions) {
139163             var start = ts.timestamp();
139164             var settings = toEditorSettings(editorOptions);
139165             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139166             log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start));
139167             start = ts.timestamp();
139168             var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings);
139169             log("getIndentationAtPosition: computeIndentation  : " + (ts.timestamp() - start));
139170             return result;
139171         }
139172         function getFormattingEditsForRange(fileName, start, end, options) {
139173             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139174             return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options), host));
139175         }
139176         function getFormattingEditsForDocument(fileName, options) {
139177             return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options), host));
139178         }
139179         function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
139180             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139181             var formatContext = ts.formatting.getFormatContext(toEditorSettings(options), host);
139182             if (!ts.isInComment(sourceFile, position)) {
139183                 switch (key) {
139184                     case "{":
139185                         return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext);
139186                     case "}":
139187                         return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext);
139188                     case ";":
139189                         return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext);
139190                     case "\n":
139191                         return ts.formatting.formatOnEnter(position, sourceFile, formatContext);
139192                 }
139193             }
139194             return [];
139195         }
139196         function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) {
139197             if (preferences === void 0) { preferences = ts.emptyOptions; }
139198             synchronizeHostData();
139199             var sourceFile = getValidSourceFile(fileName);
139200             var span = ts.createTextSpanFromBounds(start, end);
139201             var formatContext = ts.formatting.getFormatContext(formatOptions, host);
139202             return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) {
139203                 cancellationToken.throwIfCancellationRequested();
139204                 return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
139205             });
139206         }
139207         function getCombinedCodeFix(scope, fixId, formatOptions, preferences) {
139208             if (preferences === void 0) { preferences = ts.emptyOptions; }
139209             synchronizeHostData();
139210             ts.Debug.assert(scope.type === "file");
139211             var sourceFile = getValidSourceFile(scope.fileName);
139212             var formatContext = ts.formatting.getFormatContext(formatOptions, host);
139213             return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
139214         }
139215         function organizeImports(scope, formatOptions, preferences) {
139216             if (preferences === void 0) { preferences = ts.emptyOptions; }
139217             synchronizeHostData();
139218             ts.Debug.assert(scope.type === "file");
139219             var sourceFile = getValidSourceFile(scope.fileName);
139220             var formatContext = ts.formatting.getFormatContext(formatOptions, host);
139221             return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences);
139222         }
139223         function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) {
139224             if (preferences === void 0) { preferences = ts.emptyOptions; }
139225             return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions, host), preferences, sourceMapper);
139226         }
139227         function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) {
139228             var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName;
139229             return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a); })) : applySingleCodeActionCommand(action);
139230         }
139231         function applySingleCodeActionCommand(action) {
139232             var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); };
139233             ts.Debug.assertEqual(action.type, "install package");
139234             return host.installPackage
139235                 ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName })
139236                 : Promise.reject("Host does not implement `installPackage`");
139237         }
139238         function getDocCommentTemplateAtPosition(fileName, position) {
139239             return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position);
139240         }
139241         function isValidBraceCompletionAtPosition(fileName, position, openingBrace) {
139242             // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too
139243             // expensive to do during typing scenarios
139244             // i.e. whether we're dealing with:
139245             //      var x = new foo<| ( with class foo<T>{} )
139246             // or
139247             //      var y = 3 <|
139248             if (openingBrace === 60 /* lessThan */) {
139249                 return false;
139250             }
139251             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139252             // Check if in a context where we don't want to perform any insertion
139253             if (ts.isInString(sourceFile, position)) {
139254                 return false;
139255             }
139256             if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) {
139257                 return openingBrace === 123 /* openBrace */;
139258             }
139259             if (ts.isInTemplateString(sourceFile, position)) {
139260                 return false;
139261             }
139262             switch (openingBrace) {
139263                 case 39 /* singleQuote */:
139264                 case 34 /* doubleQuote */:
139265                 case 96 /* backtick */:
139266                     return !ts.isInComment(sourceFile, position);
139267             }
139268             return true;
139269         }
139270         function getJsxClosingTagAtPosition(fileName, position) {
139271             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139272             var token = ts.findPrecedingToken(position, sourceFile);
139273             if (!token)
139274                 return undefined;
139275             var element = token.kind === 31 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent
139276                 : ts.isJsxText(token) ? token.parent : undefined;
139277             if (element && isUnclosedTag(element)) {
139278                 return { newText: "</" + element.openingElement.tagName.getText(sourceFile) + ">" };
139279             }
139280         }
139281         function isUnclosedTag(_a) {
139282             var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent;
139283             return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) ||
139284                 ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent);
139285         }
139286         function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) {
139287             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139288             var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position);
139289             return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined;
139290         }
139291         function getTodoComments(fileName, descriptors) {
139292             // Note: while getting todo comments seems like a syntactic operation, we actually
139293             // treat it as a semantic operation here.  This is because we expect our host to call
139294             // this on every single file.  If we treat this syntactically, then that will cause
139295             // us to populate and throw away the tree in our syntax tree cache for each file.  By
139296             // treating this as a semantic operation, we can access any tree without throwing
139297             // anything away.
139298             synchronizeHostData();
139299             var sourceFile = getValidSourceFile(fileName);
139300             cancellationToken.throwIfCancellationRequested();
139301             var fileContents = sourceFile.text;
139302             var result = [];
139303             // Exclude node_modules files as we don't want to show the todos of external libraries.
139304             if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) {
139305                 var regExp = getTodoCommentsRegExp();
139306                 var matchArray = void 0;
139307                 while (matchArray = regExp.exec(fileContents)) {
139308                     cancellationToken.throwIfCancellationRequested();
139309                     // If we got a match, here is what the match array will look like.  Say the source text is:
139310                     //
139311                     //      "    // hack   1"
139312                     //
139313                     // The result array with the regexp:    will be:
139314                     //
139315                     //      ["// hack   1", "// ", "hack   1", undefined, "hack"]
139316                     //
139317                     // Here are the relevant capture groups:
139318                     //  0) The full match for the entire regexp.
139319                     //  1) The preamble to the message portion.
139320                     //  2) The message portion.
139321                     //  3...N) The descriptor that was matched - by index.  'undefined' for each
139322                     //         descriptor that didn't match.  an actual value if it did match.
139323                     //
139324                     //  i.e. 'undefined' in position 3 above means TODO(jason) didn't match.
139325                     //       "hack"      in position 4 means HACK did match.
139326                     var firstDescriptorCaptureIndex = 3;
139327                     ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex);
139328                     var preamble = matchArray[1];
139329                     var matchPosition = matchArray.index + preamble.length;
139330                     // OK, we have found a match in the file.  This is only an acceptable match if
139331                     // it is contained within a comment.
139332                     if (!ts.isInComment(sourceFile, matchPosition)) {
139333                         continue;
139334                     }
139335                     var descriptor = void 0;
139336                     for (var i = 0; i < descriptors.length; i++) {
139337                         if (matchArray[i + firstDescriptorCaptureIndex]) {
139338                             descriptor = descriptors[i];
139339                         }
139340                     }
139341                     if (descriptor === undefined)
139342                         return ts.Debug.fail();
139343                     // We don't want to match something like 'TODOBY', so we make sure a non
139344                     // letter/digit follows the match.
139345                     if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) {
139346                         continue;
139347                     }
139348                     var message = matchArray[2];
139349                     result.push({ descriptor: descriptor, message: message, position: matchPosition });
139350                 }
139351             }
139352             return result;
139353             function escapeRegExp(str) {
139354                 return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
139355             }
139356             function getTodoCommentsRegExp() {
139357                 // NOTE: `?:` means 'non-capture group'.  It allows us to have groups without having to
139358                 // filter them out later in the final result array.
139359                 // TODO comments can appear in one of the following forms:
139360                 //
139361                 //  1)      // TODO     or  /////////// TODO
139362                 //
139363                 //  2)      /* TODO     or  /********** TODO
139364                 //
139365                 //  3)      /*
139366                 //           *   TODO
139367                 //           */
139368                 //
139369                 // The following three regexps are used to match the start of the text up to the TODO
139370                 // comment portion.
139371                 var singleLineCommentStart = /(?:\/\/+\s*)/.source;
139372                 var multiLineCommentStart = /(?:\/\*+\s*)/.source;
139373                 var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
139374                 // Match any of the above three TODO comment start regexps.
139375                 // Note that the outermost group *is* a capture group.  We want to capture the preamble
139376                 // so that we can determine the starting position of the TODO comment match.
139377                 var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
139378                 // Takes the descriptors and forms a regexp that matches them as if they were literals.
139379                 // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be:
139380                 //
139381                 //      (?:(TODO\(jason\))|(HACK))
139382                 //
139383                 // Note that the outermost group is *not* a capture group, but the innermost groups
139384                 // *are* capture groups.  By capturing the inner literals we can determine after
139385                 // matching which descriptor we are dealing with.
139386                 var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")";
139387                 // After matching a descriptor literal, the following regexp matches the rest of the
139388                 // text up to the end of the line (or */).
139389                 var endOfLineOrEndOfComment = /(?:$|\*\/)/.source;
139390                 var messageRemainder = /(?:.*?)/.source;
139391                 // This is the portion of the match we'll return as part of the TODO comment result. We
139392                 // match the literal portion up to the end of the line or end of comment.
139393                 var messagePortion = "(" + literals + messageRemainder + ")";
139394                 var regExpString = preamble + messagePortion + endOfLineOrEndOfComment;
139395                 // The final regexp will look like this:
139396                 // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim
139397                 // The flags of the regexp are important here.
139398                 //  'g' is so that we are doing a global search and can find matches several times
139399                 //  in the input.
139400                 //
139401                 //  'i' is for case insensitivity (We do this to match C# TODO comment code).
139402                 //
139403                 //  'm' is so we can find matches in a multi-line input.
139404                 return new RegExp(regExpString, "gim");
139405             }
139406             function isLetterOrDigit(char) {
139407                 return (char >= 97 /* a */ && char <= 122 /* z */) ||
139408                     (char >= 65 /* A */ && char <= 90 /* Z */) ||
139409                     (char >= 48 /* _0 */ && char <= 57 /* _9 */);
139410             }
139411             function isNodeModulesFile(path) {
139412                 return ts.stringContains(path, "/node_modules/");
139413             }
139414         }
139415         function getRenameInfo(fileName, position, options) {
139416             synchronizeHostData();
139417             return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options);
139418         }
139419         function getRefactorContext(file, positionOrRange, preferences, formatOptions) {
139420             var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1];
139421             return {
139422                 file: file,
139423                 startPosition: startPosition,
139424                 endPosition: endPosition,
139425                 program: getProgram(),
139426                 host: host,
139427                 formatContext: ts.formatting.getFormatContext(formatOptions, host),
139428                 cancellationToken: cancellationToken,
139429                 preferences: preferences,
139430             };
139431         }
139432         function getSmartSelectionRange(fileName, position) {
139433             return ts.SmartSelectionRange.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName));
139434         }
139435         function getApplicableRefactors(fileName, positionOrRange, preferences) {
139436             if (preferences === void 0) { preferences = ts.emptyOptions; }
139437             synchronizeHostData();
139438             var file = getValidSourceFile(fileName);
139439             return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences));
139440         }
139441         function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) {
139442             if (preferences === void 0) { preferences = ts.emptyOptions; }
139443             synchronizeHostData();
139444             var file = getValidSourceFile(fileName);
139445             return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName);
139446         }
139447         function prepareCallHierarchy(fileName, position) {
139448             synchronizeHostData();
139449             var declarations = ts.CallHierarchy.resolveCallHierarchyDeclaration(program, ts.getTouchingPropertyName(getValidSourceFile(fileName), position));
139450             return declarations && ts.mapOneOrMany(declarations, function (declaration) { return ts.CallHierarchy.createCallHierarchyItem(program, declaration); });
139451         }
139452         function provideCallHierarchyIncomingCalls(fileName, position) {
139453             synchronizeHostData();
139454             var sourceFile = getValidSourceFile(fileName);
139455             var declaration = ts.firstOrOnly(ts.CallHierarchy.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : ts.getTouchingPropertyName(sourceFile, position)));
139456             return declaration ? ts.CallHierarchy.getIncomingCalls(program, declaration, cancellationToken) : [];
139457         }
139458         function provideCallHierarchyOutgoingCalls(fileName, position) {
139459             synchronizeHostData();
139460             var sourceFile = getValidSourceFile(fileName);
139461             var declaration = ts.firstOrOnly(ts.CallHierarchy.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : ts.getTouchingPropertyName(sourceFile, position)));
139462             return declaration ? ts.CallHierarchy.getOutgoingCalls(program, declaration) : [];
139463         }
139464         return {
139465             dispose: dispose,
139466             cleanupSemanticCache: cleanupSemanticCache,
139467             getSyntacticDiagnostics: getSyntacticDiagnostics,
139468             getSemanticDiagnostics: getSemanticDiagnostics,
139469             getSuggestionDiagnostics: getSuggestionDiagnostics,
139470             getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics,
139471             getSyntacticClassifications: getSyntacticClassifications,
139472             getSemanticClassifications: getSemanticClassifications,
139473             getEncodedSyntacticClassifications: getEncodedSyntacticClassifications,
139474             getEncodedSemanticClassifications: getEncodedSemanticClassifications,
139475             getCompletionsAtPosition: getCompletionsAtPosition,
139476             getCompletionEntryDetails: getCompletionEntryDetails,
139477             getCompletionEntrySymbol: getCompletionEntrySymbol,
139478             getSignatureHelpItems: getSignatureHelpItems,
139479             getQuickInfoAtPosition: getQuickInfoAtPosition,
139480             getDefinitionAtPosition: getDefinitionAtPosition,
139481             getDefinitionAndBoundSpan: getDefinitionAndBoundSpan,
139482             getImplementationAtPosition: getImplementationAtPosition,
139483             getTypeDefinitionAtPosition: getTypeDefinitionAtPosition,
139484             getReferencesAtPosition: getReferencesAtPosition,
139485             findReferences: findReferences,
139486             getOccurrencesAtPosition: getOccurrencesAtPosition,
139487             getDocumentHighlights: getDocumentHighlights,
139488             getNameOrDottedNameSpan: getNameOrDottedNameSpan,
139489             getBreakpointStatementAtPosition: getBreakpointStatementAtPosition,
139490             getNavigateToItems: getNavigateToItems,
139491             getRenameInfo: getRenameInfo,
139492             getSmartSelectionRange: getSmartSelectionRange,
139493             findRenameLocations: findRenameLocations,
139494             getNavigationBarItems: getNavigationBarItems,
139495             getNavigationTree: getNavigationTree,
139496             getOutliningSpans: getOutliningSpans,
139497             getTodoComments: getTodoComments,
139498             getBraceMatchingAtPosition: getBraceMatchingAtPosition,
139499             getIndentationAtPosition: getIndentationAtPosition,
139500             getFormattingEditsForRange: getFormattingEditsForRange,
139501             getFormattingEditsForDocument: getFormattingEditsForDocument,
139502             getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke,
139503             getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition,
139504             isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition,
139505             getJsxClosingTagAtPosition: getJsxClosingTagAtPosition,
139506             getSpanOfEnclosingComment: getSpanOfEnclosingComment,
139507             getCodeFixesAtPosition: getCodeFixesAtPosition,
139508             getCombinedCodeFix: getCombinedCodeFix,
139509             applyCodeActionCommand: applyCodeActionCommand,
139510             organizeImports: organizeImports,
139511             getEditsForFileRename: getEditsForFileRename,
139512             getEmitOutput: getEmitOutput,
139513             getNonBoundSourceFile: getNonBoundSourceFile,
139514             getProgram: getProgram,
139515             getApplicableRefactors: getApplicableRefactors,
139516             getEditsForRefactor: getEditsForRefactor,
139517             toLineColumnOffset: sourceMapper.toLineColumnOffset,
139518             getSourceMapper: function () { return sourceMapper; },
139519             clearSourceMapperCache: function () { return sourceMapper.clearCache(); },
139520             prepareCallHierarchy: prepareCallHierarchy,
139521             provideCallHierarchyIncomingCalls: provideCallHierarchyIncomingCalls,
139522             provideCallHierarchyOutgoingCalls: provideCallHierarchyOutgoingCalls
139523         };
139524     }
139525     ts.createLanguageService = createLanguageService;
139526     /* @internal */
139527     /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */
139528     function getNameTable(sourceFile) {
139529         if (!sourceFile.nameTable) {
139530             initializeNameTable(sourceFile);
139531         }
139532         return sourceFile.nameTable; // TODO: GH#18217
139533     }
139534     ts.getNameTable = getNameTable;
139535     function initializeNameTable(sourceFile) {
139536         var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap();
139537         sourceFile.forEachChild(function walk(node) {
139538             if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
139539                 var text = ts.getEscapedTextOfIdentifierOrLiteral(node);
139540                 nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
139541             }
139542             else if (ts.isPrivateIdentifier(node)) {
139543                 var text = node.escapedText;
139544                 nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
139545             }
139546             ts.forEachChild(node, walk);
139547             if (ts.hasJSDocNodes(node)) {
139548                 for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
139549                     var jsDoc = _a[_i];
139550                     ts.forEachChild(jsDoc, walk);
139551                 }
139552             }
139553         });
139554     }
139555     /**
139556      * We want to store any numbers/strings if they were a name that could be
139557      * related to a declaration.  So, if we have 'import x = require("something")'
139558      * then we want 'something' to be in the name table.  Similarly, if we have
139559      * "a['propname']" then we want to store "propname" in the name table.
139560      */
139561     function literalIsName(node) {
139562         return ts.isDeclarationName(node) ||
139563             node.parent.kind === 265 /* ExternalModuleReference */ ||
139564             isArgumentOfElementAccessExpression(node) ||
139565             ts.isLiteralComputedPropertyDeclarationName(node);
139566     }
139567     /**
139568      * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 }
139569      */
139570     /* @internal */
139571     function getContainingObjectLiteralElement(node) {
139572         var element = getContainingObjectLiteralElementWorker(node);
139573         return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined;
139574     }
139575     ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement;
139576     function getContainingObjectLiteralElementWorker(node) {
139577         switch (node.kind) {
139578             case 10 /* StringLiteral */:
139579             case 14 /* NoSubstitutionTemplateLiteral */:
139580             case 8 /* NumericLiteral */:
139581                 if (node.parent.kind === 154 /* ComputedPropertyName */) {
139582                     return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined;
139583                 }
139584             // falls through
139585             case 75 /* Identifier */:
139586                 return ts.isObjectLiteralElement(node.parent) &&
139587                     (node.parent.parent.kind === 193 /* ObjectLiteralExpression */ || node.parent.parent.kind === 274 /* JsxAttributes */) &&
139588                     node.parent.name === node ? node.parent : undefined;
139589         }
139590         return undefined;
139591     }
139592     function getSymbolAtLocationForQuickInfo(node, checker) {
139593         var object = getContainingObjectLiteralElement(node);
139594         if (object) {
139595             var contextualType = checker.getContextualType(object.parent);
139596             var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false);
139597             if (properties && properties.length === 1) {
139598                 return ts.first(properties);
139599             }
139600         }
139601         return checker.getSymbolAtLocation(node);
139602     }
139603     /** Gets all symbols for one property. Does not get symbols for every property. */
139604     /* @internal */
139605     function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) {
139606         var name = ts.getNameFromPropertyName(node.name);
139607         if (!name)
139608             return ts.emptyArray;
139609         if (!contextualType.isUnion()) {
139610             var symbol = contextualType.getProperty(name);
139611             return symbol ? [symbol] : ts.emptyArray;
139612         }
139613         var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); });
139614         if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) {
139615             var symbol = contextualType.getProperty(name);
139616             if (symbol)
139617                 return [symbol];
139618         }
139619         if (discriminatedPropertySymbols.length === 0) {
139620             // Bad discriminant -- do again without discriminating
139621             return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); });
139622         }
139623         return discriminatedPropertySymbols;
139624     }
139625     ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType;
139626     function isArgumentOfElementAccessExpression(node) {
139627         return node &&
139628             node.parent &&
139629             node.parent.kind === 195 /* ElementAccessExpression */ &&
139630             node.parent.argumentExpression === node;
139631     }
139632     /**
139633      * Get the path of the default library files (lib.d.ts) as distributed with the typescript
139634      * node package.
139635      * The functionality is not supported if the ts module is consumed outside of a node module.
139636      */
139637     function getDefaultLibFilePath(options) {
139638         // Check __dirname is defined and that we are on a node.js system.
139639         if (typeof __dirname !== "undefined") {
139640             return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options);
139641         }
139642         throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
139643     }
139644     ts.getDefaultLibFilePath = getDefaultLibFilePath;
139645     ts.setObjectAllocator(getServicesObjectAllocator());
139646 })(ts || (ts = {}));
139647 /* @internal */
139648 var ts;
139649 (function (ts) {
139650     var BreakpointResolver;
139651     (function (BreakpointResolver) {
139652         /**
139653          * Get the breakpoint span in given sourceFile
139654          */
139655         function spanInSourceFileAtLocation(sourceFile, position) {
139656             // Cannot set breakpoint in dts file
139657             if (sourceFile.isDeclarationFile) {
139658                 return undefined;
139659             }
139660             var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position);
139661             var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
139662             if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
139663                 // Get previous token if the token is returned starts on new line
139664                 // eg: let x =10; |--- cursor is here
139665                 //     let y = 10;
139666                 // token at position will return let keyword on second line as the token but we would like to use
139667                 // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
139668                 var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile);
139669                 // It's a blank line
139670                 if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) {
139671                     return undefined;
139672                 }
139673                 tokenAtLocation = preceding;
139674             }
139675             // Cannot set breakpoint in ambient declarations
139676             if (tokenAtLocation.flags & 8388608 /* Ambient */) {
139677                 return undefined;
139678             }
139679             // Get the span in the node based on its syntax
139680             return spanInNode(tokenAtLocation);
139681             function textSpan(startNode, endNode) {
139682                 var start = startNode.decorators ?
139683                     ts.skipTrivia(sourceFile.text, startNode.decorators.end) :
139684                     startNode.getStart(sourceFile);
139685                 return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
139686             }
139687             function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
139688                 return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
139689             }
139690             function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
139691                 if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
139692                     return spanInNode(node);
139693                 }
139694                 return spanInNode(otherwiseOnNode);
139695             }
139696             function spanInNodeArray(nodeArray) {
139697                 return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
139698             }
139699             function spanInPreviousNode(node) {
139700                 return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
139701             }
139702             function spanInNextNode(node) {
139703                 return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
139704             }
139705             function spanInNode(node) {
139706                 if (node) {
139707                     var parent = node.parent;
139708                     switch (node.kind) {
139709                         case 225 /* VariableStatement */:
139710                             // Span on first variable declaration
139711                             return spanInVariableDeclaration(node.declarationList.declarations[0]);
139712                         case 242 /* VariableDeclaration */:
139713                         case 159 /* PropertyDeclaration */:
139714                         case 158 /* PropertySignature */:
139715                             return spanInVariableDeclaration(node);
139716                         case 156 /* Parameter */:
139717                             return spanInParameterDeclaration(node);
139718                         case 244 /* FunctionDeclaration */:
139719                         case 161 /* MethodDeclaration */:
139720                         case 160 /* MethodSignature */:
139721                         case 163 /* GetAccessor */:
139722                         case 164 /* SetAccessor */:
139723                         case 162 /* Constructor */:
139724                         case 201 /* FunctionExpression */:
139725                         case 202 /* ArrowFunction */:
139726                             return spanInFunctionDeclaration(node);
139727                         case 223 /* Block */:
139728                             if (ts.isFunctionBlock(node)) {
139729                                 return spanInFunctionBlock(node);
139730                             }
139731                         // falls through
139732                         case 250 /* ModuleBlock */:
139733                             return spanInBlock(node);
139734                         case 280 /* CatchClause */:
139735                             return spanInBlock(node.block);
139736                         case 226 /* ExpressionStatement */:
139737                             // span on the expression
139738                             return textSpan(node.expression);
139739                         case 235 /* ReturnStatement */:
139740                             // span on return keyword and expression if present
139741                             return textSpan(node.getChildAt(0), node.expression);
139742                         case 229 /* WhileStatement */:
139743                             // Span on while(...)
139744                             return textSpanEndingAtNextToken(node, node.expression);
139745                         case 228 /* DoStatement */:
139746                             // span in statement of the do statement
139747                             return spanInNode(node.statement);
139748                         case 241 /* DebuggerStatement */:
139749                             // span on debugger keyword
139750                             return textSpan(node.getChildAt(0));
139751                         case 227 /* IfStatement */:
139752                             // set on if(..) span
139753                             return textSpanEndingAtNextToken(node, node.expression);
139754                         case 238 /* LabeledStatement */:
139755                             // span in statement
139756                             return spanInNode(node.statement);
139757                         case 234 /* BreakStatement */:
139758                         case 233 /* ContinueStatement */:
139759                             // On break or continue keyword and label if present
139760                             return textSpan(node.getChildAt(0), node.label);
139761                         case 230 /* ForStatement */:
139762                             return spanInForStatement(node);
139763                         case 231 /* ForInStatement */:
139764                             // span of for (a in ...)
139765                             return textSpanEndingAtNextToken(node, node.expression);
139766                         case 232 /* ForOfStatement */:
139767                             // span in initializer
139768                             return spanInInitializerOfForLike(node);
139769                         case 237 /* SwitchStatement */:
139770                             // span on switch(...)
139771                             return textSpanEndingAtNextToken(node, node.expression);
139772                         case 277 /* CaseClause */:
139773                         case 278 /* DefaultClause */:
139774                             // span in first statement of the clause
139775                             return spanInNode(node.statements[0]);
139776                         case 240 /* TryStatement */:
139777                             // span in try block
139778                             return spanInBlock(node.tryBlock);
139779                         case 239 /* ThrowStatement */:
139780                             // span in throw ...
139781                             return textSpan(node, node.expression);
139782                         case 259 /* ExportAssignment */:
139783                             // span on export = id
139784                             return textSpan(node, node.expression);
139785                         case 253 /* ImportEqualsDeclaration */:
139786                             // import statement without including semicolon
139787                             return textSpan(node, node.moduleReference);
139788                         case 254 /* ImportDeclaration */:
139789                             // import statement without including semicolon
139790                             return textSpan(node, node.moduleSpecifier);
139791                         case 260 /* ExportDeclaration */:
139792                             // import statement without including semicolon
139793                             return textSpan(node, node.moduleSpecifier);
139794                         case 249 /* ModuleDeclaration */:
139795                             // span on complete module if it is instantiated
139796                             if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
139797                                 return undefined;
139798                             }
139799                         // falls through
139800                         case 245 /* ClassDeclaration */:
139801                         case 248 /* EnumDeclaration */:
139802                         case 284 /* EnumMember */:
139803                         case 191 /* BindingElement */:
139804                             // span on complete node
139805                             return textSpan(node);
139806                         case 236 /* WithStatement */:
139807                             // span in statement
139808                             return spanInNode(node.statement);
139809                         case 157 /* Decorator */:
139810                             return spanInNodeArray(parent.decorators);
139811                         case 189 /* ObjectBindingPattern */:
139812                         case 190 /* ArrayBindingPattern */:
139813                             return spanInBindingPattern(node);
139814                         // No breakpoint in interface, type alias
139815                         case 246 /* InterfaceDeclaration */:
139816                         case 247 /* TypeAliasDeclaration */:
139817                             return undefined;
139818                         // Tokens:
139819                         case 26 /* SemicolonToken */:
139820                         case 1 /* EndOfFileToken */:
139821                             return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile));
139822                         case 27 /* CommaToken */:
139823                             return spanInPreviousNode(node);
139824                         case 18 /* OpenBraceToken */:
139825                             return spanInOpenBraceToken(node);
139826                         case 19 /* CloseBraceToken */:
139827                             return spanInCloseBraceToken(node);
139828                         case 23 /* CloseBracketToken */:
139829                             return spanInCloseBracketToken(node);
139830                         case 20 /* OpenParenToken */:
139831                             return spanInOpenParenToken(node);
139832                         case 21 /* CloseParenToken */:
139833                             return spanInCloseParenToken(node);
139834                         case 58 /* ColonToken */:
139835                             return spanInColonToken(node);
139836                         case 31 /* GreaterThanToken */:
139837                         case 29 /* LessThanToken */:
139838                             return spanInGreaterThanOrLessThanToken(node);
139839                         // Keywords:
139840                         case 111 /* WhileKeyword */:
139841                             return spanInWhileKeyword(node);
139842                         case 87 /* ElseKeyword */:
139843                         case 79 /* CatchKeyword */:
139844                         case 92 /* FinallyKeyword */:
139845                             return spanInNextNode(node);
139846                         case 152 /* OfKeyword */:
139847                             return spanInOfKeyword(node);
139848                         default:
139849                             // Destructuring pattern in destructuring assignment
139850                             // [a, b, c] of
139851                             // [a, b, c] = expression
139852                             if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
139853                                 return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node);
139854                             }
139855                             // Set breakpoint on identifier element of destructuring pattern
139856                             // `a` or `...c` or `d: x` from
139857                             // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern
139858                             if ((node.kind === 75 /* Identifier */ ||
139859                                 node.kind === 213 /* SpreadElement */ ||
139860                                 node.kind === 281 /* PropertyAssignment */ ||
139861                                 node.kind === 282 /* ShorthandPropertyAssignment */) &&
139862                                 ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) {
139863                                 return textSpan(node);
139864                             }
139865                             if (node.kind === 209 /* BinaryExpression */) {
139866                                 var _a = node, left = _a.left, operatorToken = _a.operatorToken;
139867                                 // Set breakpoint in destructuring pattern if its destructuring assignment
139868                                 // [a, b, c] or {a, b, c} of
139869                                 // [a, b, c] = expression or
139870                                 // {a, b, c} = expression
139871                                 if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
139872                                     return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left);
139873                                 }
139874                                 if (operatorToken.kind === 62 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
139875                                     // Set breakpoint on assignment expression element of destructuring pattern
139876                                     // a = expression of
139877                                     // [a = expression, b, c] = someExpression or
139878                                     // { a = expression, b, c } = someExpression
139879                                     return textSpan(node);
139880                                 }
139881                                 if (operatorToken.kind === 27 /* CommaToken */) {
139882                                     return spanInNode(left);
139883                                 }
139884                             }
139885                             if (ts.isExpressionNode(node)) {
139886                                 switch (parent.kind) {
139887                                     case 228 /* DoStatement */:
139888                                         // Set span as if on while keyword
139889                                         return spanInPreviousNode(node);
139890                                     case 157 /* Decorator */:
139891                                         // Set breakpoint on the decorator emit
139892                                         return spanInNode(node.parent);
139893                                     case 230 /* ForStatement */:
139894                                     case 232 /* ForOfStatement */:
139895                                         return textSpan(node);
139896                                     case 209 /* BinaryExpression */:
139897                                         if (node.parent.operatorToken.kind === 27 /* CommaToken */) {
139898                                             // If this is a comma expression, the breakpoint is possible in this expression
139899                                             return textSpan(node);
139900                                         }
139901                                         break;
139902                                     case 202 /* ArrowFunction */:
139903                                         if (node.parent.body === node) {
139904                                             // If this is body of arrow function, it is allowed to have the breakpoint
139905                                             return textSpan(node);
139906                                         }
139907                                         break;
139908                                 }
139909                             }
139910                             switch (node.parent.kind) {
139911                                 case 281 /* PropertyAssignment */:
139912                                     // If this is name of property assignment, set breakpoint in the initializer
139913                                     if (node.parent.name === node &&
139914                                         !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
139915                                         return spanInNode(node.parent.initializer);
139916                                     }
139917                                     break;
139918                                 case 199 /* TypeAssertionExpression */:
139919                                     // Breakpoint in type assertion goes to its operand
139920                                     if (node.parent.type === node) {
139921                                         return spanInNextNode(node.parent.type);
139922                                     }
139923                                     break;
139924                                 case 242 /* VariableDeclaration */:
139925                                 case 156 /* Parameter */: {
139926                                     // initializer of variable/parameter declaration go to previous node
139927                                     var _b = node.parent, initializer = _b.initializer, type = _b.type;
139928                                     if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) {
139929                                         return spanInPreviousNode(node);
139930                                     }
139931                                     break;
139932                                 }
139933                                 case 209 /* BinaryExpression */: {
139934                                     var left = node.parent.left;
139935                                     if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
139936                                         // If initializer of destructuring assignment move to previous token
139937                                         return spanInPreviousNode(node);
139938                                     }
139939                                     break;
139940                                 }
139941                                 default:
139942                                     // return type of function go to previous token
139943                                     if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
139944                                         return spanInPreviousNode(node);
139945                                     }
139946                             }
139947                             // Default go to parent to set the breakpoint
139948                             return spanInNode(node.parent);
139949                     }
139950                 }
139951                 function textSpanFromVariableDeclaration(variableDeclaration) {
139952                     if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
139953                         // First declaration - include let keyword
139954                         return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
139955                     }
139956                     else {
139957                         // Span only on this declaration
139958                         return textSpan(variableDeclaration);
139959                     }
139960                 }
139961                 function spanInVariableDeclaration(variableDeclaration) {
139962                     // If declaration of for in statement, just set the span in parent
139963                     if (variableDeclaration.parent.parent.kind === 231 /* ForInStatement */) {
139964                         return spanInNode(variableDeclaration.parent.parent);
139965                     }
139966                     var parent = variableDeclaration.parent;
139967                     // If this is a destructuring pattern, set breakpoint in binding pattern
139968                     if (ts.isBindingPattern(variableDeclaration.name)) {
139969                         return spanInBindingPattern(variableDeclaration.name);
139970                     }
139971                     // Breakpoint is possible in variableDeclaration only if there is initialization
139972                     // or its declaration from 'for of'
139973                     if (variableDeclaration.initializer ||
139974                         ts.hasModifier(variableDeclaration, 1 /* Export */) ||
139975                         parent.parent.kind === 232 /* ForOfStatement */) {
139976                         return textSpanFromVariableDeclaration(variableDeclaration);
139977                     }
139978                     if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
139979                         variableDeclaration.parent.declarations[0] !== variableDeclaration) {
139980                         // If we cannot set breakpoint on this declaration, set it on previous one
139981                         // Because the variable declaration may be binding pattern and
139982                         // we would like to set breakpoint in last binding element if that's the case,
139983                         // use preceding token instead
139984                         return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
139985                     }
139986                 }
139987                 function canHaveSpanInParameterDeclaration(parameter) {
139988                     // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier
139989                     return !!parameter.initializer || parameter.dotDotDotToken !== undefined ||
139990                         ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */);
139991                 }
139992                 function spanInParameterDeclaration(parameter) {
139993                     if (ts.isBindingPattern(parameter.name)) {
139994                         // Set breakpoint in binding pattern
139995                         return spanInBindingPattern(parameter.name);
139996                     }
139997                     else if (canHaveSpanInParameterDeclaration(parameter)) {
139998                         return textSpan(parameter);
139999                     }
140000                     else {
140001                         var functionDeclaration = parameter.parent;
140002                         var indexOfParameter = functionDeclaration.parameters.indexOf(parameter);
140003                         ts.Debug.assert(indexOfParameter !== -1);
140004                         if (indexOfParameter !== 0) {
140005                             // Not a first parameter, go to previous parameter
140006                             return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
140007                         }
140008                         else {
140009                             // Set breakpoint in the function declaration body
140010                             return spanInNode(functionDeclaration.body);
140011                         }
140012                     }
140013                 }
140014                 function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
140015                     return ts.hasModifier(functionDeclaration, 1 /* Export */) ||
140016                         (functionDeclaration.parent.kind === 245 /* ClassDeclaration */ && functionDeclaration.kind !== 162 /* Constructor */);
140017                 }
140018                 function spanInFunctionDeclaration(functionDeclaration) {
140019                     // No breakpoints in the function signature
140020                     if (!functionDeclaration.body) {
140021                         return undefined;
140022                     }
140023                     if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) {
140024                         // Set the span on whole function declaration
140025                         return textSpan(functionDeclaration);
140026                     }
140027                     // Set span in function body
140028                     return spanInNode(functionDeclaration.body);
140029                 }
140030                 function spanInFunctionBlock(block) {
140031                     var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
140032                     if (canFunctionHaveSpanInWholeDeclaration(block.parent)) {
140033                         return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
140034                     }
140035                     return spanInNode(nodeForSpanInBlock);
140036                 }
140037                 function spanInBlock(block) {
140038                     switch (block.parent.kind) {
140039                         case 249 /* ModuleDeclaration */:
140040                             if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
140041                                 return undefined;
140042                             }
140043                         // Set on parent if on same line otherwise on first statement
140044                         // falls through
140045                         case 229 /* WhileStatement */:
140046                         case 227 /* IfStatement */:
140047                         case 231 /* ForInStatement */:
140048                             return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
140049                         // Set span on previous token if it starts on same line otherwise on the first statement of the block
140050                         case 230 /* ForStatement */:
140051                         case 232 /* ForOfStatement */:
140052                             return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
140053                     }
140054                     // Default action is to set on first statement
140055                     return spanInNode(block.statements[0]);
140056                 }
140057                 function spanInInitializerOfForLike(forLikeStatement) {
140058                     if (forLikeStatement.initializer.kind === 243 /* VariableDeclarationList */) {
140059                         // Declaration list - set breakpoint in first declaration
140060                         var variableDeclarationList = forLikeStatement.initializer;
140061                         if (variableDeclarationList.declarations.length > 0) {
140062                             return spanInNode(variableDeclarationList.declarations[0]);
140063                         }
140064                     }
140065                     else {
140066                         // Expression - set breakpoint in it
140067                         return spanInNode(forLikeStatement.initializer);
140068                     }
140069                 }
140070                 function spanInForStatement(forStatement) {
140071                     if (forStatement.initializer) {
140072                         return spanInInitializerOfForLike(forStatement);
140073                     }
140074                     if (forStatement.condition) {
140075                         return textSpan(forStatement.condition);
140076                     }
140077                     if (forStatement.incrementor) {
140078                         return textSpan(forStatement.incrementor);
140079                     }
140080                 }
140081                 function spanInBindingPattern(bindingPattern) {
140082                     // Set breakpoint in first binding element
140083                     var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 215 /* OmittedExpression */ ? element : undefined; });
140084                     if (firstBindingElement) {
140085                         return spanInNode(firstBindingElement);
140086                     }
140087                     // Empty binding pattern of binding element, set breakpoint on binding element
140088                     if (bindingPattern.parent.kind === 191 /* BindingElement */) {
140089                         return textSpan(bindingPattern.parent);
140090                     }
140091                     // Variable declaration is used as the span
140092                     return textSpanFromVariableDeclaration(bindingPattern.parent);
140093                 }
140094                 function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) {
140095                     ts.Debug.assert(node.kind !== 190 /* ArrayBindingPattern */ && node.kind !== 189 /* ObjectBindingPattern */);
140096                     var elements = node.kind === 192 /* ArrayLiteralExpression */ ? node.elements : node.properties;
140097                     var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 215 /* OmittedExpression */ ? element : undefined; });
140098                     if (firstBindingElement) {
140099                         return spanInNode(firstBindingElement);
140100                     }
140101                     // Could be ArrayLiteral from destructuring assignment or
140102                     // just nested element in another destructuring assignment
140103                     // set breakpoint on assignment when parent is destructuring assignment
140104                     // Otherwise set breakpoint for this element
140105                     return textSpan(node.parent.kind === 209 /* BinaryExpression */ ? node.parent : node);
140106                 }
140107                 // Tokens:
140108                 function spanInOpenBraceToken(node) {
140109                     switch (node.parent.kind) {
140110                         case 248 /* EnumDeclaration */:
140111                             var enumDeclaration = node.parent;
140112                             return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
140113                         case 245 /* ClassDeclaration */:
140114                             var classDeclaration = node.parent;
140115                             return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
140116                         case 251 /* CaseBlock */:
140117                             return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]);
140118                     }
140119                     // Default to parent node
140120                     return spanInNode(node.parent);
140121                 }
140122                 function spanInCloseBraceToken(node) {
140123                     switch (node.parent.kind) {
140124                         case 250 /* ModuleBlock */:
140125                             // If this is not an instantiated module block, no bp span
140126                             if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) {
140127                                 return undefined;
140128                             }
140129                         // falls through
140130                         case 248 /* EnumDeclaration */:
140131                         case 245 /* ClassDeclaration */:
140132                             // Span on close brace token
140133                             return textSpan(node);
140134                         case 223 /* Block */:
140135                             if (ts.isFunctionBlock(node.parent)) {
140136                                 // Span on close brace token
140137                                 return textSpan(node);
140138                             }
140139                         // falls through
140140                         case 280 /* CatchClause */:
140141                             return spanInNode(ts.lastOrUndefined(node.parent.statements));
140142                         case 251 /* CaseBlock */:
140143                             // breakpoint in last statement of the last clause
140144                             var caseBlock = node.parent;
140145                             var lastClause = ts.lastOrUndefined(caseBlock.clauses);
140146                             if (lastClause) {
140147                                 return spanInNode(ts.lastOrUndefined(lastClause.statements));
140148                             }
140149                             return undefined;
140150                         case 189 /* ObjectBindingPattern */:
140151                             // Breakpoint in last binding element or binding pattern if it contains no elements
140152                             var bindingPattern = node.parent;
140153                             return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
140154                         // Default to parent node
140155                         default:
140156                             if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
140157                                 // Breakpoint in last binding element or binding pattern if it contains no elements
140158                                 var objectLiteral = node.parent;
140159                                 return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral);
140160                             }
140161                             return spanInNode(node.parent);
140162                     }
140163                 }
140164                 function spanInCloseBracketToken(node) {
140165                     switch (node.parent.kind) {
140166                         case 190 /* ArrayBindingPattern */:
140167                             // Breakpoint in last binding element or binding pattern if it contains no elements
140168                             var bindingPattern = node.parent;
140169                             return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
140170                         default:
140171                             if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
140172                                 // Breakpoint in last binding element or binding pattern if it contains no elements
140173                                 var arrayLiteral = node.parent;
140174                                 return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
140175                             }
140176                             // Default to parent node
140177                             return spanInNode(node.parent);
140178                     }
140179                 }
140180                 function spanInOpenParenToken(node) {
140181                     if (node.parent.kind === 228 /* DoStatement */ || // Go to while keyword and do action instead
140182                         node.parent.kind === 196 /* CallExpression */ ||
140183                         node.parent.kind === 197 /* NewExpression */) {
140184                         return spanInPreviousNode(node);
140185                     }
140186                     if (node.parent.kind === 200 /* ParenthesizedExpression */) {
140187                         return spanInNextNode(node);
140188                     }
140189                     // Default to parent node
140190                     return spanInNode(node.parent);
140191                 }
140192                 function spanInCloseParenToken(node) {
140193                     // Is this close paren token of parameter list, set span in previous token
140194                     switch (node.parent.kind) {
140195                         case 201 /* FunctionExpression */:
140196                         case 244 /* FunctionDeclaration */:
140197                         case 202 /* ArrowFunction */:
140198                         case 161 /* MethodDeclaration */:
140199                         case 160 /* MethodSignature */:
140200                         case 163 /* GetAccessor */:
140201                         case 164 /* SetAccessor */:
140202                         case 162 /* Constructor */:
140203                         case 229 /* WhileStatement */:
140204                         case 228 /* DoStatement */:
140205                         case 230 /* ForStatement */:
140206                         case 232 /* ForOfStatement */:
140207                         case 196 /* CallExpression */:
140208                         case 197 /* NewExpression */:
140209                         case 200 /* ParenthesizedExpression */:
140210                             return spanInPreviousNode(node);
140211                         // Default to parent node
140212                         default:
140213                             return spanInNode(node.parent);
140214                     }
140215                 }
140216                 function spanInColonToken(node) {
140217                     // Is this : specifying return annotation of the function declaration
140218                     if (ts.isFunctionLike(node.parent) ||
140219                         node.parent.kind === 281 /* PropertyAssignment */ ||
140220                         node.parent.kind === 156 /* Parameter */) {
140221                         return spanInPreviousNode(node);
140222                     }
140223                     return spanInNode(node.parent);
140224                 }
140225                 function spanInGreaterThanOrLessThanToken(node) {
140226                     if (node.parent.kind === 199 /* TypeAssertionExpression */) {
140227                         return spanInNextNode(node);
140228                     }
140229                     return spanInNode(node.parent);
140230                 }
140231                 function spanInWhileKeyword(node) {
140232                     if (node.parent.kind === 228 /* DoStatement */) {
140233                         // Set span on while expression
140234                         return textSpanEndingAtNextToken(node, node.parent.expression);
140235                     }
140236                     // Default to parent node
140237                     return spanInNode(node.parent);
140238                 }
140239                 function spanInOfKeyword(node) {
140240                     if (node.parent.kind === 232 /* ForOfStatement */) {
140241                         // Set using next token
140242                         return spanInNextNode(node);
140243                     }
140244                     // Default to parent node
140245                     return spanInNode(node.parent);
140246                 }
140247             }
140248         }
140249         BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation;
140250     })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {}));
140251 })(ts || (ts = {}));
140252 var ts;
140253 (function (ts) {
140254     /**
140255      * Transform one or more nodes using the supplied transformers.
140256      * @param source A single `Node` or an array of `Node` objects.
140257      * @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
140258      * @param compilerOptions Optional compiler options.
140259      */
140260     function transform(source, transformers, compilerOptions) {
140261         var diagnostics = [];
140262         compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217
140263         var nodes = ts.isArray(source) ? source : [source];
140264         var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true);
140265         result.diagnostics = ts.concatenate(result.diagnostics, diagnostics);
140266         return result;
140267     }
140268     ts.transform = transform;
140269 })(ts || (ts = {}));
140270 //
140271 // Copyright (c) Microsoft Corporation.  All rights reserved.
140272 //
140273 // Licensed under the Apache License, Version 2.0 (the "License");
140274 // you may not use this file except in compliance with the License.
140275 // You may obtain a copy of the License at
140276 //   http://www.apache.org/licenses/LICENSE-2.0
140277 //
140278 // Unless required by applicable law or agreed to in writing, software
140279 // distributed under the License is distributed on an "AS IS" BASIS,
140280 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
140281 // See the License for the specific language governing permissions and
140282 // limitations under the License.
140283 //
140284 /* @internal */
140285 var debugObjectHost = (function () { return this; })(); // eslint-disable-line prefer-const
140286 // We need to use 'null' to interface with the managed side.
140287 /* eslint-disable no-in-operator */
140288 /* @internal */
140289 var ts;
140290 (function (ts) {
140291     function logInternalError(logger, err) {
140292         if (logger) {
140293             logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
140294         }
140295     }
140296     var ScriptSnapshotShimAdapter = /** @class */ (function () {
140297         function ScriptSnapshotShimAdapter(scriptSnapshotShim) {
140298             this.scriptSnapshotShim = scriptSnapshotShim;
140299         }
140300         ScriptSnapshotShimAdapter.prototype.getText = function (start, end) {
140301             return this.scriptSnapshotShim.getText(start, end);
140302         };
140303         ScriptSnapshotShimAdapter.prototype.getLength = function () {
140304             return this.scriptSnapshotShim.getLength();
140305         };
140306         ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) {
140307             var oldSnapshotShim = oldSnapshot;
140308             var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
140309             /* eslint-disable no-null/no-null */
140310             if (encoded === null) {
140311                 return null; // TODO: GH#18217
140312             }
140313             /* eslint-enable no-null/no-null */
140314             var decoded = JSON.parse(encoded); // TODO: GH#18217
140315             return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
140316         };
140317         ScriptSnapshotShimAdapter.prototype.dispose = function () {
140318             // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments
140319             // 'in' does not have this effect
140320             if ("dispose" in this.scriptSnapshotShim) {
140321                 this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`?
140322             }
140323         };
140324         return ScriptSnapshotShimAdapter;
140325     }());
140326     var LanguageServiceShimHostAdapter = /** @class */ (function () {
140327         function LanguageServiceShimHostAdapter(shimHost) {
140328             var _this = this;
140329             this.shimHost = shimHost;
140330             this.loggingEnabled = false;
140331             this.tracingEnabled = false;
140332             // if shimHost is a COM object then property check will become method call with no arguments.
140333             // 'in' does not have this effect.
140334             if ("getModuleResolutionsForFile" in this.shimHost) {
140335                 this.resolveModuleNames = function (moduleNames, containingFile) {
140336                     var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217
140337                     return ts.map(moduleNames, function (name) {
140338                         var result = ts.getProperty(resolutionsInFile, name);
140339                         return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined;
140340                     });
140341                 };
140342             }
140343             if ("directoryExists" in this.shimHost) {
140344                 this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
140345             }
140346             if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
140347                 this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
140348                     var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217
140349                     return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); });
140350                 };
140351             }
140352         }
140353         LanguageServiceShimHostAdapter.prototype.log = function (s) {
140354             if (this.loggingEnabled) {
140355                 this.shimHost.log(s);
140356             }
140357         };
140358         LanguageServiceShimHostAdapter.prototype.trace = function (s) {
140359             if (this.tracingEnabled) {
140360                 this.shimHost.trace(s);
140361             }
140362         };
140363         LanguageServiceShimHostAdapter.prototype.error = function (s) {
140364             this.shimHost.error(s);
140365         };
140366         LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () {
140367             if (!this.shimHost.getProjectVersion) {
140368                 // shimmed host does not support getProjectVersion
140369                 return undefined; // TODO: GH#18217
140370             }
140371             return this.shimHost.getProjectVersion();
140372         };
140373         LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () {
140374             if (!this.shimHost.getTypeRootsVersion) {
140375                 return 0;
140376             }
140377             return this.shimHost.getTypeRootsVersion();
140378         };
140379         LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () {
140380             return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
140381         };
140382         LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () {
140383             var settingsJson = this.shimHost.getCompilationSettings();
140384             // eslint-disable-next-line no-null/no-null
140385             if (settingsJson === null || settingsJson === "") {
140386                 throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
140387             }
140388             var compilerOptions = JSON.parse(settingsJson);
140389             // permit language service to handle all files (filtering should be performed on the host side)
140390             compilerOptions.allowNonTsExtensions = true;
140391             return compilerOptions;
140392         };
140393         LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () {
140394             var encoded = this.shimHost.getScriptFileNames();
140395             return JSON.parse(encoded);
140396         };
140397         LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) {
140398             var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
140399             return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
140400         };
140401         LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) {
140402             if ("getScriptKind" in this.shimHost) {
140403                 return this.shimHost.getScriptKind(fileName); // TODO: GH#18217
140404             }
140405             else {
140406                 return 0 /* Unknown */;
140407             }
140408         };
140409         LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) {
140410             return this.shimHost.getScriptVersion(fileName);
140411         };
140412         LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () {
140413             /* eslint-disable no-null/no-null */
140414             var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
140415             if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") {
140416                 return null;
140417             }
140418             try {
140419                 return JSON.parse(diagnosticMessagesJson);
140420             }
140421             catch (e) {
140422                 this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
140423                 return null;
140424             }
140425             /* eslint-enable no-null/no-null */
140426         };
140427         LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () {
140428             var hostCancellationToken = this.shimHost.getCancellationToken();
140429             return new ts.ThrottledCancellationToken(hostCancellationToken);
140430         };
140431         LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () {
140432             return this.shimHost.getCurrentDirectory();
140433         };
140434         LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
140435             return JSON.parse(this.shimHost.getDirectories(path));
140436         };
140437         LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
140438             return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
140439         };
140440         LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) {
140441             var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
140442             return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
140443         };
140444         LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) {
140445             return this.shimHost.readFile(path, encoding);
140446         };
140447         LanguageServiceShimHostAdapter.prototype.fileExists = function (path) {
140448             return this.shimHost.fileExists(path);
140449         };
140450         return LanguageServiceShimHostAdapter;
140451     }());
140452     ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter;
140453     var CoreServicesShimHostAdapter = /** @class */ (function () {
140454         function CoreServicesShimHostAdapter(shimHost) {
140455             var _this = this;
140456             this.shimHost = shimHost;
140457             this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
140458             if ("directoryExists" in this.shimHost) {
140459                 this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
140460             }
140461             else {
140462                 this.directoryExists = undefined; // TODO: GH#18217
140463             }
140464             if ("realpath" in this.shimHost) {
140465                 this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217
140466             }
140467             else {
140468                 this.realpath = undefined; // TODO: GH#18217
140469             }
140470         }
140471         CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) {
140472             var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
140473             return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
140474         };
140475         CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) {
140476             return this.shimHost.fileExists(fileName);
140477         };
140478         CoreServicesShimHostAdapter.prototype.readFile = function (fileName) {
140479             return this.shimHost.readFile(fileName);
140480         };
140481         CoreServicesShimHostAdapter.prototype.getDirectories = function (path) {
140482             return JSON.parse(this.shimHost.getDirectories(path));
140483         };
140484         return CoreServicesShimHostAdapter;
140485     }());
140486     ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter;
140487     function simpleForwardCall(logger, actionDescription, action, logPerformance) {
140488         var start;
140489         if (logPerformance) {
140490             logger.log(actionDescription);
140491             start = ts.timestamp();
140492         }
140493         var result = action();
140494         if (logPerformance) {
140495             var end = ts.timestamp();
140496             logger.log(actionDescription + " completed in " + (end - start) + " msec");
140497             if (ts.isString(result)) {
140498                 var str = result;
140499                 if (str.length > 128) {
140500                     str = str.substring(0, 128) + "...";
140501                 }
140502                 logger.log("  result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
140503             }
140504         }
140505         return result;
140506     }
140507     function forwardJSONCall(logger, actionDescription, action, logPerformance) {
140508         return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance);
140509     }
140510     function forwardCall(logger, actionDescription, returnJson, action, logPerformance) {
140511         try {
140512             var result = simpleForwardCall(logger, actionDescription, action, logPerformance);
140513             return returnJson ? JSON.stringify({ result: result }) : result;
140514         }
140515         catch (err) {
140516             if (err instanceof ts.OperationCanceledException) {
140517                 return JSON.stringify({ canceled: true });
140518             }
140519             logInternalError(logger, err);
140520             err.description = actionDescription;
140521             return JSON.stringify({ error: err });
140522         }
140523     }
140524     var ShimBase = /** @class */ (function () {
140525         function ShimBase(factory) {
140526             this.factory = factory;
140527             factory.registerShim(this);
140528         }
140529         ShimBase.prototype.dispose = function (_dummy) {
140530             this.factory.unregisterShim(this);
140531         };
140532         return ShimBase;
140533     }());
140534     function realizeDiagnostics(diagnostics, newLine) {
140535         return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); });
140536     }
140537     ts.realizeDiagnostics = realizeDiagnostics;
140538     function realizeDiagnostic(diagnostic, newLine) {
140539         return {
140540             message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine),
140541             start: diagnostic.start,
140542             length: diagnostic.length,
140543             category: ts.diagnosticCategoryName(diagnostic),
140544             code: diagnostic.code,
140545             reportsUnnecessary: diagnostic.reportsUnnecessary,
140546         };
140547     }
140548     var LanguageServiceShimObject = /** @class */ (function (_super) {
140549         __extends(LanguageServiceShimObject, _super);
140550         function LanguageServiceShimObject(factory, host, languageService) {
140551             var _this = _super.call(this, factory) || this;
140552             _this.host = host;
140553             _this.languageService = languageService;
140554             _this.logPerformance = false;
140555             _this.logger = _this.host;
140556             return _this;
140557         }
140558         LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) {
140559             return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
140560         };
140561         /// DISPOSE
140562         /**
140563          * Ensure (almost) deterministic release of internal Javascript resources when
140564          * some external native objects holds onto us (e.g. Com/Interop).
140565          */
140566         LanguageServiceShimObject.prototype.dispose = function (dummy) {
140567             this.logger.log("dispose()");
140568             this.languageService.dispose();
140569             this.languageService = null; // eslint-disable-line no-null/no-null
140570             // force a GC
140571             if (debugObjectHost && debugObjectHost.CollectGarbage) {
140572                 debugObjectHost.CollectGarbage();
140573                 this.logger.log("CollectGarbage()");
140574             }
140575             this.logger = null; // eslint-disable-line no-null/no-null
140576             _super.prototype.dispose.call(this, dummy);
140577         };
140578         /// REFRESH
140579         /**
140580          * Update the list of scripts known to the compiler
140581          */
140582         LanguageServiceShimObject.prototype.refresh = function (throwOnError) {
140583             this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; } // eslint-disable-line no-null/no-null
140584             );
140585         };
140586         LanguageServiceShimObject.prototype.cleanupSemanticCache = function () {
140587             var _this = this;
140588             this.forwardJSONCall("cleanupSemanticCache()", function () {
140589                 _this.languageService.cleanupSemanticCache();
140590                 return null; // eslint-disable-line no-null/no-null
140591             });
140592         };
140593         LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) {
140594             var newLine = ts.getNewLineOrDefaultFromHost(this.host);
140595             return realizeDiagnostics(diagnostics, newLine);
140596         };
140597         LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) {
140598             var _this = this;
140599             return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); });
140600         };
140601         LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) {
140602             var _this = this;
140603             return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); });
140604         };
140605         LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) {
140606             var _this = this;
140607             return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", 
140608             // directly serialize the spans out to a string.  This is much faster to decode
140609             // on the managed side versus a full JSON array.
140610             function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); });
140611         };
140612         LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) {
140613             var _this = this;
140614             return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", 
140615             // directly serialize the spans out to a string.  This is much faster to decode
140616             // on the managed side versus a full JSON array.
140617             function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); });
140618         };
140619         LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) {
140620             var _this = this;
140621             return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () {
140622                 var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName);
140623                 return _this.realizeDiagnostics(diagnostics);
140624             });
140625         };
140626         LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) {
140627             var _this = this;
140628             return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () {
140629                 var diagnostics = _this.languageService.getSemanticDiagnostics(fileName);
140630                 return _this.realizeDiagnostics(diagnostics);
140631             });
140632         };
140633         LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) {
140634             var _this = this;
140635             return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); });
140636         };
140637         LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () {
140638             var _this = this;
140639             return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () {
140640                 var diagnostics = _this.languageService.getCompilerOptionsDiagnostics();
140641                 return _this.realizeDiagnostics(diagnostics);
140642             });
140643         };
140644         /// QUICKINFO
140645         /**
140646          * Computes a string representation of the type at the requested position
140647          * in the active file.
140648          */
140649         LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) {
140650             var _this = this;
140651             return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); });
140652         };
140653         /// NAMEORDOTTEDNAMESPAN
140654         /**
140655          * Computes span information of the name or dotted name at the requested position
140656          * in the active file.
140657          */
140658         LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) {
140659             var _this = this;
140660             return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); });
140661         };
140662         /**
140663          * STATEMENTSPAN
140664          * Computes span information of statement at the requested position in the active file.
140665          */
140666         LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) {
140667             var _this = this;
140668             return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); });
140669         };
140670         /// SIGNATUREHELP
140671         LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) {
140672             var _this = this;
140673             return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); });
140674         };
140675         /// GOTO DEFINITION
140676         /**
140677          * Computes the definition location and file for the symbol
140678          * at the requested position.
140679          */
140680         LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) {
140681             var _this = this;
140682             return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); });
140683         };
140684         /**
140685          * Computes the definition location and file for the symbol
140686          * at the requested position.
140687          */
140688         LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) {
140689             var _this = this;
140690             return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); });
140691         };
140692         /// GOTO Type
140693         /**
140694          * Computes the definition location of the type of the symbol
140695          * at the requested position.
140696          */
140697         LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) {
140698             var _this = this;
140699             return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); });
140700         };
140701         /// GOTO Implementation
140702         /**
140703          * Computes the implementation location of the symbol
140704          * at the requested position.
140705          */
140706         LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) {
140707             var _this = this;
140708             return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); });
140709         };
140710         LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) {
140711             var _this = this;
140712             return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position, options); });
140713         };
140714         LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) {
140715             var _this = this;
140716             return this.forwardJSONCall("getSmartSelectionRange('" + fileName + "', " + position + ")", function () { return _this.languageService.getSmartSelectionRange(fileName, position); });
140717         };
140718         LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) {
140719             var _this = this;
140720             return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ", " + providePrefixAndSuffixTextForRename + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); });
140721         };
140722         /// GET BRACE MATCHING
140723         LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) {
140724             var _this = this;
140725             return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); });
140726         };
140727         LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) {
140728             var _this = this;
140729             return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); });
140730         };
140731         LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) {
140732             var _this = this;
140733             return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); });
140734         };
140735         /// GET SMART INDENT
140736         LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) {
140737             var _this = this;
140738             return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () {
140739                 var localOptions = JSON.parse(options);
140740                 return _this.languageService.getIndentationAtPosition(fileName, position, localOptions);
140741             });
140742         };
140743         /// GET REFERENCES
140744         LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) {
140745             var _this = this;
140746             return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); });
140747         };
140748         LanguageServiceShimObject.prototype.findReferences = function (fileName, position) {
140749             var _this = this;
140750             return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); });
140751         };
140752         LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) {
140753             var _this = this;
140754             return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); });
140755         };
140756         LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) {
140757             var _this = this;
140758             return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () {
140759                 var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
140760                 // workaround for VS document highlighting issue - keep only items from the initial file
140761                 var normalizedName = ts.toFileNameLowerCase(ts.normalizeSlashes(fileName));
140762                 return ts.filter(results, function (r) { return ts.toFileNameLowerCase(ts.normalizeSlashes(r.fileName)) === normalizedName; });
140763             });
140764         };
140765         /// COMPLETION LISTS
140766         /**
140767          * Get a string based representation of the completions
140768          * to provide at the given source position and providing a member completion
140769          * list if requested.
140770          */
140771         LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) {
140772             var _this = this;
140773             return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); });
140774         };
140775         /** Get a string based representation of a completion list entry details */
140776         LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) {
140777             var _this = this;
140778             return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () {
140779                 var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions);
140780                 return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences);
140781             });
140782         };
140783         LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) {
140784             var _this = this;
140785             return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () {
140786                 var localOptions = JSON.parse(options);
140787                 return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
140788             });
140789         };
140790         LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) {
140791             var _this = this;
140792             return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () {
140793                 var localOptions = JSON.parse(options);
140794                 return _this.languageService.getFormattingEditsForDocument(fileName, localOptions);
140795             });
140796         };
140797         LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) {
140798             var _this = this;
140799             return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () {
140800                 var localOptions = JSON.parse(options);
140801                 return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
140802             });
140803         };
140804         LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) {
140805             var _this = this;
140806             return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); });
140807         };
140808         /// NAVIGATE TO
140809         /** Return a list of symbols that are interesting to navigate to */
140810         LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) {
140811             var _this = this;
140812             return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); });
140813         };
140814         LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) {
140815             var _this = this;
140816             return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); });
140817         };
140818         LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) {
140819             var _this = this;
140820             return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); });
140821         };
140822         LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) {
140823             var _this = this;
140824             return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); });
140825         };
140826         LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) {
140827             var _this = this;
140828             return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); });
140829         };
140830         /// CALL HIERARCHY
140831         LanguageServiceShimObject.prototype.prepareCallHierarchy = function (fileName, position) {
140832             var _this = this;
140833             return this.forwardJSONCall("prepareCallHierarchy('" + fileName + "', " + position + ")", function () { return _this.languageService.prepareCallHierarchy(fileName, position); });
140834         };
140835         LanguageServiceShimObject.prototype.provideCallHierarchyIncomingCalls = function (fileName, position) {
140836             var _this = this;
140837             return this.forwardJSONCall("provideCallHierarchyIncomingCalls('" + fileName + "', " + position + ")", function () { return _this.languageService.provideCallHierarchyIncomingCalls(fileName, position); });
140838         };
140839         LanguageServiceShimObject.prototype.provideCallHierarchyOutgoingCalls = function (fileName, position) {
140840             var _this = this;
140841             return this.forwardJSONCall("provideCallHierarchyOutgoingCalls('" + fileName + "', " + position + ")", function () { return _this.languageService.provideCallHierarchyOutgoingCalls(fileName, position); });
140842         };
140843         /// Emit
140844         LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) {
140845             var _this = this;
140846             return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () {
140847                 var _a = _this.languageService.getEmitOutput(fileName), diagnostics = _a.diagnostics, rest = __rest(_a, ["diagnostics"]);
140848                 return __assign(__assign({}, rest), { diagnostics: _this.realizeDiagnostics(diagnostics) });
140849             });
140850         };
140851         LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) {
140852             var _this = this;
140853             return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", 
140854             /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance);
140855         };
140856         return LanguageServiceShimObject;
140857     }(ShimBase));
140858     function convertClassifications(classifications) {
140859         return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
140860     }
140861     var ClassifierShimObject = /** @class */ (function (_super) {
140862         __extends(ClassifierShimObject, _super);
140863         function ClassifierShimObject(factory, logger) {
140864             var _this = _super.call(this, factory) || this;
140865             _this.logger = logger;
140866             _this.logPerformance = false;
140867             _this.classifier = ts.createClassifier();
140868             return _this;
140869         }
140870         ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) {
140871             var _this = this;
140872             if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; }
140873             return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance);
140874         };
140875         /// COLORIZATION
140876         ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) {
140877             if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; }
140878             var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
140879             var result = "";
140880             for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) {
140881                 var item = _a[_i];
140882                 result += item.length + "\n";
140883                 result += item.classification + "\n";
140884             }
140885             result += classification.finalLexState;
140886             return result;
140887         };
140888         return ClassifierShimObject;
140889     }(ShimBase));
140890     var CoreServicesShimObject = /** @class */ (function (_super) {
140891         __extends(CoreServicesShimObject, _super);
140892         function CoreServicesShimObject(factory, logger, host) {
140893             var _this = _super.call(this, factory) || this;
140894             _this.logger = logger;
140895             _this.host = host;
140896             _this.logPerformance = false;
140897             return _this;
140898         }
140899         CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) {
140900             return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
140901         };
140902         CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) {
140903             var _this = this;
140904             return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () {
140905                 var compilerOptions = JSON.parse(compilerOptionsJson);
140906                 var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
140907                 var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined;
140908                 if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) {
140909                     resolvedFileName = undefined;
140910                 }
140911                 return {
140912                     resolvedFileName: resolvedFileName,
140913                     failedLookupLocations: result.failedLookupLocations
140914                 };
140915             });
140916         };
140917         CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) {
140918             var _this = this;
140919             return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () {
140920                 var compilerOptions = JSON.parse(compilerOptionsJson);
140921                 var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
140922                 return {
140923                     resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined,
140924                     primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true,
140925                     failedLookupLocations: result.failedLookupLocations
140926                 };
140927             });
140928         };
140929         CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) {
140930             var _this = this;
140931             return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () {
140932                 // for now treat files as JavaScript
140933                 var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
140934                 return {
140935                     referencedFiles: _this.convertFileReferences(result.referencedFiles),
140936                     importedFiles: _this.convertFileReferences(result.importedFiles),
140937                     ambientExternalModules: result.ambientExternalModules,
140938                     isLibFile: result.isLibFile,
140939                     typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives),
140940                     libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives)
140941                 };
140942             });
140943         };
140944         CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) {
140945             var _this = this;
140946             return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () {
140947                 var compilerOptions = JSON.parse(compilerOptionsJson);
140948                 return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host);
140949             });
140950         };
140951         CoreServicesShimObject.prototype.convertFileReferences = function (refs) {
140952             if (!refs) {
140953                 return undefined;
140954             }
140955             var result = [];
140956             for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
140957                 var ref = refs_1[_i];
140958                 result.push({
140959                     path: ts.normalizeSlashes(ref.fileName),
140960                     position: ref.pos,
140961                     length: ref.end - ref.pos
140962                 });
140963             }
140964             return result;
140965         };
140966         CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) {
140967             var _this = this;
140968             return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () {
140969                 var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot));
140970                 var normalizedFileName = ts.normalizeSlashes(fileName);
140971                 var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName);
140972                 return {
140973                     options: configFile.options,
140974                     typeAcquisition: configFile.typeAcquisition,
140975                     files: configFile.fileNames,
140976                     raw: configFile.raw,
140977                     errors: realizeDiagnostics(__spreadArrays(result.parseDiagnostics, configFile.errors), "\r\n")
140978                 };
140979             });
140980         };
140981         CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () {
140982             return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); });
140983         };
140984         CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) {
140985             var _this = this;
140986             var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false);
140987             return this.forwardJSONCall("discoverTypings()", function () {
140988                 var info = JSON.parse(discoverTypingsJson);
140989                 if (_this.safeList === undefined) {
140990                     _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName));
140991                 }
140992                 return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry);
140993             });
140994         };
140995         return CoreServicesShimObject;
140996     }(ShimBase));
140997     var TypeScriptServicesFactory = /** @class */ (function () {
140998         function TypeScriptServicesFactory() {
140999             this._shims = [];
141000         }
141001         /*
141002          * Returns script API version.
141003          */
141004         TypeScriptServicesFactory.prototype.getServicesVersion = function () {
141005             return ts.servicesVersion;
141006         };
141007         TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) {
141008             try {
141009                 if (this.documentRegistry === undefined) {
141010                     this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
141011                 }
141012                 var hostAdapter = new LanguageServiceShimHostAdapter(host);
141013                 var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false);
141014                 return new LanguageServiceShimObject(this, host, languageService);
141015             }
141016             catch (err) {
141017                 logInternalError(host, err);
141018                 throw err;
141019             }
141020         };
141021         TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) {
141022             try {
141023                 return new ClassifierShimObject(this, logger);
141024             }
141025             catch (err) {
141026                 logInternalError(logger, err);
141027                 throw err;
141028             }
141029         };
141030         TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) {
141031             try {
141032                 var adapter = new CoreServicesShimHostAdapter(host);
141033                 return new CoreServicesShimObject(this, host, adapter);
141034             }
141035             catch (err) {
141036                 logInternalError(host, err);
141037                 throw err;
141038             }
141039         };
141040         TypeScriptServicesFactory.prototype.close = function () {
141041             // Forget all the registered shims
141042             ts.clear(this._shims);
141043             this.documentRegistry = undefined;
141044         };
141045         TypeScriptServicesFactory.prototype.registerShim = function (shim) {
141046             this._shims.push(shim);
141047         };
141048         TypeScriptServicesFactory.prototype.unregisterShim = function (shim) {
141049             for (var i = 0; i < this._shims.length; i++) {
141050                 if (this._shims[i] === shim) {
141051                     delete this._shims[i];
141052                     return;
141053                 }
141054             }
141055             throw new Error("Invalid operation");
141056         };
141057         return TypeScriptServicesFactory;
141058     }());
141059     ts.TypeScriptServicesFactory = TypeScriptServicesFactory;
141060 })(ts || (ts = {}));
141061 /* eslint-enable no-in-operator */
141062 // We polyfill `globalThis` here so re can reliably patch the global scope
141063 // in the contexts we want to in the same way across script and module formats
141064 /* eslint-enable no-var */
141065 ((function () {
141066     if (typeof globalThis === "object")
141067         return;
141068     try {
141069         Object.defineProperty(Object.prototype, "__magic__", {
141070             get: function () {
141071                 return this;
141072             },
141073             configurable: true
141074         });
141075         //@ts-ignore
141076         __magic__.globalThis = __magic__;
141077         // The previous line should have made `globalThis` globally
141078         // available, but it fails in Internet Explorer 10 and older.
141079         // Detect this failure and fall back.
141080         if (typeof globalThis === "undefined") {
141081             // Assume `window` exists.
141082             //@ts-ignore
141083             window.globalThis = window;
141084         }
141085         //@ts-ignore
141086         delete Object.prototype.__magic__;
141087     }
141088     catch (error) {
141089         // In IE8, Object.defineProperty only works on DOM objects.
141090         // If we hit this code path, assume `window` exists.
141091         //@ts-ignore
141092         window.globalThis = window;
141093     }
141094 })());
141095 // #endregion The polyfill ends here.
141096 // if `process` is undefined, we're probably not running in node - patch legacy members onto the global scope
141097 // @ts-ignore
141098 if (typeof process === "undefined" || process.browser) {
141099     /// TODO: this is used by VS, clean this up on both sides of the interface
141100     //@ts-ignore
141101     globalThis.TypeScript = globalThis.TypeScript || {};
141102     //@ts-ignore
141103     globalThis.TypeScript.Services = globalThis.TypeScript.Services || {};
141104     //@ts-ignore
141105     globalThis.TypeScript.Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
141106     // 'toolsVersion' gets consumed by the managed side, so it's not unused.
141107     // TODO: it should be moved into a namespace though.
141108     //@ts-ignore
141109     globalThis.toolsVersion = ts.versionMajorMinor;
141110 }
141111 if (typeof module !== "undefined" && module.exports) {
141112     module.exports = ts;
141113 }
141114 var ts;
141115 (function (ts) {
141116     var server;
141117     (function (server) {
141118         /* @internal */
141119         server.ActionSet = "action::set";
141120         /* @internal */
141121         server.ActionInvalidate = "action::invalidate";
141122         /* @internal */
141123         server.ActionPackageInstalled = "action::packageInstalled";
141124         /* @internal */
141125         server.EventTypesRegistry = "event::typesRegistry";
141126         /* @internal */
141127         server.EventBeginInstallTypes = "event::beginInstallTypes";
141128         /* @internal */
141129         server.EventEndInstallTypes = "event::endInstallTypes";
141130         /* @internal */
141131         server.EventInitializationFailed = "event::initializationFailed";
141132         /* @internal */
141133         var Arguments;
141134         (function (Arguments) {
141135             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
141136             Arguments.LogFile = "--logFile";
141137             Arguments.EnableTelemetry = "--enableTelemetry";
141138             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
141139             Arguments.TypesMapLocation = "--typesMapLocation";
141140             /**
141141              * This argument specifies the location of the NPM executable.
141142              * typingsInstaller will run the command with `${npmLocation} install ...`.
141143              */
141144             Arguments.NpmLocation = "--npmLocation";
141145             /**
141146              * Flag indicating that the typings installer should try to validate the default npm location.
141147              * If the default npm is not found when this flag is enabled, fallback to `npm install`
141148              */
141149             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
141150         })(Arguments = server.Arguments || (server.Arguments = {}));
141151         /* @internal */
141152         function hasArgument(argumentName) {
141153             return ts.sys.args.indexOf(argumentName) >= 0;
141154         }
141155         server.hasArgument = hasArgument;
141156         /* @internal */
141157         function findArgument(argumentName) {
141158             var index = ts.sys.args.indexOf(argumentName);
141159             return index >= 0 && index < ts.sys.args.length - 1
141160                 ? ts.sys.args[index + 1]
141161                 : undefined;
141162         }
141163         server.findArgument = findArgument;
141164         /* @internal */
141165         function nowString() {
141166             // E.g. "12:34:56.789"
141167             var d = new Date();
141168             return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
141169         }
141170         server.nowString = nowString;
141171     })(server = ts.server || (ts.server = {}));
141172 })(ts || (ts = {}));
141173 /* @internal */
141174 var ts;
141175 (function (ts) {
141176     var JsTyping;
141177     (function (JsTyping) {
141178         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
141179             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
141180             return availableVersion.compareTo(cachedTyping.version) <= 0;
141181         }
141182         JsTyping.isTypingUpToDate = isTypingUpToDate;
141183         JsTyping.nodeCoreModuleList = [
141184             "assert",
141185             "async_hooks",
141186             "buffer",
141187             "child_process",
141188             "cluster",
141189             "console",
141190             "constants",
141191             "crypto",
141192             "dgram",
141193             "dns",
141194             "domain",
141195             "events",
141196             "fs",
141197             "http",
141198             "https",
141199             "http2",
141200             "inspector",
141201             "net",
141202             "os",
141203             "path",
141204             "perf_hooks",
141205             "process",
141206             "punycode",
141207             "querystring",
141208             "readline",
141209             "repl",
141210             "stream",
141211             "string_decoder",
141212             "timers",
141213             "tls",
141214             "tty",
141215             "url",
141216             "util",
141217             "v8",
141218             "vm",
141219             "zlib"
141220         ];
141221         JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
141222         function nonRelativeModuleNameForTypingCache(moduleName) {
141223             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
141224         }
141225         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
141226         function loadSafeList(host, safeListPath) {
141227             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
141228             return ts.createMapFromTemplate(result.config);
141229         }
141230         JsTyping.loadSafeList = loadSafeList;
141231         function loadTypesMap(host, typesMapPath) {
141232             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
141233             if (result.config) {
141234                 return ts.createMapFromTemplate(result.config.simpleMap);
141235             }
141236             return undefined;
141237         }
141238         JsTyping.loadTypesMap = loadTypesMap;
141239         /**
141240          * @param host is the object providing I/O related operations.
141241          * @param fileNames are the file names that belong to the same project
141242          * @param projectRootPath is the path to the project root directory
141243          * @param safeListPath is the path used to retrieve the safe list
141244          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
141245          * @param typeAcquisition is used to customize the typing acquisition process
141246          * @param compilerOptions are used as a source for typing inference
141247          */
141248         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
141249             if (!typeAcquisition || !typeAcquisition.enable) {
141250                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
141251             }
141252             // A typing name to typing file path mapping
141253             var inferredTypings = ts.createMap();
141254             // Only infer typings for .js and .jsx files
141255             fileNames = ts.mapDefined(fileNames, function (fileName) {
141256                 var path = ts.normalizePath(fileName);
141257                 if (ts.hasJSFileExtension(path)) {
141258                     return path;
141259                 }
141260             });
141261             var filesToWatch = [];
141262             if (typeAcquisition.include)
141263                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
141264             var exclude = typeAcquisition.exclude || [];
141265             // Directories to search for package.json, bower.json and other typing information
141266             var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
141267             possibleSearchDirs.set(projectRootPath, true);
141268             possibleSearchDirs.forEach(function (_true, searchDir) {
141269                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
141270                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
141271                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
141272                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
141273                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
141274                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
141275                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
141276                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
141277             });
141278             getTypingNamesFromSourceFileNames(fileNames);
141279             // add typings for unresolved imports
141280             if (unresolvedImports) {
141281                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
141282                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
141283             }
141284             // Add the cached typing locations for inferred typings that are already installed
141285             packageNameToTypingLocation.forEach(function (typing, name) {
141286                 var registryEntry = typesRegistry.get(name);
141287                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
141288                     inferredTypings.set(name, typing.typingLocation);
141289                 }
141290             });
141291             // Remove typings that the user has added to the exclude list
141292             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
141293                 var excludeTypingName = exclude_1[_i];
141294                 var didDelete = inferredTypings.delete(excludeTypingName);
141295                 if (didDelete && log)
141296                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
141297             }
141298             var newTypingNames = [];
141299             var cachedTypingPaths = [];
141300             inferredTypings.forEach(function (inferred, typing) {
141301                 if (inferred !== undefined) {
141302                     cachedTypingPaths.push(inferred);
141303                 }
141304                 else {
141305                     newTypingNames.push(typing);
141306                 }
141307             });
141308             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
141309             if (log)
141310                 log("Result: " + JSON.stringify(result));
141311             return result;
141312             function addInferredTyping(typingName) {
141313                 if (!inferredTypings.has(typingName)) {
141314                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
141315                 }
141316             }
141317             function addInferredTypings(typingNames, message) {
141318                 if (log)
141319                     log(message + ": " + JSON.stringify(typingNames));
141320                 ts.forEach(typingNames, addInferredTyping);
141321             }
141322             /**
141323              * Get the typing info from common package manager json files like package.json or bower.json
141324              */
141325             function getTypingNamesFromJson(jsonPath, filesToWatch) {
141326                 if (!host.fileExists(jsonPath)) {
141327                     return;
141328                 }
141329                 filesToWatch.push(jsonPath);
141330                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
141331                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
141332                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
141333             }
141334             /**
141335              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
141336              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
141337              * to the 'angular-route' typing name.
141338              * @param fileNames are the names for source files in the project
141339              */
141340             function getTypingNamesFromSourceFileNames(fileNames) {
141341                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
141342                     if (!ts.hasJSFileExtension(j))
141343                         return undefined;
141344                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
141345                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
141346                     return safeList.get(cleanedTypingName);
141347                 });
141348                 if (fromFileNames.length) {
141349                     addInferredTypings(fromFileNames, "Inferred typings from file names");
141350                 }
141351                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
141352                 if (hasJsxFile) {
141353                     if (log)
141354                         log("Inferred 'react' typings due to presence of '.jsx' extension");
141355                     addInferredTyping("react");
141356                 }
141357             }
141358             /**
141359              * Infer typing names from packages folder (ex: node_module, bower_components)
141360              * @param packagesFolderPath is the path to the packages folder
141361              */
141362             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
141363                 filesToWatch.push(packagesFolderPath);
141364                 // Todo: add support for ModuleResolutionHost too
141365                 if (!host.directoryExists(packagesFolderPath)) {
141366                     return;
141367                 }
141368                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
141369                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
141370                 if (log)
141371                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
141372                 var packageNames = [];
141373                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
141374                     var fileName = fileNames_1[_i];
141375                     var normalizedFileName = ts.normalizePath(fileName);
141376                     var baseFileName = ts.getBaseFileName(normalizedFileName);
141377                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
141378                         continue;
141379                     }
141380                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
141381                     var packageJson = result_1.config;
141382                     // npm 3's package.json contains a "_requiredBy" field
141383                     // we should include all the top level module names for npm 2, and only module names whose
141384                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
141385                     if (baseFileName === "package.json" && packageJson._requiredBy &&
141386                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
141387                         continue;
141388                     }
141389                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
141390                     // to download d.ts files from DefinitelyTyped
141391                     if (!packageJson.name) {
141392                         continue;
141393                     }
141394                     var ownTypes = packageJson.types || packageJson.typings;
141395                     if (ownTypes) {
141396                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
141397                         if (log)
141398                             log("    Package '" + packageJson.name + "' provides its own types.");
141399                         inferredTypings.set(packageJson.name, absolutePath);
141400                     }
141401                     else {
141402                         packageNames.push(packageJson.name);
141403                     }
141404                 }
141405                 addInferredTypings(packageNames, "    Found package names");
141406             }
141407         }
141408         JsTyping.discoverTypings = discoverTypings;
141409         var NameValidationResult;
141410         (function (NameValidationResult) {
141411             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
141412             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
141413             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
141414             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
141415             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
141416             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
141417         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
141418         var maxPackageNameLength = 214;
141419         /**
141420          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
141421          */
141422         function validatePackageName(packageName) {
141423             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
141424         }
141425         JsTyping.validatePackageName = validatePackageName;
141426         function validatePackageNameWorker(packageName, supportScopedPackage) {
141427             if (!packageName) {
141428                 return 1 /* EmptyName */;
141429             }
141430             if (packageName.length > maxPackageNameLength) {
141431                 return 2 /* NameTooLong */;
141432             }
141433             if (packageName.charCodeAt(0) === 46 /* dot */) {
141434                 return 3 /* NameStartsWithDot */;
141435             }
141436             if (packageName.charCodeAt(0) === 95 /* _ */) {
141437                 return 4 /* NameStartsWithUnderscore */;
141438             }
141439             // check if name is scope package like: starts with @ and has one '/' in the middle
141440             // scoped packages are not currently supported
141441             if (supportScopedPackage) {
141442                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
141443                 if (matches) {
141444                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
141445                     if (scopeResult !== 0 /* Ok */) {
141446                         return { name: matches[1], isScopeName: true, result: scopeResult };
141447                     }
141448                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
141449                     if (packageResult !== 0 /* Ok */) {
141450                         return { name: matches[2], isScopeName: false, result: packageResult };
141451                     }
141452                     return 0 /* Ok */;
141453                 }
141454             }
141455             if (encodeURIComponent(packageName) !== packageName) {
141456                 return 5 /* NameContainsNonURISafeCharacters */;
141457             }
141458             return 0 /* Ok */;
141459         }
141460         function renderPackageNameValidationFailure(result, typing) {
141461             return typeof result === "object" ?
141462                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
141463                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
141464         }
141465         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
141466         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
141467             var kind = isScopeName ? "Scope" : "Package";
141468             switch (result) {
141469                 case 1 /* EmptyName */:
141470                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
141471                 case 2 /* NameTooLong */:
141472                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
141473                 case 3 /* NameStartsWithDot */:
141474                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
141475                 case 4 /* NameStartsWithUnderscore */:
141476                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
141477                 case 5 /* NameContainsNonURISafeCharacters */:
141478                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
141479                 case 0 /* Ok */:
141480                     return ts.Debug.fail(); // Shouldn't have called this.
141481                 default:
141482                     throw ts.Debug.assertNever(result);
141483             }
141484         }
141485     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
141486 })(ts || (ts = {}));
141487 var ts;
141488 (function (ts) {
141489     var server;
141490     (function (server) {
141491         var LogLevel;
141492         (function (LogLevel) {
141493             LogLevel[LogLevel["terse"] = 0] = "terse";
141494             LogLevel[LogLevel["normal"] = 1] = "normal";
141495             LogLevel[LogLevel["requestTime"] = 2] = "requestTime";
141496             LogLevel[LogLevel["verbose"] = 3] = "verbose";
141497         })(LogLevel = server.LogLevel || (server.LogLevel = {}));
141498         server.emptyArray = createSortedArray();
141499         // TODO: Use a const enum (https://github.com/Microsoft/TypeScript/issues/16804)
141500         var Msg;
141501         (function (Msg) {
141502             Msg["Err"] = "Err";
141503             Msg["Info"] = "Info";
141504             Msg["Perf"] = "Perf";
141505         })(Msg = server.Msg || (server.Msg = {}));
141506         function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) {
141507             return {
141508                 projectName: project.getProjectName(),
141509                 fileNames: project.getFileNames(/*excludeFilesFromExternalLibraries*/ true, /*excludeConfigFiles*/ true).concat(project.getExcludedFiles()),
141510                 compilerOptions: project.getCompilationSettings(),
141511                 watchOptions: project.projectService.getWatchOptions(project),
141512                 typeAcquisition: typeAcquisition,
141513                 unresolvedImports: unresolvedImports,
141514                 projectRootPath: project.getCurrentDirectory(),
141515                 cachePath: cachePath,
141516                 kind: "discover"
141517             };
141518         }
141519         server.createInstallTypingsRequest = createInstallTypingsRequest;
141520         var Errors;
141521         (function (Errors) {
141522             function ThrowNoProject() {
141523                 throw new Error("No Project.");
141524             }
141525             Errors.ThrowNoProject = ThrowNoProject;
141526             function ThrowProjectLanguageServiceDisabled() {
141527                 throw new Error("The project's language service is disabled.");
141528             }
141529             Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled;
141530             function ThrowProjectDoesNotContainDocument(fileName, project) {
141531                 throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'");
141532             }
141533             Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument;
141534         })(Errors = server.Errors || (server.Errors = {}));
141535         function toNormalizedPath(fileName) {
141536             return ts.normalizePath(fileName);
141537         }
141538         server.toNormalizedPath = toNormalizedPath;
141539         function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) {
141540             var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory);
141541             return getCanonicalFileName(f);
141542         }
141543         server.normalizedPathToPath = normalizedPathToPath;
141544         function asNormalizedPath(fileName) {
141545             return fileName;
141546         }
141547         server.asNormalizedPath = asNormalizedPath;
141548         function createNormalizedPathMap() {
141549             var map = ts.createMap();
141550             return {
141551                 get: function (path) {
141552                     return map.get(path);
141553                 },
141554                 set: function (path, value) {
141555                     map.set(path, value);
141556                 },
141557                 contains: function (path) {
141558                     return map.has(path);
141559                 },
141560                 remove: function (path) {
141561                     map.delete(path);
141562                 }
141563             };
141564         }
141565         server.createNormalizedPathMap = createNormalizedPathMap;
141566         function isInferredProjectName(name) {
141567             // POSIX defines /dev/null as a device - there should be no file with this prefix
141568             return /dev\/null\/inferredProject\d+\*/.test(name);
141569         }
141570         server.isInferredProjectName = isInferredProjectName;
141571         function makeInferredProjectName(counter) {
141572             return "/dev/null/inferredProject" + counter + "*";
141573         }
141574         server.makeInferredProjectName = makeInferredProjectName;
141575         function createSortedArray() {
141576             return []; // TODO: GH#19873
141577         }
141578         server.createSortedArray = createSortedArray;
141579     })(server = ts.server || (ts.server = {}));
141580 })(ts || (ts = {}));
141581 /* @internal */
141582 var ts;
141583 (function (ts) {
141584     var server;
141585     (function (server) {
141586         var ThrottledOperations = /** @class */ (function () {
141587             function ThrottledOperations(host, logger) {
141588                 this.host = host;
141589                 this.pendingTimeouts = ts.createMap();
141590                 this.logger = logger.hasLevel(server.LogLevel.verbose) ? logger : undefined;
141591             }
141592             /**
141593              * Wait `number` milliseconds and then invoke `cb`.  If, while waiting, schedule
141594              * is called again with the same `operationId`, cancel this operation in favor
141595              * of the new one.  (Note that the amount of time the canceled operation had been
141596              * waiting does not affect the amount of time that the new operation waits.)
141597              */
141598             ThrottledOperations.prototype.schedule = function (operationId, delay, cb) {
141599                 var pendingTimeout = this.pendingTimeouts.get(operationId);
141600                 if (pendingTimeout) {
141601                     // another operation was already scheduled for this id - cancel it
141602                     this.host.clearTimeout(pendingTimeout);
141603                 }
141604                 // schedule new operation, pass arguments
141605                 this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb));
141606                 if (this.logger) {
141607                     this.logger.info("Scheduled: " + operationId + (pendingTimeout ? ", Cancelled earlier one" : ""));
141608                 }
141609             };
141610             ThrottledOperations.run = function (self, operationId, cb) {
141611                 ts.perfLogger.logStartScheduledOperation(operationId);
141612                 self.pendingTimeouts.delete(operationId);
141613                 if (self.logger) {
141614                     self.logger.info("Running: " + operationId);
141615                 }
141616                 cb();
141617                 ts.perfLogger.logStopScheduledOperation();
141618             };
141619             return ThrottledOperations;
141620         }());
141621         server.ThrottledOperations = ThrottledOperations;
141622         var GcTimer = /** @class */ (function () {
141623             function GcTimer(host, delay, logger) {
141624                 this.host = host;
141625                 this.delay = delay;
141626                 this.logger = logger;
141627             }
141628             GcTimer.prototype.scheduleCollect = function () {
141629                 if (!this.host.gc || this.timerId !== undefined) {
141630                     // no global.gc or collection was already scheduled - skip this request
141631                     return;
141632                 }
141633                 this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this);
141634             };
141635             GcTimer.run = function (self) {
141636                 self.timerId = undefined;
141637                 ts.perfLogger.logStartScheduledOperation("GC collect");
141638                 var log = self.logger.hasLevel(server.LogLevel.requestTime);
141639                 var before = log && self.host.getMemoryUsage(); // TODO: GH#18217
141640                 self.host.gc(); // TODO: GH#18217
141641                 if (log) {
141642                     var after = self.host.getMemoryUsage(); // TODO: GH#18217
141643                     self.logger.perftrc("GC::before " + before + ", after " + after);
141644                 }
141645                 ts.perfLogger.logStopScheduledOperation();
141646             };
141647             return GcTimer;
141648         }());
141649         server.GcTimer = GcTimer;
141650         function getBaseConfigFileName(configFilePath) {
141651             var base = ts.getBaseFileName(configFilePath);
141652             return base === "tsconfig.json" || base === "jsconfig.json" ? base : undefined;
141653         }
141654         server.getBaseConfigFileName = getBaseConfigFileName;
141655         function removeSorted(array, remove, compare) {
141656             if (!array || array.length === 0) {
141657                 return;
141658             }
141659             if (array[0] === remove) {
141660                 array.splice(0, 1);
141661                 return;
141662             }
141663             var removeIndex = ts.binarySearch(array, remove, ts.identity, compare);
141664             if (removeIndex >= 0) {
141665                 array.splice(removeIndex, 1);
141666             }
141667         }
141668         server.removeSorted = removeSorted;
141669         var indentStr = "\n    ";
141670         function indent(str) {
141671             return indentStr + str.replace(/\n/g, indentStr);
141672         }
141673         server.indent = indent;
141674         /** Put stringified JSON on the next line, indented. */
141675         function stringifyIndented(json) {
141676             return indentStr + JSON.stringify(json);
141677         }
141678         server.stringifyIndented = stringifyIndented;
141679     })(server = ts.server || (ts.server = {}));
141680 })(ts || (ts = {}));
141681 /* @internal */
141682 var ts;
141683 (function (ts) {
141684     ts.WatchType.ClosedScriptInfo = "Closed Script info";
141685     ts.WatchType.ConfigFileForInferredRoot = "Config file for the inferred project root";
141686     ts.WatchType.NodeModulesForClosedScriptInfo = "node_modules for closed script infos in them";
141687     ts.WatchType.MissingSourceMapFile = "Missing source map file";
141688     ts.WatchType.NoopConfigFileForInferredRoot = "Noop Config file for the inferred project root";
141689     ts.WatchType.MissingGeneratedFile = "Missing generated file";
141690     ts.WatchType.PackageJsonFile = "package.json file for import suggestions";
141691 })(ts || (ts = {}));
141692 /* eslint-disable @typescript-eslint/no-unnecessary-qualifier */
141693 /**
141694  * Declaration module describing the TypeScript Server protocol
141695  */
141696 var ts;
141697 (function (ts) {
141698     var server;
141699     (function (server) {
141700         var protocol;
141701         (function (protocol) {
141702             // NOTE: If updating this, be sure to also update `allCommandNames` in `testRunner/unittests/tsserver/session.ts`.
141703             var CommandTypes;
141704             (function (CommandTypes) {
141705                 CommandTypes["JsxClosingTag"] = "jsxClosingTag";
141706                 CommandTypes["Brace"] = "brace";
141707                 /* @internal */
141708                 CommandTypes["BraceFull"] = "brace-full";
141709                 CommandTypes["BraceCompletion"] = "braceCompletion";
141710                 CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment";
141711                 CommandTypes["Change"] = "change";
141712                 CommandTypes["Close"] = "close";
141713                 /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */
141714                 CommandTypes["Completions"] = "completions";
141715                 CommandTypes["CompletionInfo"] = "completionInfo";
141716                 /* @internal */
141717                 CommandTypes["CompletionsFull"] = "completions-full";
141718                 CommandTypes["CompletionDetails"] = "completionEntryDetails";
141719                 /* @internal */
141720                 CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full";
141721                 CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList";
141722                 CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile";
141723                 CommandTypes["Configure"] = "configure";
141724                 CommandTypes["Definition"] = "definition";
141725                 /* @internal */
141726                 CommandTypes["DefinitionFull"] = "definition-full";
141727                 CommandTypes["DefinitionAndBoundSpan"] = "definitionAndBoundSpan";
141728                 /* @internal */
141729                 CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full";
141730                 CommandTypes["Implementation"] = "implementation";
141731                 /* @internal */
141732                 CommandTypes["ImplementationFull"] = "implementation-full";
141733                 /* @internal */
141734                 CommandTypes["EmitOutput"] = "emit-output";
141735                 CommandTypes["Exit"] = "exit";
141736                 CommandTypes["Format"] = "format";
141737                 CommandTypes["Formatonkey"] = "formatonkey";
141738                 /* @internal */
141739                 CommandTypes["FormatFull"] = "format-full";
141740                 /* @internal */
141741                 CommandTypes["FormatonkeyFull"] = "formatonkey-full";
141742                 /* @internal */
141743                 CommandTypes["FormatRangeFull"] = "formatRange-full";
141744                 CommandTypes["Geterr"] = "geterr";
141745                 CommandTypes["GeterrForProject"] = "geterrForProject";
141746                 CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync";
141747                 CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync";
141748                 CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync";
141749                 CommandTypes["NavBar"] = "navbar";
141750                 /* @internal */
141751                 CommandTypes["NavBarFull"] = "navbar-full";
141752                 CommandTypes["Navto"] = "navto";
141753                 /* @internal */
141754                 CommandTypes["NavtoFull"] = "navto-full";
141755                 CommandTypes["NavTree"] = "navtree";
141756                 CommandTypes["NavTreeFull"] = "navtree-full";
141757                 /** @deprecated */
141758                 CommandTypes["Occurrences"] = "occurrences";
141759                 CommandTypes["DocumentHighlights"] = "documentHighlights";
141760                 /* @internal */
141761                 CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full";
141762                 CommandTypes["Open"] = "open";
141763                 CommandTypes["Quickinfo"] = "quickinfo";
141764                 /* @internal */
141765                 CommandTypes["QuickinfoFull"] = "quickinfo-full";
141766                 CommandTypes["References"] = "references";
141767                 /* @internal */
141768                 CommandTypes["ReferencesFull"] = "references-full";
141769                 CommandTypes["Reload"] = "reload";
141770                 CommandTypes["Rename"] = "rename";
141771                 /* @internal */
141772                 CommandTypes["RenameInfoFull"] = "rename-full";
141773                 /* @internal */
141774                 CommandTypes["RenameLocationsFull"] = "renameLocations-full";
141775                 CommandTypes["Saveto"] = "saveto";
141776                 CommandTypes["SignatureHelp"] = "signatureHelp";
141777                 /* @internal */
141778                 CommandTypes["SignatureHelpFull"] = "signatureHelp-full";
141779                 CommandTypes["Status"] = "status";
141780                 CommandTypes["TypeDefinition"] = "typeDefinition";
141781                 CommandTypes["ProjectInfo"] = "projectInfo";
141782                 CommandTypes["ReloadProjects"] = "reloadProjects";
141783                 CommandTypes["Unknown"] = "unknown";
141784                 CommandTypes["OpenExternalProject"] = "openExternalProject";
141785                 CommandTypes["OpenExternalProjects"] = "openExternalProjects";
141786                 CommandTypes["CloseExternalProject"] = "closeExternalProject";
141787                 /* @internal */
141788                 CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList";
141789                 /* @internal */
141790                 CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles";
141791                 CommandTypes["UpdateOpen"] = "updateOpen";
141792                 /* @internal */
141793                 CommandTypes["EncodedSyntacticClassificationsFull"] = "encodedSyntacticClassifications-full";
141794                 /* @internal */
141795                 CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full";
141796                 /* @internal */
141797                 CommandTypes["Cleanup"] = "cleanup";
141798                 CommandTypes["GetOutliningSpans"] = "getOutliningSpans";
141799                 /* @internal */
141800                 CommandTypes["GetOutliningSpansFull"] = "outliningSpans";
141801                 CommandTypes["TodoComments"] = "todoComments";
141802                 CommandTypes["Indentation"] = "indentation";
141803                 CommandTypes["DocCommentTemplate"] = "docCommentTemplate";
141804                 /* @internal */
141805                 CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full";
141806                 /* @internal */
141807                 CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan";
141808                 /* @internal */
141809                 CommandTypes["BreakpointStatement"] = "breakpointStatement";
141810                 CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects";
141811                 CommandTypes["GetCodeFixes"] = "getCodeFixes";
141812                 /* @internal */
141813                 CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full";
141814                 CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix";
141815                 /* @internal */
141816                 CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full";
141817                 CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand";
141818                 CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes";
141819                 CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors";
141820                 CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor";
141821                 /* @internal */
141822                 CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full";
141823                 CommandTypes["OrganizeImports"] = "organizeImports";
141824                 /* @internal */
141825                 CommandTypes["OrganizeImportsFull"] = "organizeImports-full";
141826                 CommandTypes["GetEditsForFileRename"] = "getEditsForFileRename";
141827                 /* @internal */
141828                 CommandTypes["GetEditsForFileRenameFull"] = "getEditsForFileRename-full";
141829                 CommandTypes["ConfigurePlugin"] = "configurePlugin";
141830                 CommandTypes["SelectionRange"] = "selectionRange";
141831                 /* @internal */
141832                 CommandTypes["SelectionRangeFull"] = "selectionRange-full";
141833                 CommandTypes["PrepareCallHierarchy"] = "prepareCallHierarchy";
141834                 CommandTypes["ProvideCallHierarchyIncomingCalls"] = "provideCallHierarchyIncomingCalls";
141835                 CommandTypes["ProvideCallHierarchyOutgoingCalls"] = "provideCallHierarchyOutgoingCalls";
141836                 // NOTE: If updating this, be sure to also update `allCommandNames` in `testRunner/unittests/tsserver/session.ts`.
141837             })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {}));
141838             var WatchFileKind;
141839             (function (WatchFileKind) {
141840                 WatchFileKind["FixedPollingInterval"] = "FixedPollingInterval";
141841                 WatchFileKind["PriorityPollingInterval"] = "PriorityPollingInterval";
141842                 WatchFileKind["DynamicPriorityPolling"] = "DynamicPriorityPolling";
141843                 WatchFileKind["UseFsEvents"] = "UseFsEvents";
141844                 WatchFileKind["UseFsEventsOnParentDirectory"] = "UseFsEventsOnParentDirectory";
141845             })(WatchFileKind = protocol.WatchFileKind || (protocol.WatchFileKind = {}));
141846             var WatchDirectoryKind;
141847             (function (WatchDirectoryKind) {
141848                 WatchDirectoryKind["UseFsEvents"] = "UseFsEvents";
141849                 WatchDirectoryKind["FixedPollingInterval"] = "FixedPollingInterval";
141850                 WatchDirectoryKind["DynamicPriorityPolling"] = "DynamicPriorityPolling";
141851             })(WatchDirectoryKind = protocol.WatchDirectoryKind || (protocol.WatchDirectoryKind = {}));
141852             var PollingWatchKind;
141853             (function (PollingWatchKind) {
141854                 PollingWatchKind["FixedInterval"] = "FixedInterval";
141855                 PollingWatchKind["PriorityInterval"] = "PriorityInterval";
141856                 PollingWatchKind["DynamicPriority"] = "DynamicPriority";
141857             })(PollingWatchKind = protocol.PollingWatchKind || (protocol.PollingWatchKind = {}));
141858             var IndentStyle;
141859             (function (IndentStyle) {
141860                 IndentStyle["None"] = "None";
141861                 IndentStyle["Block"] = "Block";
141862                 IndentStyle["Smart"] = "Smart";
141863             })(IndentStyle = protocol.IndentStyle || (protocol.IndentStyle = {}));
141864             var SemicolonPreference;
141865             (function (SemicolonPreference) {
141866                 SemicolonPreference["Ignore"] = "ignore";
141867                 SemicolonPreference["Insert"] = "insert";
141868                 SemicolonPreference["Remove"] = "remove";
141869             })(SemicolonPreference = protocol.SemicolonPreference || (protocol.SemicolonPreference = {}));
141870             var JsxEmit;
141871             (function (JsxEmit) {
141872                 JsxEmit["None"] = "None";
141873                 JsxEmit["Preserve"] = "Preserve";
141874                 JsxEmit["ReactNative"] = "ReactNative";
141875                 JsxEmit["React"] = "React";
141876             })(JsxEmit = protocol.JsxEmit || (protocol.JsxEmit = {}));
141877             var ModuleKind;
141878             (function (ModuleKind) {
141879                 ModuleKind["None"] = "None";
141880                 ModuleKind["CommonJS"] = "CommonJS";
141881                 ModuleKind["AMD"] = "AMD";
141882                 ModuleKind["UMD"] = "UMD";
141883                 ModuleKind["System"] = "System";
141884                 ModuleKind["ES6"] = "ES6";
141885                 ModuleKind["ES2015"] = "ES2015";
141886                 ModuleKind["ESNext"] = "ESNext";
141887             })(ModuleKind = protocol.ModuleKind || (protocol.ModuleKind = {}));
141888             var ModuleResolutionKind;
141889             (function (ModuleResolutionKind) {
141890                 ModuleResolutionKind["Classic"] = "Classic";
141891                 ModuleResolutionKind["Node"] = "Node";
141892             })(ModuleResolutionKind = protocol.ModuleResolutionKind || (protocol.ModuleResolutionKind = {}));
141893             var NewLineKind;
141894             (function (NewLineKind) {
141895                 NewLineKind["Crlf"] = "Crlf";
141896                 NewLineKind["Lf"] = "Lf";
141897             })(NewLineKind = protocol.NewLineKind || (protocol.NewLineKind = {}));
141898             var ScriptTarget;
141899             (function (ScriptTarget) {
141900                 ScriptTarget["ES3"] = "ES3";
141901                 ScriptTarget["ES5"] = "ES5";
141902                 ScriptTarget["ES6"] = "ES6";
141903                 ScriptTarget["ES2015"] = "ES2015";
141904                 ScriptTarget["ES2016"] = "ES2016";
141905                 ScriptTarget["ES2017"] = "ES2017";
141906                 ScriptTarget["ES2018"] = "ES2018";
141907                 ScriptTarget["ES2019"] = "ES2019";
141908                 ScriptTarget["ES2020"] = "ES2020";
141909                 ScriptTarget["ESNext"] = "ESNext";
141910             })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {}));
141911         })(protocol = server.protocol || (server.protocol = {}));
141912     })(server = ts.server || (ts.server = {}));
141913 })(ts || (ts = {}));
141914 var ts;
141915 (function (ts) {
141916     var server;
141917     (function (server) {
141918         /* @internal */
141919         var TextStorage = /** @class */ (function () {
141920             function TextStorage(host, info, initialVersion) {
141921                 this.host = host;
141922                 this.info = info;
141923                 /**
141924                  * True if the text is for the file thats open in the editor
141925                  */
141926                 this.isOpen = false;
141927                 /**
141928                  * True if the text present is the text from the file on the disk
141929                  */
141930                 this.ownFileText = false;
141931                 /**
141932                  * True when reloading contents of file from the disk is pending
141933                  */
141934                 this.pendingReloadFromDisk = false;
141935                 this.version = initialVersion || { svc: 0, text: 0 };
141936             }
141937             TextStorage.prototype.getVersion = function () {
141938                 return this.svc
141939                     ? "SVC-" + this.version.svc + "-" + this.svc.getSnapshotVersion()
141940                     : "Text-" + this.version.text;
141941             };
141942             TextStorage.prototype.hasScriptVersionCache_TestOnly = function () {
141943                 return this.svc !== undefined;
141944             };
141945             TextStorage.prototype.useScriptVersionCache_TestOnly = function () {
141946                 this.switchToScriptVersionCache();
141947             };
141948             TextStorage.prototype.resetSourceMapInfo = function () {
141949                 this.info.sourceFileLike = undefined;
141950                 this.info.closeSourceMapFileWatcher();
141951                 this.info.sourceMapFilePath = undefined;
141952                 this.info.declarationInfoPath = undefined;
141953                 this.info.sourceInfos = undefined;
141954                 this.info.documentPositionMapper = undefined;
141955             };
141956             /** Public for testing */
141957             TextStorage.prototype.useText = function (newText) {
141958                 this.svc = undefined;
141959                 this.text = newText;
141960                 this.lineMap = undefined;
141961                 this.fileSize = undefined;
141962                 this.resetSourceMapInfo();
141963                 this.version.text++;
141964             };
141965             TextStorage.prototype.edit = function (start, end, newText) {
141966                 this.switchToScriptVersionCache().edit(start, end - start, newText);
141967                 this.ownFileText = false;
141968                 this.text = undefined;
141969                 this.lineMap = undefined;
141970                 this.fileSize = undefined;
141971                 this.resetSourceMapInfo();
141972             };
141973             /**
141974              * Set the contents as newText
141975              * returns true if text changed
141976              */
141977             TextStorage.prototype.reload = function (newText) {
141978                 ts.Debug.assert(newText !== undefined);
141979                 // Reload always has fresh content
141980                 this.pendingReloadFromDisk = false;
141981                 // If text changed set the text
141982                 // This also ensures that if we had switched to version cache,
141983                 // we are switching back to text.
141984                 // The change to version cache will happen when needed
141985                 // Thus avoiding the computation if there are no changes
141986                 if (this.text !== newText) {
141987                     this.useText(newText);
141988                     // We cant guarantee new text is own file text
141989                     this.ownFileText = false;
141990                     return true;
141991                 }
141992                 return false;
141993             };
141994             /**
141995              * Reads the contents from tempFile(if supplied) or own file and sets it as contents
141996              * returns true if text changed
141997              */
141998             TextStorage.prototype.reloadWithFileText = function (tempFileName) {
141999                 var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize;
142000                 var reloaded = this.reload(newText);
142001                 this.fileSize = fileSize; // NB: after reload since reload clears it
142002                 this.ownFileText = !tempFileName || tempFileName === this.info.fileName;
142003                 return reloaded;
142004             };
142005             /**
142006              * Reloads the contents from the file if there is no pending reload from disk or the contents of file are same as file text
142007              * returns true if text changed
142008              */
142009             TextStorage.prototype.reloadFromDisk = function () {
142010                 if (!this.pendingReloadFromDisk && !this.ownFileText) {
142011                     return this.reloadWithFileText();
142012                 }
142013                 return false;
142014             };
142015             TextStorage.prototype.delayReloadFromFileIntoText = function () {
142016                 this.pendingReloadFromDisk = true;
142017             };
142018             /**
142019              * For telemetry purposes, we would like to be able to report the size of the file.
142020              * However, we do not want telemetry to require extra file I/O so we report a size
142021              * that may be stale (e.g. may not reflect change made on disk since the last reload).
142022              * NB: Will read from disk if the file contents have never been loaded because
142023              * telemetry falsely indicating size 0 would be counter-productive.
142024              */
142025             TextStorage.prototype.getTelemetryFileSize = function () {
142026                 return !!this.fileSize
142027                     ? this.fileSize
142028                     : !!this.text // Check text before svc because its length is cheaper
142029                         ? this.text.length // Could be wrong if this.pendingReloadFromDisk
142030                         : !!this.svc
142031                             ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk
142032                             : this.getSnapshot().getLength(); // Should be strictly correct
142033             };
142034             TextStorage.prototype.getSnapshot = function () {
142035                 return this.useScriptVersionCacheIfValidOrOpen()
142036                     ? this.svc.getSnapshot()
142037                     : ts.ScriptSnapshot.fromString(this.getOrLoadText());
142038             };
142039             TextStorage.prototype.getAbsolutePositionAndLineText = function (line) {
142040                 return this.switchToScriptVersionCache().getAbsolutePositionAndLineText(line);
142041             };
142042             /**
142043              *  @param line 0 based index
142044              */
142045             TextStorage.prototype.lineToTextSpan = function (line) {
142046                 if (!this.useScriptVersionCacheIfValidOrOpen()) {
142047                     var lineMap = this.getLineMap();
142048                     var start = lineMap[line]; // -1 since line is 1-based
142049                     var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length;
142050                     return ts.createTextSpanFromBounds(start, end);
142051                 }
142052                 return this.svc.lineToTextSpan(line);
142053             };
142054             /**
142055              * @param line 1 based index
142056              * @param offset 1 based index
142057              */
142058             TextStorage.prototype.lineOffsetToPosition = function (line, offset, allowEdits) {
142059                 if (!this.useScriptVersionCacheIfValidOrOpen()) {
142060                     return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits);
142061                 }
142062                 // TODO: assert this offset is actually on the line
142063                 return this.svc.lineOffsetToPosition(line, offset);
142064             };
142065             TextStorage.prototype.positionToLineOffset = function (position) {
142066                 if (!this.useScriptVersionCacheIfValidOrOpen()) {
142067                     var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character;
142068                     return { line: line + 1, offset: character + 1 };
142069                 }
142070                 return this.svc.positionToLineOffset(position);
142071             };
142072             TextStorage.prototype.getFileTextAndSize = function (tempFileName) {
142073                 var _this = this;
142074                 var text;
142075                 var fileName = tempFileName || this.info.fileName;
142076                 var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; };
142077                 // Only non typescript files have size limitation
142078                 if (!ts.hasTSFileExtension(this.info.fileName)) {
142079                     var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length;
142080                     if (fileSize > server.maxFileSize) {
142081                         ts.Debug.assert(!!this.info.containingProjects.length);
142082                         var service = this.info.containingProjects[0].projectService;
142083                         service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize);
142084                         this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize);
142085                         return { text: "", fileSize: fileSize };
142086                     }
142087                 }
142088                 return { text: getText() };
142089             };
142090             TextStorage.prototype.switchToScriptVersionCache = function () {
142091                 if (!this.svc || this.pendingReloadFromDisk) {
142092                     this.svc = server.ScriptVersionCache.fromString(this.getOrLoadText());
142093                     this.version.svc++;
142094                 }
142095                 return this.svc;
142096             };
142097             TextStorage.prototype.useScriptVersionCacheIfValidOrOpen = function () {
142098                 // If this is open script, use the cache
142099                 if (this.isOpen) {
142100                     return this.switchToScriptVersionCache();
142101                 }
142102                 // If there is pending reload from the disk then, reload the text
142103                 if (this.pendingReloadFromDisk) {
142104                     this.reloadWithFileText();
142105                 }
142106                 // At this point if svc is present its valid
142107                 return this.svc;
142108             };
142109             TextStorage.prototype.getOrLoadText = function () {
142110                 if (this.text === undefined || this.pendingReloadFromDisk) {
142111                     ts.Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk");
142112                     this.reloadWithFileText();
142113                 }
142114                 return this.text;
142115             };
142116             TextStorage.prototype.getLineMap = function () {
142117                 ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set");
142118                 return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText()));
142119             };
142120             TextStorage.prototype.getLineInfo = function () {
142121                 var _this = this;
142122                 if (this.svc) {
142123                     return {
142124                         getLineCount: function () { return _this.svc.getLineCount(); },
142125                         getLineText: function (line) { return _this.svc.getAbsolutePositionAndLineText(line + 1).lineText; }
142126                     };
142127                 }
142128                 var lineMap = this.getLineMap();
142129                 return ts.getLineInfo(this.text, lineMap);
142130             };
142131             return TextStorage;
142132         }());
142133         server.TextStorage = TextStorage;
142134         /*@internal*/
142135         function isDynamicFileName(fileName) {
142136             return fileName[0] === "^" ||
142137                 ((ts.stringContains(fileName, "walkThroughSnippet:/") || ts.stringContains(fileName, "untitled:/")) &&
142138                     ts.getBaseFileName(fileName)[0] === "^") ||
142139                 (ts.stringContains(fileName, ":^") && !ts.stringContains(fileName, ts.directorySeparator));
142140         }
142141         server.isDynamicFileName = isDynamicFileName;
142142         var ScriptInfo = /** @class */ (function () {
142143             function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path, initialVersion) {
142144                 this.host = host;
142145                 this.fileName = fileName;
142146                 this.scriptKind = scriptKind;
142147                 this.hasMixedContent = hasMixedContent;
142148                 this.path = path;
142149                 /**
142150                  * All projects that include this file
142151                  */
142152                 this.containingProjects = [];
142153                 this.isDynamic = isDynamicFileName(fileName);
142154                 this.textStorage = new TextStorage(host, this, initialVersion);
142155                 if (hasMixedContent || this.isDynamic) {
142156                     this.textStorage.reload("");
142157                     this.realpath = this.path;
142158                 }
142159                 this.scriptKind = scriptKind
142160                     ? scriptKind
142161                     : ts.getScriptKindFromFileName(fileName);
142162             }
142163             /*@internal*/
142164             ScriptInfo.prototype.getVersion = function () {
142165                 return this.textStorage.version;
142166             };
142167             /*@internal*/
142168             ScriptInfo.prototype.getTelemetryFileSize = function () {
142169                 return this.textStorage.getTelemetryFileSize();
142170             };
142171             /*@internal*/
142172             ScriptInfo.prototype.isDynamicOrHasMixedContent = function () {
142173                 return this.hasMixedContent || this.isDynamic;
142174             };
142175             ScriptInfo.prototype.isScriptOpen = function () {
142176                 return this.textStorage.isOpen;
142177             };
142178             ScriptInfo.prototype.open = function (newText) {
142179                 this.textStorage.isOpen = true;
142180                 if (newText !== undefined &&
142181                     this.textStorage.reload(newText)) {
142182                     // reload new contents only if the existing contents changed
142183                     this.markContainingProjectsAsDirty();
142184                 }
142185             };
142186             ScriptInfo.prototype.close = function (fileExists) {
142187                 if (fileExists === void 0) { fileExists = true; }
142188                 this.textStorage.isOpen = false;
142189                 if (this.isDynamicOrHasMixedContent() || !fileExists) {
142190                     if (this.textStorage.reload("")) {
142191                         this.markContainingProjectsAsDirty();
142192                     }
142193                 }
142194                 else if (this.textStorage.reloadFromDisk()) {
142195                     this.markContainingProjectsAsDirty();
142196                 }
142197             };
142198             ScriptInfo.prototype.getSnapshot = function () {
142199                 return this.textStorage.getSnapshot();
142200             };
142201             ScriptInfo.prototype.ensureRealPath = function () {
142202                 if (this.realpath === undefined) {
142203                     // Default is just the path
142204                     this.realpath = this.path;
142205                     if (this.host.realpath) {
142206                         ts.Debug.assert(!!this.containingProjects.length);
142207                         var project = this.containingProjects[0];
142208                         var realpath = this.host.realpath(this.path);
142209                         if (realpath) {
142210                             this.realpath = project.toPath(realpath);
142211                             // If it is different from this.path, add to the map
142212                             if (this.realpath !== this.path) {
142213                                 project.projectService.realpathToScriptInfos.add(this.realpath, this); // TODO: GH#18217
142214                             }
142215                         }
142216                     }
142217                 }
142218             };
142219             /*@internal*/
142220             ScriptInfo.prototype.getRealpathIfDifferent = function () {
142221                 return this.realpath && this.realpath !== this.path ? this.realpath : undefined;
142222             };
142223             ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatSettings; };
142224             ScriptInfo.prototype.getPreferences = function () { return this.preferences; };
142225             ScriptInfo.prototype.attachToProject = function (project) {
142226                 var isNew = !this.isAttached(project);
142227                 if (isNew) {
142228                     this.containingProjects.push(project);
142229                     project.onFileAddedOrRemoved();
142230                     if (!project.getCompilerOptions().preserveSymlinks) {
142231                         this.ensureRealPath();
142232                     }
142233                 }
142234                 return isNew;
142235             };
142236             ScriptInfo.prototype.isAttached = function (project) {
142237                 // unrolled for common cases
142238                 switch (this.containingProjects.length) {
142239                     case 0: return false;
142240                     case 1: return this.containingProjects[0] === project;
142241                     case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project;
142242                     default: return ts.contains(this.containingProjects, project);
142243                 }
142244             };
142245             ScriptInfo.prototype.detachFromProject = function (project) {
142246                 // unrolled for common cases
142247                 switch (this.containingProjects.length) {
142248                     case 0:
142249                         return;
142250                     case 1:
142251                         if (this.containingProjects[0] === project) {
142252                             project.onFileAddedOrRemoved();
142253                             this.containingProjects.pop();
142254                         }
142255                         break;
142256                     case 2:
142257                         if (this.containingProjects[0] === project) {
142258                             project.onFileAddedOrRemoved();
142259                             this.containingProjects[0] = this.containingProjects.pop();
142260                         }
142261                         else if (this.containingProjects[1] === project) {
142262                             project.onFileAddedOrRemoved();
142263                             this.containingProjects.pop();
142264                         }
142265                         break;
142266                     default:
142267                         if (ts.unorderedRemoveItem(this.containingProjects, project)) {
142268                             project.onFileAddedOrRemoved();
142269                         }
142270                         break;
142271                 }
142272             };
142273             ScriptInfo.prototype.detachAllProjects = function () {
142274                 for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
142275                     var p = _a[_i];
142276                     if (server.isConfiguredProject(p)) {
142277                         p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted);
142278                     }
142279                     var existingRoot = p.getRootFilesMap().get(this.path);
142280                     // detach is unnecessary since we'll clean the list of containing projects anyways
142281                     p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false);
142282                     // If the info was for the external or configured project's root,
142283                     // add missing file as the root
142284                     if (existingRoot && !server.isInferredProject(p)) {
142285                         p.addMissingFileRoot(existingRoot.fileName);
142286                     }
142287                 }
142288                 ts.clear(this.containingProjects);
142289             };
142290             ScriptInfo.prototype.getDefaultProject = function () {
142291                 switch (this.containingProjects.length) {
142292                     case 0:
142293                         return server.Errors.ThrowNoProject();
142294                     case 1:
142295                         return this.containingProjects[0];
142296                     default:
142297                         // If this file belongs to multiple projects, below is the order in which default project is used
142298                         // - for open script info, its default configured project during opening is default if info is part of it
142299                         // - first configured project of which script info is not a source of project reference redirect
142300                         // - first configured project
142301                         // - first external project
142302                         // - first inferred project
142303                         var firstExternalProject = void 0;
142304                         var firstConfiguredProject = void 0;
142305                         var firstNonSourceOfProjectReferenceRedirect = void 0;
142306                         var defaultConfiguredProject = void 0;
142307                         for (var index = 0; index < this.containingProjects.length; index++) {
142308                             var project = this.containingProjects[index];
142309                             if (server.isConfiguredProject(project)) {
142310                                 if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) {
142311                                     // If we havent found default configuredProject and
142312                                     // its not the last one, find it and use that one if there
142313                                     if (defaultConfiguredProject === undefined &&
142314                                         index !== this.containingProjects.length - 1) {
142315                                         defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false;
142316                                     }
142317                                     if (defaultConfiguredProject === project)
142318                                         return project;
142319                                     if (!firstNonSourceOfProjectReferenceRedirect)
142320                                         firstNonSourceOfProjectReferenceRedirect = project;
142321                                 }
142322                                 if (!firstConfiguredProject)
142323                                     firstConfiguredProject = project;
142324                             }
142325                             else if (!firstExternalProject && server.isExternalProject(project)) {
142326                                 firstExternalProject = project;
142327                             }
142328                         }
142329                         return defaultConfiguredProject ||
142330                             firstNonSourceOfProjectReferenceRedirect ||
142331                             firstConfiguredProject ||
142332                             firstExternalProject ||
142333                             this.containingProjects[0];
142334                 }
142335             };
142336             ScriptInfo.prototype.registerFileUpdate = function () {
142337                 for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
142338                     var p = _a[_i];
142339                     p.registerFileUpdate(this.path);
142340                 }
142341             };
142342             ScriptInfo.prototype.setOptions = function (formatSettings, preferences) {
142343                 if (formatSettings) {
142344                     if (!this.formatSettings) {
142345                         this.formatSettings = ts.getDefaultFormatCodeSettings(this.host.newLine);
142346                         ts.assign(this.formatSettings, formatSettings);
142347                     }
142348                     else {
142349                         this.formatSettings = __assign(__assign({}, this.formatSettings), formatSettings);
142350                     }
142351                 }
142352                 if (preferences) {
142353                     if (!this.preferences) {
142354                         this.preferences = ts.emptyOptions;
142355                     }
142356                     this.preferences = __assign(__assign({}, this.preferences), preferences);
142357                 }
142358             };
142359             ScriptInfo.prototype.getLatestVersion = function () {
142360                 // Ensure we have updated snapshot to give back latest version
142361                 this.textStorage.getSnapshot();
142362                 return this.textStorage.getVersion();
142363             };
142364             ScriptInfo.prototype.saveTo = function (fileName) {
142365                 this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot()));
142366             };
142367             /*@internal*/
142368             ScriptInfo.prototype.delayReloadNonMixedContentFile = function () {
142369                 ts.Debug.assert(!this.isDynamicOrHasMixedContent());
142370                 this.textStorage.delayReloadFromFileIntoText();
142371                 this.markContainingProjectsAsDirty();
142372             };
142373             ScriptInfo.prototype.reloadFromFile = function (tempFileName) {
142374                 if (this.isDynamicOrHasMixedContent()) {
142375                     this.textStorage.reload("");
142376                     this.markContainingProjectsAsDirty();
142377                     return true;
142378                 }
142379                 else {
142380                     if (this.textStorage.reloadWithFileText(tempFileName)) {
142381                         this.markContainingProjectsAsDirty();
142382                         return true;
142383                     }
142384                 }
142385                 return false;
142386             };
142387             /*@internal*/
142388             ScriptInfo.prototype.getAbsolutePositionAndLineText = function (line) {
142389                 return this.textStorage.getAbsolutePositionAndLineText(line);
142390             };
142391             ScriptInfo.prototype.editContent = function (start, end, newText) {
142392                 this.textStorage.edit(start, end, newText);
142393                 this.markContainingProjectsAsDirty();
142394             };
142395             ScriptInfo.prototype.markContainingProjectsAsDirty = function () {
142396                 for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
142397                     var p = _a[_i];
142398                     p.markFileAsDirty(this.path);
142399                 }
142400             };
142401             ScriptInfo.prototype.isOrphan = function () {
142402                 return !ts.forEach(this.containingProjects, function (p) { return !p.isOrphan(); });
142403             };
142404             /**
142405              *  @param line 1 based index
142406              */
142407             ScriptInfo.prototype.lineToTextSpan = function (line) {
142408                 return this.textStorage.lineToTextSpan(line);
142409             };
142410             ScriptInfo.prototype.lineOffsetToPosition = function (line, offset, allowEdits) {
142411                 return this.textStorage.lineOffsetToPosition(line, offset, allowEdits);
142412             };
142413             ScriptInfo.prototype.positionToLineOffset = function (position) {
142414                 failIfInvalidPosition(position);
142415                 var location = this.textStorage.positionToLineOffset(position);
142416                 failIfInvalidLocation(location);
142417                 return location;
142418             };
142419             ScriptInfo.prototype.isJavaScript = function () {
142420                 return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */;
142421             };
142422             /*@internal*/
142423             ScriptInfo.prototype.getLineInfo = function () {
142424                 return this.textStorage.getLineInfo();
142425             };
142426             /*@internal*/
142427             ScriptInfo.prototype.closeSourceMapFileWatcher = function () {
142428                 if (this.sourceMapFilePath && !ts.isString(this.sourceMapFilePath)) {
142429                     ts.closeFileWatcherOf(this.sourceMapFilePath);
142430                     this.sourceMapFilePath = undefined;
142431                 }
142432             };
142433             return ScriptInfo;
142434         }());
142435         server.ScriptInfo = ScriptInfo;
142436         function failIfInvalidPosition(position) {
142437             ts.Debug.assert(typeof position === "number", "Expected position " + position + " to be a number.");
142438             ts.Debug.assert(position >= 0, "Expected position to be non-negative.");
142439         }
142440         function failIfInvalidLocation(location) {
142441             ts.Debug.assert(typeof location.line === "number", "Expected line " + location.line + " to be a number.");
142442             ts.Debug.assert(typeof location.offset === "number", "Expected offset " + location.offset + " to be a number.");
142443             ts.Debug.assert(location.line > 0, "Expected line to be non-" + (location.line === 0 ? "zero" : "negative"));
142444             ts.Debug.assert(location.offset > 0, "Expected offset to be non-" + (location.offset === 0 ? "zero" : "negative"));
142445         }
142446     })(server = ts.server || (ts.server = {}));
142447 })(ts || (ts = {}));
142448 var ts;
142449 (function (ts) {
142450     var server;
142451     (function (server) {
142452         server.nullTypingsInstaller = {
142453             isKnownTypesPackageName: ts.returnFalse,
142454             // Should never be called because we never provide a types registry.
142455             installPackage: ts.notImplemented,
142456             enqueueInstallTypingsRequest: ts.noop,
142457             attach: ts.noop,
142458             onProjectClosed: ts.noop,
142459             globalTypingsCacheLocation: undefined // TODO: GH#18217
142460         };
142461         function setIsEqualTo(arr1, arr2) {
142462             if (arr1 === arr2) {
142463                 return true;
142464             }
142465             if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) {
142466                 return true;
142467             }
142468             var set = ts.createMap();
142469             var unique = 0;
142470             for (var _i = 0, _a = arr1; _i < _a.length; _i++) {
142471                 var v = _a[_i];
142472                 if (set.get(v) !== true) {
142473                     set.set(v, true);
142474                     unique++;
142475                 }
142476             }
142477             for (var _b = 0, _c = arr2; _b < _c.length; _b++) {
142478                 var v = _c[_b];
142479                 var isSet = set.get(v);
142480                 if (isSet === undefined) {
142481                     return false;
142482                 }
142483                 if (isSet === true) {
142484                     set.set(v, false);
142485                     unique--;
142486                 }
142487             }
142488             return unique === 0;
142489         }
142490         function typeAcquisitionChanged(opt1, opt2) {
142491             return opt1.enable !== opt2.enable ||
142492                 !setIsEqualTo(opt1.include, opt2.include) ||
142493                 !setIsEqualTo(opt1.exclude, opt2.exclude);
142494         }
142495         function compilerOptionsChanged(opt1, opt2) {
142496             // TODO: add more relevant properties
142497             return opt1.allowJs !== opt2.allowJs;
142498         }
142499         function unresolvedImportsChanged(imports1, imports2) {
142500             if (imports1 === imports2) {
142501                 return false;
142502             }
142503             return !ts.arrayIsEqualTo(imports1, imports2);
142504         }
142505         /*@internal*/
142506         var TypingsCache = /** @class */ (function () {
142507             function TypingsCache(installer) {
142508                 this.installer = installer;
142509                 this.perProjectCache = ts.createMap();
142510             }
142511             TypingsCache.prototype.isKnownTypesPackageName = function (name) {
142512                 return this.installer.isKnownTypesPackageName(name);
142513             };
142514             TypingsCache.prototype.installPackage = function (options) {
142515                 return this.installer.installPackage(options);
142516             };
142517             TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) {
142518                 var typeAcquisition = project.getTypeAcquisition();
142519                 if (!typeAcquisition || !typeAcquisition.enable) {
142520                     return;
142521                 }
142522                 var entry = this.perProjectCache.get(project.getProjectName());
142523                 if (forceRefresh ||
142524                     !entry ||
142525                     typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) ||
142526                     compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) ||
142527                     unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) {
142528                     // Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options.
142529                     // instead it acts as a placeholder to prevent issuing multiple requests
142530                     this.perProjectCache.set(project.getProjectName(), {
142531                         compilerOptions: project.getCompilationSettings(),
142532                         typeAcquisition: typeAcquisition,
142533                         typings: entry ? entry.typings : server.emptyArray,
142534                         unresolvedImports: unresolvedImports,
142535                         poisoned: true
142536                     });
142537                     // something has been changed, issue a request to update typings
142538                     this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
142539                 }
142540             };
142541             TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) {
142542                 var typings = ts.sort(newTypings);
142543                 this.perProjectCache.set(projectName, {
142544                     compilerOptions: compilerOptions,
142545                     typeAcquisition: typeAcquisition,
142546                     typings: typings,
142547                     unresolvedImports: unresolvedImports,
142548                     poisoned: false
142549                 });
142550                 return !typeAcquisition || !typeAcquisition.enable ? server.emptyArray : typings;
142551             };
142552             TypingsCache.prototype.onProjectClosed = function (project) {
142553                 this.perProjectCache.delete(project.getProjectName());
142554                 this.installer.onProjectClosed(project);
142555             };
142556             return TypingsCache;
142557         }());
142558         server.TypingsCache = TypingsCache;
142559     })(server = ts.server || (ts.server = {}));
142560 })(ts || (ts = {}));
142561 var ts;
142562 (function (ts) {
142563     var server;
142564     (function (server) {
142565         var ProjectKind;
142566         (function (ProjectKind) {
142567             ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred";
142568             ProjectKind[ProjectKind["Configured"] = 1] = "Configured";
142569             ProjectKind[ProjectKind["External"] = 2] = "External";
142570         })(ProjectKind = server.ProjectKind || (server.ProjectKind = {}));
142571         /* @internal */
142572         function countEachFileTypes(infos, includeSizes) {
142573             if (includeSizes === void 0) { includeSizes = false; }
142574             var result = {
142575                 js: 0, jsSize: 0,
142576                 jsx: 0, jsxSize: 0,
142577                 ts: 0, tsSize: 0,
142578                 tsx: 0, tsxSize: 0,
142579                 dts: 0, dtsSize: 0,
142580                 deferred: 0, deferredSize: 0,
142581             };
142582             for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
142583                 var info = infos_1[_i];
142584                 var fileSize = includeSizes ? info.getTelemetryFileSize() : 0;
142585                 switch (info.scriptKind) {
142586                     case 1 /* JS */:
142587                         result.js += 1;
142588                         result.jsSize += fileSize;
142589                         break;
142590                     case 2 /* JSX */:
142591                         result.jsx += 1;
142592                         result.jsxSize += fileSize;
142593                         break;
142594                     case 3 /* TS */:
142595                         if (ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */)) {
142596                             result.dts += 1;
142597                             result.dtsSize += fileSize;
142598                         }
142599                         else {
142600                             result.ts += 1;
142601                             result.tsSize += fileSize;
142602                         }
142603                         break;
142604                     case 4 /* TSX */:
142605                         result.tsx += 1;
142606                         result.tsxSize += fileSize;
142607                         break;
142608                     case 7 /* Deferred */:
142609                         result.deferred += 1;
142610                         result.deferredSize += fileSize;
142611                         break;
142612                 }
142613             }
142614             return result;
142615         }
142616         server.countEachFileTypes = countEachFileTypes;
142617         function hasOneOrMoreJsAndNoTsFiles(project) {
142618             var counts = countEachFileTypes(project.getScriptInfos());
142619             return counts.js > 0 && counts.ts === 0 && counts.tsx === 0;
142620         }
142621         function allRootFilesAreJsOrDts(project) {
142622             var counts = countEachFileTypes(project.getRootScriptInfos());
142623             return counts.ts === 0 && counts.tsx === 0;
142624         }
142625         server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts;
142626         function allFilesAreJsOrDts(project) {
142627             var counts = countEachFileTypes(project.getScriptInfos());
142628             return counts.ts === 0 && counts.tsx === 0;
142629         }
142630         server.allFilesAreJsOrDts = allFilesAreJsOrDts;
142631         /* @internal */
142632         function hasNoTypeScriptSource(fileNames) {
142633             return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts" /* Ts */) && !ts.fileExtensionIs(fileName, ".d.ts" /* Dts */)) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */); });
142634         }
142635         server.hasNoTypeScriptSource = hasNoTypeScriptSource;
142636         function isGeneratedFileWatcher(watch) {
142637             return watch.generatedFilePath !== undefined;
142638         }
142639         var Project = /** @class */ (function () {
142640             /*@internal*/
142641             function Project(
142642             /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, directoryStructureHost, currentDirectory) {
142643                 var _this = this;
142644                 this.projectName = projectName;
142645                 this.projectKind = projectKind;
142646                 this.projectService = projectService;
142647                 this.documentRegistry = documentRegistry;
142648                 this.compilerOptions = compilerOptions;
142649                 this.compileOnSaveEnabled = compileOnSaveEnabled;
142650                 this.watchOptions = watchOptions;
142651                 this.rootFiles = [];
142652                 this.rootFilesMap = ts.createMap();
142653                 this.plugins = [];
142654                 /*@internal*/
142655                 /**
142656                  * This is map from files to unresolved imports in it
142657                  * Maop does not contain entries for files that do not have unresolved imports
142658                  * This helps in containing the set of files to invalidate
142659                  */
142660                 this.cachedUnresolvedImportsPerFile = ts.createMap();
142661                 /*@internal*/
142662                 this.hasAddedorRemovedFiles = false;
142663                 /**
142664                  * Last version that was reported.
142665                  */
142666                 this.lastReportedVersion = 0;
142667                 /**
142668                  * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one)
142669                  * This property is changed in 'updateGraph' based on the set of files in program
142670                  */
142671                 this.projectProgramVersion = 0;
142672                 /**
142673                  * Current version of the project state. It is changed when:
142674                  * - new root file was added/removed
142675                  * - edit happen in some file that is currently included in the project.
142676                  * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project
142677                  */
142678                 this.projectStateVersion = 0;
142679                 this.isInitialLoadPending = ts.returnFalse;
142680                 /*@internal*/
142681                 this.dirty = false;
142682                 /*@internal*/
142683                 this.hasChangedAutomaticTypeDirectiveNames = false;
142684                 /*@internal*/
142685                 this.typingFiles = server.emptyArray;
142686                 /*@internal*/
142687                 this.importSuggestionsCache = ts.Completions.createImportSuggestionsForFileCache();
142688                 /*@internal*/
142689                 this.globalCacheResolutionModuleName = ts.JsTyping.nonRelativeModuleNameForTypingCache;
142690                 this.directoryStructureHost = directoryStructureHost;
142691                 this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || "");
142692                 this.getCanonicalFileName = this.projectService.toCanonicalFileName;
142693                 this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds);
142694                 if (!this.compilerOptions) {
142695                     this.compilerOptions = ts.getDefaultCompilerOptions();
142696                     this.compilerOptions.allowNonTsExtensions = true;
142697                     this.compilerOptions.allowJs = true;
142698                 }
142699                 else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) {
142700                     // If files are listed explicitly or allowJs is specified, allow all extensions
142701                     this.compilerOptions.allowNonTsExtensions = true;
142702                 }
142703                 this.languageServiceEnabled = !projectService.syntaxOnly;
142704                 this.setInternalCompilerOptionsForEmittingJsFiles();
142705                 var host = this.projectService.host;
142706                 if (this.projectService.logger.loggingEnabled()) {
142707                     this.trace = function (s) { return _this.writeLog(s); };
142708                 }
142709                 else if (host.trace) {
142710                     this.trace = function (s) { return host.trace(s); };
142711                 }
142712                 this.realpath = ts.maybeBind(host, host.realpath);
142713                 // Use the current directory as resolution root only if the project created using current directory string
142714                 this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true);
142715                 this.languageService = ts.createLanguageService(this, this.documentRegistry, projectService.syntaxOnly);
142716                 if (lastFileExceededProgramSize) {
142717                     this.disableLanguageService(lastFileExceededProgramSize);
142718                 }
142719                 this.markAsDirty();
142720                 this.projectService.pendingEnsureProjectForOpenFiles = true;
142721                 this.packageJsonCache = server.createPackageJsonCache(this);
142722             }
142723             /*@internal*/
142724             Project.prototype.getResolvedProjectReferenceToRedirect = function (_fileName) {
142725                 return undefined;
142726             };
142727             Project.prototype.isNonTsProject = function () {
142728                 server.updateProjectIfDirty(this);
142729                 return allFilesAreJsOrDts(this);
142730             };
142731             Project.prototype.isJsOnlyProject = function () {
142732                 server.updateProjectIfDirty(this);
142733                 return hasOneOrMoreJsAndNoTsFiles(this);
142734             };
142735             Project.resolveModule = function (moduleName, initialDir, host, log, logErrors) {
142736                 var resolvedPath = ts.normalizeSlashes(host.resolvePath(ts.combinePaths(initialDir, "node_modules")));
142737                 log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")");
142738                 var result = host.require(resolvedPath, moduleName); // TODO: GH#18217
142739                 if (result.error) {
142740                     var err = result.error.stack || result.error.message || JSON.stringify(result.error);
142741                     (logErrors || log)("Failed to load module '" + moduleName + "' from " + resolvedPath + ": " + err);
142742                     return undefined;
142743                 }
142744                 return result.module;
142745             };
142746             Project.prototype.isKnownTypesPackageName = function (name) {
142747                 return this.typingsCache.isKnownTypesPackageName(name);
142748             };
142749             Project.prototype.installPackage = function (options) {
142750                 return this.typingsCache.installPackage(__assign(__assign({}, options), { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }));
142751             };
142752             /*@internal*/
142753             Project.prototype.getGlobalTypingsCacheLocation = function () {
142754                 return this.getGlobalCache();
142755             };
142756             Object.defineProperty(Project.prototype, "typingsCache", {
142757                 get: function () {
142758                     return this.projectService.typingsCache;
142759                 },
142760                 enumerable: false,
142761                 configurable: true
142762             });
142763             /*@internal*/
142764             Project.prototype.getProbableSymlinks = function (files) {
142765                 return this.symlinks || (this.symlinks = ts.discoverProbableSymlinks(files, this.getCanonicalFileName, this.getCurrentDirectory()));
142766             };
142767             // Method of LanguageServiceHost
142768             Project.prototype.getCompilationSettings = function () {
142769                 return this.compilerOptions;
142770             };
142771             // Method to support public API
142772             Project.prototype.getCompilerOptions = function () {
142773                 return this.getCompilationSettings();
142774             };
142775             Project.prototype.getNewLine = function () {
142776                 return this.projectService.host.newLine;
142777             };
142778             Project.prototype.getProjectVersion = function () {
142779                 return this.projectStateVersion.toString();
142780             };
142781             Project.prototype.getProjectReferences = function () {
142782                 return undefined;
142783             };
142784             Project.prototype.getScriptFileNames = function () {
142785                 var _this = this;
142786                 if (!this.rootFiles) {
142787                     return ts.emptyArray;
142788                 }
142789                 var result;
142790                 this.rootFilesMap.forEach(function (value) {
142791                     if (_this.languageServiceEnabled || (value.info && value.info.isScriptOpen())) {
142792                         // if language service is disabled - process only files that are open
142793                         (result || (result = [])).push(value.fileName);
142794                     }
142795                 });
142796                 return ts.addRange(result, this.typingFiles) || ts.emptyArray;
142797             };
142798             Project.prototype.getOrCreateScriptInfoAndAttachToProject = function (fileName) {
142799                 var scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(fileName, this.currentDirectory, this.directoryStructureHost);
142800                 if (scriptInfo) {
142801                     var existingValue = this.rootFilesMap.get(scriptInfo.path);
142802                     if (existingValue && existingValue.info !== scriptInfo) {
142803                         // This was missing path earlier but now the file exists. Update the root
142804                         this.rootFiles.push(scriptInfo);
142805                         existingValue.info = scriptInfo;
142806                     }
142807                     scriptInfo.attachToProject(this);
142808                 }
142809                 return scriptInfo;
142810             };
142811             Project.prototype.getScriptKind = function (fileName) {
142812                 var info = this.getOrCreateScriptInfoAndAttachToProject(fileName);
142813                 return (info && info.scriptKind); // TODO: GH#18217
142814             };
142815             Project.prototype.getScriptVersion = function (filename) {
142816                 // Don't attach to the project if version is asked
142817                 var info = this.projectService.getOrCreateScriptInfoNotOpenedByClient(filename, this.currentDirectory, this.directoryStructureHost);
142818                 return (info && info.getLatestVersion()); // TODO: GH#18217
142819             };
142820             Project.prototype.getScriptSnapshot = function (filename) {
142821                 var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename);
142822                 if (scriptInfo) {
142823                     return scriptInfo.getSnapshot();
142824                 }
142825             };
142826             Project.prototype.getCancellationToken = function () {
142827                 return this.cancellationToken;
142828             };
142829             Project.prototype.getCurrentDirectory = function () {
142830                 return this.currentDirectory;
142831             };
142832             Project.prototype.getDefaultLibFileName = function () {
142833                 var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.getExecutingFilePath()));
142834                 return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions));
142835             };
142836             Project.prototype.useCaseSensitiveFileNames = function () {
142837                 return this.projectService.host.useCaseSensitiveFileNames;
142838             };
142839             Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) {
142840                 return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth);
142841             };
142842             Project.prototype.readFile = function (fileName) {
142843                 return this.projectService.host.readFile(fileName);
142844             };
142845             Project.prototype.writeFile = function (fileName, content) {
142846                 return this.projectService.host.writeFile(fileName, content);
142847             };
142848             Project.prototype.fileExists = function (file) {
142849                 // As an optimization, don't hit the disks for files we already know don't exist
142850                 // (because we're watching for their creation).
142851                 var path = this.toPath(file);
142852                 return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file);
142853             };
142854             Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) {
142855                 return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference);
142856             };
142857             Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) {
142858                 return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile);
142859             };
142860             Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile, redirectedReference) {
142861                 return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference);
142862             };
142863             Project.prototype.directoryExists = function (path) {
142864                 return this.directoryStructureHost.directoryExists(path); // TODO: GH#18217
142865             };
142866             Project.prototype.getDirectories = function (path) {
142867                 return this.directoryStructureHost.getDirectories(path); // TODO: GH#18217
142868             };
142869             /*@internal*/
142870             Project.prototype.getCachedDirectoryStructureHost = function () {
142871                 return undefined; // TODO: GH#18217
142872             };
142873             /*@internal*/
142874             Project.prototype.toPath = function (fileName) {
142875                 return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName);
142876             };
142877             /*@internal*/
142878             Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) {
142879                 return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, this.projectService.getWatchOptions(this), ts.WatchType.FailedLookupLocations, this);
142880             };
142881             /*@internal*/
142882             Project.prototype.onInvalidatedResolution = function () {
142883                 this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
142884             };
142885             /*@internal*/
142886             Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) {
142887                 return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, this.projectService.getWatchOptions(this), ts.WatchType.TypeRoots, this);
142888             };
142889             /*@internal*/
142890             Project.prototype.onChangedAutomaticTypeDirectiveNames = function () {
142891                 this.hasChangedAutomaticTypeDirectiveNames = true;
142892                 this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
142893             };
142894             /*@internal*/
142895             Project.prototype.getGlobalCache = function () {
142896                 return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined;
142897             };
142898             /*@internal*/
142899             Project.prototype.fileIsOpen = function (filePath) {
142900                 return this.projectService.openFiles.has(filePath);
142901             };
142902             /*@internal*/
142903             Project.prototype.writeLog = function (s) {
142904                 this.projectService.logger.info(s);
142905             };
142906             Project.prototype.log = function (s) {
142907                 this.writeLog(s);
142908             };
142909             Project.prototype.error = function (s) {
142910                 this.projectService.logger.msg(s, server.Msg.Err);
142911             };
142912             Project.prototype.setInternalCompilerOptionsForEmittingJsFiles = function () {
142913                 if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) {
142914                     this.compilerOptions.noEmitForJsFiles = true;
142915                 }
142916             };
142917             /**
142918              * Get the errors that dont have any file name associated
142919              */
142920             Project.prototype.getGlobalProjectErrors = function () {
142921                 return server.emptyArray;
142922             };
142923             Project.prototype.getAllProjectErrors = function () {
142924                 return server.emptyArray;
142925             };
142926             Project.prototype.getLanguageService = function (ensureSynchronized) {
142927                 if (ensureSynchronized === void 0) { ensureSynchronized = true; }
142928                 if (ensureSynchronized) {
142929                     server.updateProjectIfDirty(this);
142930                 }
142931                 return this.languageService;
142932             };
142933             /** @internal */
142934             Project.prototype.getSourceMapper = function () {
142935                 return this.getLanguageService().getSourceMapper();
142936             };
142937             /** @internal */
142938             Project.prototype.clearSourceMapperCache = function () {
142939                 this.languageService.clearSourceMapperCache();
142940             };
142941             /*@internal*/
142942             Project.prototype.getDocumentPositionMapper = function (generatedFileName, sourceFileName) {
142943                 return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName);
142944             };
142945             /*@internal*/
142946             Project.prototype.getSourceFileLike = function (fileName) {
142947                 return this.projectService.getSourceFileLike(fileName, this);
142948             };
142949             /*@internal*/
142950             Project.prototype.shouldEmitFile = function (scriptInfo) {
142951                 return scriptInfo &&
142952                     !scriptInfo.isDynamicOrHasMixedContent() &&
142953                     !this.program.isSourceOfProjectReferenceRedirect(scriptInfo.path);
142954             };
142955             Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) {
142956                 var _this = this;
142957                 if (!this.languageServiceEnabled) {
142958                     return [];
142959                 }
142960                 server.updateProjectIfDirty(this);
142961                 this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState);
142962                 return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), // TODO: GH#18217
142963                 function (// TODO: GH#18217
142964                 sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; });
142965             };
142966             /**
142967              * Returns true if emit was conducted
142968              */
142969             Project.prototype.emitFile = function (scriptInfo, writeFile) {
142970                 if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) {
142971                     return { emitSkipped: true, diagnostics: server.emptyArray };
142972                 }
142973                 var _a = this.getLanguageService().getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, outputFiles = _a.outputFiles;
142974                 if (!emitSkipped) {
142975                     for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) {
142976                         var outputFile = outputFiles_1[_i];
142977                         var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, this.currentDirectory);
142978                         writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark);
142979                     }
142980                     // Update the signature
142981                     if (this.builderState && ts.getEmitDeclarations(this.compilerOptions)) {
142982                         var dtsFiles = outputFiles.filter(function (f) { return ts.fileExtensionIs(f.name, ".d.ts" /* Dts */); });
142983                         if (dtsFiles.length === 1) {
142984                             var sourceFile = this.program.getSourceFile(scriptInfo.fileName);
142985                             ts.BuilderState.updateSignatureOfFile(this.builderState, this.projectService.host.createHash(dtsFiles[0].text), sourceFile.resolvedPath);
142986                         }
142987                     }
142988                 }
142989                 return { emitSkipped: emitSkipped, diagnostics: diagnostics };
142990             };
142991             Project.prototype.enableLanguageService = function () {
142992                 if (this.languageServiceEnabled || this.projectService.syntaxOnly) {
142993                     return;
142994                 }
142995                 this.languageServiceEnabled = true;
142996                 this.lastFileExceededProgramSize = undefined;
142997                 this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ true);
142998             };
142999             Project.prototype.disableLanguageService = function (lastFileExceededProgramSize) {
143000                 if (!this.languageServiceEnabled) {
143001                     return;
143002                 }
143003                 ts.Debug.assert(!this.projectService.syntaxOnly);
143004                 this.languageService.cleanupSemanticCache();
143005                 this.languageServiceEnabled = false;
143006                 this.lastFileExceededProgramSize = lastFileExceededProgramSize;
143007                 this.builderState = undefined;
143008                 this.resolutionCache.closeTypeRootsWatch();
143009                 this.clearGeneratedFileWatch();
143010                 this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false);
143011             };
143012             Project.prototype.getProjectName = function () {
143013                 return this.projectName;
143014             };
143015             Project.prototype.removeLocalTypingsFromTypeAcquisition = function (newTypeAcquisition) {
143016                 if (!newTypeAcquisition || !newTypeAcquisition.include) {
143017                     // Nothing to filter out, so just return as-is
143018                     return newTypeAcquisition;
143019                 }
143020                 return __assign(__assign({}, newTypeAcquisition), { include: this.removeExistingTypings(newTypeAcquisition.include) });
143021             };
143022             Project.prototype.getExternalFiles = function () {
143023                 var _this = this;
143024                 return ts.sort(ts.flatMap(this.plugins, function (plugin) {
143025                     if (typeof plugin.module.getExternalFiles !== "function")
143026                         return;
143027                     try {
143028                         return plugin.module.getExternalFiles(_this);
143029                     }
143030                     catch (e) {
143031                         _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e);
143032                         if (e.stack) {
143033                             _this.projectService.logger.info(e.stack);
143034                         }
143035                     }
143036                 }));
143037             };
143038             Project.prototype.getSourceFile = function (path) {
143039                 if (!this.program) {
143040                     return undefined;
143041                 }
143042                 return this.program.getSourceFileByPath(path);
143043             };
143044             /* @internal */
143045             Project.prototype.getSourceFileOrConfigFile = function (path) {
143046                 var options = this.program.getCompilerOptions();
143047                 return path === options.configFilePath ? options.configFile : this.getSourceFile(path);
143048             };
143049             Project.prototype.close = function () {
143050                 var _this = this;
143051                 if (this.program) {
143052                     // if we have a program - release all files that are enlisted in program but arent root
143053                     // The releasing of the roots happens later
143054                     // The project could have pending update remaining and hence the info could be in the files but not in program graph
143055                     for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) {
143056                         var f = _a[_i];
143057                         this.detachScriptInfoIfNotRoot(f.fileName);
143058                     }
143059                     this.program.forEachResolvedProjectReference(function (ref) {
143060                         if (ref) {
143061                             _this.detachScriptInfoFromProject(ref.sourceFile.fileName);
143062                         }
143063                     });
143064                 }
143065                 // Release external files
143066                 ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); });
143067                 // Always remove root files from the project
143068                 for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) {
143069                     var root = _c[_b];
143070                     root.detachFromProject(this);
143071                 }
143072                 this.projectService.pendingEnsureProjectForOpenFiles = true;
143073                 this.rootFiles = undefined;
143074                 this.rootFilesMap = undefined;
143075                 this.externalFiles = undefined;
143076                 this.program = undefined;
143077                 this.builderState = undefined;
143078                 this.resolutionCache.clear();
143079                 this.resolutionCache = undefined;
143080                 this.cachedUnresolvedImportsPerFile = undefined;
143081                 this.directoryStructureHost = undefined;
143082                 // Clean up file watchers waiting for missing files
143083                 if (this.missingFilesMap) {
143084                     ts.clearMap(this.missingFilesMap, ts.closeFileWatcher);
143085                     this.missingFilesMap = undefined;
143086                 }
143087                 if (this.packageJsonFilesMap) {
143088                     ts.clearMap(this.packageJsonFilesMap, ts.closeFileWatcher);
143089                     this.packageJsonFilesMap = undefined;
143090                 }
143091                 this.clearGeneratedFileWatch();
143092                 // signal language service to release source files acquired from document registry
143093                 this.languageService.dispose();
143094                 this.languageService = undefined;
143095             };
143096             Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) {
143097                 var info = this.projectService.getScriptInfo(uncheckedFilename);
143098                 // We might not find the script info in case its not associated with the project any more
143099                 // and project graph was not updated (eg delayed update graph in case of files changed/deleted on the disk)
143100                 if (info && !this.isRoot(info)) {
143101                     info.detachFromProject(this);
143102                 }
143103             };
143104             Project.prototype.isClosed = function () {
143105                 return this.rootFiles === undefined;
143106             };
143107             Project.prototype.hasRoots = function () {
143108                 return this.rootFiles && this.rootFiles.length > 0;
143109             };
143110             /*@internal*/
143111             Project.prototype.isOrphan = function () {
143112                 return false;
143113             };
143114             Project.prototype.getRootFiles = function () {
143115                 return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; });
143116             };
143117             /*@internal*/
143118             Project.prototype.getRootFilesMap = function () {
143119                 return this.rootFilesMap;
143120             };
143121             Project.prototype.getRootScriptInfos = function () {
143122                 return this.rootFiles;
143123             };
143124             Project.prototype.getScriptInfos = function () {
143125                 var _this = this;
143126                 if (!this.languageServiceEnabled) {
143127                     // if language service is not enabled - return just root files
143128                     return this.rootFiles;
143129                 }
143130                 return ts.map(this.program.getSourceFiles(), function (sourceFile) {
143131                     var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath);
143132                     ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; });
143133                     return scriptInfo;
143134                 });
143135             };
143136             Project.prototype.getExcludedFiles = function () {
143137                 return server.emptyArray;
143138             };
143139             Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries, excludeConfigFiles) {
143140                 if (!this.program) {
143141                     return [];
143142                 }
143143                 if (!this.languageServiceEnabled) {
143144                     // if language service is disabled assume that all files in program are root files + default library
143145                     var rootFiles = this.getRootFiles();
143146                     if (this.compilerOptions) {
143147                         var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions);
143148                         if (defaultLibrary) {
143149                             (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary));
143150                         }
143151                     }
143152                     return rootFiles;
143153                 }
143154                 var result = [];
143155                 for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) {
143156                     var f = _a[_i];
143157                     if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) {
143158                         continue;
143159                     }
143160                     result.push(server.asNormalizedPath(f.fileName));
143161                 }
143162                 if (!excludeConfigFiles) {
143163                     var configFile = this.program.getCompilerOptions().configFile;
143164                     if (configFile) {
143165                         result.push(server.asNormalizedPath(configFile.fileName));
143166                         if (configFile.extendedSourceFiles) {
143167                             for (var _b = 0, _c = configFile.extendedSourceFiles; _b < _c.length; _b++) {
143168                                 var f = _c[_b];
143169                                 result.push(server.asNormalizedPath(f));
143170                             }
143171                         }
143172                     }
143173                 }
143174                 return result;
143175             };
143176             /* @internal */
143177             Project.prototype.getFileNamesWithRedirectInfo = function (includeProjectReferenceRedirectInfo) {
143178                 var _this = this;
143179                 return this.getFileNames().map(function (fileName) { return ({
143180                     fileName: fileName,
143181                     isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && _this.isSourceOfProjectReferenceRedirect(fileName)
143182                 }); });
143183             };
143184             Project.prototype.hasConfigFile = function (configFilePath) {
143185                 if (this.program && this.languageServiceEnabled) {
143186                     var configFile = this.program.getCompilerOptions().configFile;
143187                     if (configFile) {
143188                         if (configFilePath === server.asNormalizedPath(configFile.fileName)) {
143189                             return true;
143190                         }
143191                         if (configFile.extendedSourceFiles) {
143192                             for (var _i = 0, _a = configFile.extendedSourceFiles; _i < _a.length; _i++) {
143193                                 var f = _a[_i];
143194                                 if (configFilePath === server.asNormalizedPath(f)) {
143195                                     return true;
143196                                 }
143197                             }
143198                         }
143199                     }
143200                 }
143201                 return false;
143202             };
143203             Project.prototype.containsScriptInfo = function (info) {
143204                 if (this.isRoot(info))
143205                     return true;
143206                 if (!this.program)
143207                     return false;
143208                 var file = this.program.getSourceFileByPath(info.path);
143209                 return !!file && file.resolvedPath === info.path;
143210             };
143211             Project.prototype.containsFile = function (filename, requireOpen) {
143212                 var info = this.projectService.getScriptInfoForNormalizedPath(filename);
143213                 if (info && (info.isScriptOpen() || !requireOpen)) {
143214                     return this.containsScriptInfo(info);
143215                 }
143216                 return false;
143217             };
143218             Project.prototype.isRoot = function (info) {
143219                 var _a;
143220                 return this.rootFilesMap && ((_a = this.rootFilesMap.get(info.path)) === null || _a === void 0 ? void 0 : _a.info) === info;
143221             };
143222             // add a root file to project
143223             Project.prototype.addRoot = function (info, fileName) {
143224                 ts.Debug.assert(!this.isRoot(info));
143225                 this.rootFiles.push(info);
143226                 this.rootFilesMap.set(info.path, { fileName: fileName || info.fileName, info: info });
143227                 info.attachToProject(this);
143228                 this.markAsDirty();
143229             };
143230             // add a root file that doesnt exist on host
143231             Project.prototype.addMissingFileRoot = function (fileName) {
143232                 var path = this.projectService.toPath(fileName);
143233                 this.rootFilesMap.set(path, { fileName: fileName });
143234                 this.markAsDirty();
143235             };
143236             Project.prototype.removeFile = function (info, fileExists, detachFromProject) {
143237                 if (this.isRoot(info)) {
143238                     this.removeRoot(info);
143239                 }
143240                 if (fileExists) {
143241                     // If file is present, just remove the resolutions for the file
143242                     this.resolutionCache.removeResolutionsOfFile(info.path);
143243                 }
143244                 else {
143245                     this.resolutionCache.invalidateResolutionOfFile(info.path);
143246                 }
143247                 this.cachedUnresolvedImportsPerFile.delete(info.path);
143248                 if (detachFromProject) {
143249                     info.detachFromProject(this);
143250                 }
143251                 this.markAsDirty();
143252             };
143253             Project.prototype.registerFileUpdate = function (fileName) {
143254                 (this.updatedFileNames || (this.updatedFileNames = ts.createMap())).set(fileName, true);
143255             };
143256             /*@internal*/
143257             Project.prototype.markFileAsDirty = function (changedFile) {
143258                 this.markAsDirty();
143259                 if (!this.importSuggestionsCache.isEmpty()) {
143260                     (this.dirtyFilesForSuggestions || (this.dirtyFilesForSuggestions = ts.createMap())).set(changedFile, true);
143261                 }
143262             };
143263             Project.prototype.markAsDirty = function () {
143264                 if (!this.dirty) {
143265                     this.projectStateVersion++;
143266                     this.dirty = true;
143267                 }
143268             };
143269             /* @internal */
143270             Project.prototype.onFileAddedOrRemoved = function () {
143271                 this.hasAddedorRemovedFiles = true;
143272             };
143273             /**
143274              * Updates set of files that contribute to this project
143275              * @returns: true if set of files in the project stays the same and false - otherwise.
143276              */
143277             Project.prototype.updateGraph = function () {
143278                 ts.perfLogger.logStartUpdateGraph();
143279                 this.resolutionCache.startRecordingFilesWithChangedResolutions();
143280                 var hasNewProgram = this.updateGraphWorker();
143281                 var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles;
143282                 this.hasAddedorRemovedFiles = false;
143283                 var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray;
143284                 for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) {
143285                     var file = changedFiles_1[_i];
143286                     // delete cached information for changed files
143287                     this.cachedUnresolvedImportsPerFile.delete(file);
143288                 }
143289                 // update builder only if language service is enabled
143290                 // otherwise tell it to drop its internal state
143291                 if (this.languageServiceEnabled) {
143292                     // 1. no changes in structure, no changes in unresolved imports - do nothing
143293                     // 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files
143294                     // (can reuse cached imports for files that were not changed)
143295                     // 3. new files were added/removed, but compilation settings stays the same - collect unresolved imports for all new/modified files
143296                     // (can reuse cached imports for files that were not changed)
143297                     // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch
143298                     if (hasNewProgram || changedFiles.length) {
143299                         this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile);
143300                     }
143301                     this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles);
143302                 }
143303                 else {
143304                     this.lastCachedUnresolvedImportsList = undefined;
143305                 }
143306                 if (hasNewProgram) {
143307                     this.projectProgramVersion++;
143308                 }
143309                 ts.perfLogger.logStopUpdateGraph();
143310                 return !hasNewProgram;
143311             };
143312             /*@internal*/
143313             Project.prototype.updateTypingFiles = function (typingFiles) {
143314                 var _this = this;
143315                 ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), 
143316                 /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); });
143317                 this.typingFiles = typingFiles;
143318                 // Invalidate files with unresolved imports
143319                 this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile);
143320             };
143321             /* @internal */
143322             Project.prototype.getCurrentProgram = function () {
143323                 return this.program;
143324             };
143325             Project.prototype.removeExistingTypings = function (include) {
143326                 var existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost);
143327                 return include.filter(function (i) { return existing.indexOf(i) < 0; });
143328             };
143329             Project.prototype.updateGraphWorker = function () {
143330                 var _this = this;
143331                 var oldProgram = this.program;
143332                 ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project");
143333                 this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName());
143334                 var start = ts.timestamp();
143335                 this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution();
143336                 this.resolutionCache.startCachingPerDirectoryResolution();
143337                 this.program = this.languageService.getProgram(); // TODO: GH#18217
143338                 this.dirty = false;
143339                 this.resolutionCache.finishCachingPerDirectoryResolution();
143340                 ts.Debug.assert(oldProgram === undefined || this.program !== undefined);
143341                 // bump up the version if
143342                 // - oldProgram is not set - this is a first time updateGraph is called
143343                 // - newProgram is different from the old program and structure of the old program was not reused.
143344                 var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2 /* Completely */)));
143345                 this.hasChangedAutomaticTypeDirectiveNames = false;
143346                 if (hasNewProgram) {
143347                     if (oldProgram) {
143348                         for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) {
143349                             var f = _a[_i];
143350                             var newFile = this.program.getSourceFileByPath(f.resolvedPath);
143351                             if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) {
143352                                 // new program does not contain this file - detach it from the project
143353                                 // - remove resolutions only if the new program doesnt contain source file by the path (not resolvedPath since path is used for resolution)
143354                                 this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path));
143355                             }
143356                         }
143357                         oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
143358                             if (resolvedProjectReference && !_this.program.getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
143359                                 _this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName);
143360                             }
143361                         });
143362                     }
143363                     // Update the missing file paths watcher
143364                     ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), 
143365                     // Watch the missing files
143366                     function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); });
143367                     if (this.generatedFilesMap) {
143368                         var outPath = this.compilerOptions.outFile && this.compilerOptions.out;
143369                         if (isGeneratedFileWatcher(this.generatedFilesMap)) {
143370                             // --out
143371                             if (!outPath || !this.isValidGeneratedFileWatcher(ts.removeFileExtension(outPath) + ".d.ts" /* Dts */, this.generatedFilesMap)) {
143372                                 this.clearGeneratedFileWatch();
143373                             }
143374                         }
143375                         else {
143376                             // MultiFile
143377                             if (outPath) {
143378                                 this.clearGeneratedFileWatch();
143379                             }
143380                             else {
143381                                 this.generatedFilesMap.forEach(function (watcher, source) {
143382                                     var sourceFile = _this.program.getSourceFileByPath(source);
143383                                     if (!sourceFile ||
143384                                         sourceFile.resolvedPath !== source ||
143385                                         !_this.isValidGeneratedFileWatcher(ts.getDeclarationEmitOutputFilePathWorker(sourceFile.fileName, _this.compilerOptions, _this.currentDirectory, _this.program.getCommonSourceDirectory(), _this.getCanonicalFileName), watcher)) {
143386                                         ts.closeFileWatcherOf(watcher);
143387                                         _this.generatedFilesMap.delete(source);
143388                                     }
143389                                 });
143390                             }
143391                         }
143392                     }
143393                     // Watch the type locations that would be added to program as part of automatic type resolutions
143394                     if (this.languageServiceEnabled) {
143395                         this.resolutionCache.updateTypeRootsWatch();
143396                     }
143397                 }
143398                 if (!this.importSuggestionsCache.isEmpty()) {
143399                     if (this.hasAddedorRemovedFiles || oldProgram && !oldProgram.structureIsReused) {
143400                         this.importSuggestionsCache.clear();
143401                     }
143402                     else if (this.dirtyFilesForSuggestions && oldProgram && this.program) {
143403                         ts.forEachKey(this.dirtyFilesForSuggestions, function (fileName) {
143404                             var oldSourceFile = oldProgram.getSourceFile(fileName);
143405                             var sourceFile = _this.program.getSourceFile(fileName);
143406                             if (_this.sourceFileHasChangedOwnImportSuggestions(oldSourceFile, sourceFile)) {
143407                                 _this.importSuggestionsCache.clear();
143408                                 return true;
143409                             }
143410                         });
143411                     }
143412                 }
143413                 if (this.dirtyFilesForSuggestions) {
143414                     this.dirtyFilesForSuggestions.clear();
143415                 }
143416                 if (this.hasAddedorRemovedFiles) {
143417                     this.symlinks = undefined;
143418                 }
143419                 var oldExternalFiles = this.externalFiles || server.emptyArray;
143420                 this.externalFiles = this.getExternalFiles();
143421                 ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), 
143422                 // Ensure a ScriptInfo is created for new external files. This is performed indirectly
143423                 // by the host for files in the program when the program is retrieved above but
143424                 // the program doesn't contain external files so this must be done explicitly.
143425                 function (inserted) {
143426                     var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost);
143427                     scriptInfo.attachToProject(_this);
143428                 }, function (removed) { return _this.detachScriptInfoFromProject(removed); });
143429                 var elapsed = ts.timestamp() - start;
143430                 this.projectService.sendUpdateGraphPerformanceEvent(elapsed);
143431                 this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " Version: " + this.getProjectVersion() + " structureChanged: " + hasNewProgram + " Elapsed: " + elapsed + "ms");
143432                 if (this.hasAddedorRemovedFiles) {
143433                     this.print(/*writeProjectFileNames*/ true);
143434                 }
143435                 else if (this.program !== oldProgram) {
143436                     this.writeLog("Different program with same set of files:: oldProgram.structureIsReused:: " + (oldProgram && oldProgram.structureIsReused));
143437                 }
143438                 return hasNewProgram;
143439             };
143440             /*@internal*/
143441             Project.prototype.sourceFileHasChangedOwnImportSuggestions = function (oldSourceFile, newSourceFile) {
143442                 if (!oldSourceFile && !newSourceFile) {
143443                     return false;
143444                 }
143445                 // Probably shouldn’t get this far, but on the off chance the file was added or removed,
143446                 // we can’t reliably tell anything about it.
143447                 if (!oldSourceFile || !newSourceFile) {
143448                     return true;
143449                 }
143450                 ts.Debug.assertEqual(oldSourceFile.fileName, newSourceFile.fileName);
143451                 // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node.
143452                 // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list.
143453                 if (this.getTypeAcquisition().enable && ts.consumesNodeCoreModules(oldSourceFile) !== ts.consumesNodeCoreModules(newSourceFile)) {
143454                     return true;
143455                 }
143456                 // Module agumentation and ambient module changes can add or remove exports available to be auto-imported.
143457                 // Changes elsewhere in the file can change the *type* of an export in a module augmentation,
143458                 // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache.
143459                 if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) ||
143460                     !this.ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) {
143461                     return true;
143462                 }
143463                 return false;
143464             };
143465             /*@internal*/
143466             Project.prototype.ambientModuleDeclarationsAreEqual = function (oldSourceFile, newSourceFile) {
143467                 if (!ts.arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) {
143468                     return false;
143469                 }
143470                 var oldFileStatementIndex = -1;
143471                 var newFileStatementIndex = -1;
143472                 var _loop_1 = function (ambientModuleName) {
143473                     var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; };
143474                     oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1);
143475                     newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1);
143476                     if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) {
143477                         return { value: false };
143478                     }
143479                 };
143480                 for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) {
143481                     var ambientModuleName = _a[_i];
143482                     var state_1 = _loop_1(ambientModuleName);
143483                     if (typeof state_1 === "object")
143484                         return state_1.value;
143485                 }
143486                 return true;
143487             };
143488             Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName, noRemoveResolution) {
143489                 var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName);
143490                 if (scriptInfoToDetach) {
143491                     scriptInfoToDetach.detachFromProject(this);
143492                     if (!noRemoveResolution) {
143493                         this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path);
143494                     }
143495                 }
143496             };
143497             Project.prototype.addMissingFileWatcher = function (missingFilePath) {
143498                 var _this = this;
143499                 var fileWatcher = this.projectService.watchFactory.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) {
143500                     if (isConfiguredProject(_this)) {
143501                         _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind);
143502                     }
143503                     if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) {
143504                         _this.missingFilesMap.delete(missingFilePath);
143505                         fileWatcher.close();
143506                         // When a missing file is created, we should update the graph.
143507                         _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this);
143508                     }
143509                 }, ts.PollingInterval.Medium, this.projectService.getWatchOptions(this), ts.WatchType.MissingFile, this);
143510                 return fileWatcher;
143511             };
143512             Project.prototype.isWatchedMissingFile = function (path) {
143513                 return !!this.missingFilesMap && this.missingFilesMap.has(path);
143514             };
143515             /* @internal */
143516             Project.prototype.addGeneratedFileWatch = function (generatedFile, sourceFile) {
143517                 if (this.compilerOptions.outFile || this.compilerOptions.out) {
143518                     // Single watcher
143519                     if (!this.generatedFilesMap) {
143520                         this.generatedFilesMap = this.createGeneratedFileWatcher(generatedFile);
143521                     }
143522                 }
143523                 else {
143524                     // Map
143525                     var path = this.toPath(sourceFile);
143526                     if (this.generatedFilesMap) {
143527                         if (isGeneratedFileWatcher(this.generatedFilesMap)) {
143528                             ts.Debug.fail(this.projectName + " Expected to not have --out watcher for generated file with options: " + JSON.stringify(this.compilerOptions));
143529                             return;
143530                         }
143531                         if (this.generatedFilesMap.has(path))
143532                             return;
143533                     }
143534                     else {
143535                         this.generatedFilesMap = ts.createMap();
143536                     }
143537                     this.generatedFilesMap.set(path, this.createGeneratedFileWatcher(generatedFile));
143538                 }
143539             };
143540             Project.prototype.createGeneratedFileWatcher = function (generatedFile) {
143541                 var _this = this;
143542                 return {
143543                     generatedFilePath: this.toPath(generatedFile),
143544                     watcher: this.projectService.watchFactory.watchFile(this.projectService.host, generatedFile, function () {
143545                         _this.clearSourceMapperCache();
143546                         _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this);
143547                     }, ts.PollingInterval.High, this.projectService.getWatchOptions(this), ts.WatchType.MissingGeneratedFile, this)
143548                 };
143549             };
143550             Project.prototype.isValidGeneratedFileWatcher = function (generateFile, watcher) {
143551                 return this.toPath(generateFile) === watcher.generatedFilePath;
143552             };
143553             Project.prototype.clearGeneratedFileWatch = function () {
143554                 if (this.generatedFilesMap) {
143555                     if (isGeneratedFileWatcher(this.generatedFilesMap)) {
143556                         ts.closeFileWatcherOf(this.generatedFilesMap);
143557                     }
143558                     else {
143559                         ts.clearMap(this.generatedFilesMap, ts.closeFileWatcherOf);
143560                     }
143561                     this.generatedFilesMap = undefined;
143562                 }
143563             };
143564             Project.prototype.getScriptInfoForNormalizedPath = function (fileName) {
143565                 var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName));
143566                 if (scriptInfo && !scriptInfo.isAttached(this)) {
143567                     return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this);
143568                 }
143569                 return scriptInfo;
143570             };
143571             Project.prototype.getScriptInfo = function (uncheckedFileName) {
143572                 return this.projectService.getScriptInfo(uncheckedFileName);
143573             };
143574             Project.prototype.filesToString = function (writeProjectFileNames) {
143575                 if (this.isInitialLoadPending())
143576                     return "\tFiles (0) InitialLoadPending\n";
143577                 if (!this.program)
143578                     return "\tFiles (0) NoProgram\n";
143579                 var sourceFiles = this.program.getSourceFiles();
143580                 var strBuilder = "\tFiles (" + sourceFiles.length + ")\n";
143581                 if (writeProjectFileNames) {
143582                     for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
143583                         var file = sourceFiles_1[_i];
143584                         strBuilder += "\t" + file.fileName + "\n";
143585                     }
143586                 }
143587                 return strBuilder;
143588             };
143589             /*@internal*/
143590             Project.prototype.print = function (writeProjectFileNames) {
143591                 this.writeLog("Project '" + this.projectName + "' (" + ProjectKind[this.projectKind] + ")");
143592                 this.writeLog(this.filesToString(writeProjectFileNames && this.projectService.logger.hasLevel(server.LogLevel.verbose)));
143593                 this.writeLog("-----------------------------------------------");
143594             };
143595             Project.prototype.setCompilerOptions = function (compilerOptions) {
143596                 if (compilerOptions) {
143597                     compilerOptions.allowNonTsExtensions = true;
143598                     var oldOptions = this.compilerOptions;
143599                     this.compilerOptions = compilerOptions;
143600                     this.setInternalCompilerOptionsForEmittingJsFiles();
143601                     if (ts.changesAffectModuleResolution(oldOptions, compilerOptions)) {
143602                         // reset cached unresolved imports if changes in compiler options affected module resolution
143603                         this.cachedUnresolvedImportsPerFile.clear();
143604                         this.lastCachedUnresolvedImportsList = undefined;
143605                         this.resolutionCache.clear();
143606                     }
143607                     this.markAsDirty();
143608                 }
143609             };
143610             /*@internal*/
143611             Project.prototype.setWatchOptions = function (watchOptions) {
143612                 this.watchOptions = watchOptions;
143613             };
143614             /*@internal*/
143615             Project.prototype.getWatchOptions = function () {
143616                 return this.watchOptions;
143617             };
143618             /* @internal */
143619             Project.prototype.getChangesSinceVersion = function (lastKnownVersion, includeProjectReferenceRedirectInfo) {
143620                 var _this = this;
143621                 var includeProjectReferenceRedirectInfoIfRequested = includeProjectReferenceRedirectInfo
143622                     ? function (files) { return ts.arrayFrom(files.entries(), function (_a) {
143623                         var fileName = _a[0], isSourceOfProjectReferenceRedirect = _a[1];
143624                         return ({
143625                             fileName: fileName,
143626                             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect
143627                         });
143628                     }); }
143629                     : function (files) { return ts.arrayFrom(files.keys()); };
143630                 // Update the graph only if initial configured project load is not pending
143631                 if (!this.isInitialLoadPending()) {
143632                     server.updateProjectIfDirty(this);
143633                 }
143634                 var info = {
143635                     projectName: this.getProjectName(),
143636                     version: this.projectProgramVersion,
143637                     isInferred: isInferredProject(this),
143638                     options: this.getCompilationSettings(),
143639                     languageServiceDisabled: !this.languageServiceEnabled,
143640                     lastFileExceededProgramSize: this.lastFileExceededProgramSize
143641                 };
143642                 var updatedFileNames = this.updatedFileNames;
143643                 this.updatedFileNames = undefined;
143644                 // check if requested version is the same that we have reported last time
143645                 if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
143646                     // if current structure version is the same - return info without any changes
143647                     if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) {
143648                         return { info: info, projectErrors: this.getGlobalProjectErrors() };
143649                     }
143650                     // compute and return the difference
143651                     var lastReportedFileNames_1 = this.lastReportedFileNames;
143652                     var externalFiles = this.getExternalFiles().map(function (f) { return ({
143653                         fileName: server.toNormalizedPath(f),
143654                         isSourceOfProjectReferenceRedirect: false
143655                     }); });
143656                     var currentFiles_1 = ts.arrayToMap(this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo).concat(externalFiles), function (info) { return info.fileName; }, function (info) { return info.isSourceOfProjectReferenceRedirect; });
143657                     var added_1 = new ts.Map();
143658                     var removed_1 = new ts.Map();
143659                     var updated = updatedFileNames ? ts.arrayFrom(updatedFileNames.keys()) : [];
143660                     var updatedRedirects_1 = [];
143661                     ts.forEachEntry(currentFiles_1, function (isSourceOfProjectReferenceRedirect, fileName) {
143662                         if (!lastReportedFileNames_1.has(fileName)) {
143663                             added_1.set(fileName, isSourceOfProjectReferenceRedirect);
143664                         }
143665                         else if (includeProjectReferenceRedirectInfo && isSourceOfProjectReferenceRedirect !== lastReportedFileNames_1.get(fileName)) {
143666                             updatedRedirects_1.push({
143667                                 fileName: fileName,
143668                                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect
143669                             });
143670                         }
143671                     });
143672                     ts.forEachEntry(lastReportedFileNames_1, function (isSourceOfProjectReferenceRedirect, fileName) {
143673                         if (!currentFiles_1.has(fileName)) {
143674                             removed_1.set(fileName, isSourceOfProjectReferenceRedirect);
143675                         }
143676                     });
143677                     this.lastReportedFileNames = currentFiles_1;
143678                     this.lastReportedVersion = this.projectProgramVersion;
143679                     return {
143680                         info: info,
143681                         changes: {
143682                             added: includeProjectReferenceRedirectInfoIfRequested(added_1),
143683                             removed: includeProjectReferenceRedirectInfoIfRequested(removed_1),
143684                             updated: includeProjectReferenceRedirectInfo
143685                                 ? updated.map(function (fileName) { return ({
143686                                     fileName: fileName,
143687                                     isSourceOfProjectReferenceRedirect: _this.isSourceOfProjectReferenceRedirect(fileName)
143688                                 }); })
143689                                 : updated,
143690                             updatedRedirects: includeProjectReferenceRedirectInfo ? updatedRedirects_1 : undefined
143691                         },
143692                         projectErrors: this.getGlobalProjectErrors()
143693                     };
143694                 }
143695                 else {
143696                     // unknown version - return everything
143697                     var projectFileNames = this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo);
143698                     var externalFiles = this.getExternalFiles().map(function (f) { return ({
143699                         fileName: server.toNormalizedPath(f),
143700                         isSourceOfProjectReferenceRedirect: false
143701                     }); });
143702                     var allFiles = projectFileNames.concat(externalFiles);
143703                     this.lastReportedFileNames = ts.arrayToMap(allFiles, function (info) { return info.fileName; }, function (info) { return info.isSourceOfProjectReferenceRedirect; });
143704                     this.lastReportedVersion = this.projectProgramVersion;
143705                     return {
143706                         info: info,
143707                         files: includeProjectReferenceRedirectInfo ? allFiles : allFiles.map(function (f) { return f.fileName; }),
143708                         projectErrors: this.getGlobalProjectErrors()
143709                     };
143710                 }
143711             };
143712             // remove a root file from project
143713             Project.prototype.removeRoot = function (info) {
143714                 ts.orderedRemoveItem(this.rootFiles, info);
143715                 this.rootFilesMap.delete(info.path);
143716             };
143717             /*@internal*/
143718             Project.prototype.isSourceOfProjectReferenceRedirect = function (fileName) {
143719                 return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName);
143720             };
143721             Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) {
143722                 var host = this.projectService.host;
143723                 if (!host.require) {
143724                     this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
143725                     return;
143726                 }
143727                 // Search any globally-specified probe paths, then our peer node_modules
143728                 var searchPaths = __spreadArrays(this.projectService.pluginProbeLocations, [
143729                     // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
143730                     ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."),
143731                 ]);
143732                 if (this.projectService.globalPlugins) {
143733                     var _loop_2 = function (globalPluginName) {
143734                         // Skip empty names from odd commandline parses
143735                         if (!globalPluginName)
143736                             return "continue";
143737                         // Skip already-locally-loaded plugins
143738                         if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; }))
143739                             return "continue";
143740                         // Provide global: true so plugins can detect why they can't find their config
143741                         this_1.projectService.logger.info("Loading global plugin " + globalPluginName);
143742                         this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides);
143743                     };
143744                     var this_1 = this;
143745                     // Enable global plugins with synthetic configuration entries
143746                     for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) {
143747                         var globalPluginName = _a[_i];
143748                         _loop_2(globalPluginName);
143749                     }
143750                 }
143751             };
143752             Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) {
143753                 var _this = this;
143754                 this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(","));
143755                 var log = function (message) { return _this.projectService.logger.info(message); };
143756                 var errorLogs;
143757                 var logError = function (message) { (errorLogs || (errorLogs = [])).push(message); };
143758                 var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) {
143759                     return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log, logError);
143760                 });
143761                 if (resolvedModule) {
143762                     var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name);
143763                     if (configurationOverride) {
143764                         // Preserve the name property since it's immutable
143765                         var pluginName = pluginConfigEntry.name;
143766                         pluginConfigEntry = configurationOverride;
143767                         pluginConfigEntry.name = pluginName;
143768                     }
143769                     this.enableProxy(resolvedModule, pluginConfigEntry);
143770                 }
143771                 else {
143772                     ts.forEach(errorLogs, log);
143773                     this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name);
143774                 }
143775             };
143776             Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) {
143777                 try {
143778                     if (typeof pluginModuleFactory !== "function") {
143779                         this.projectService.logger.info("Skipped loading plugin " + configEntry.name + " because it did not expose a proper factory function");
143780                         return;
143781                     }
143782                     var info = {
143783                         config: configEntry,
143784                         project: this,
143785                         languageService: this.languageService,
143786                         languageServiceHost: this,
143787                         serverHost: this.projectService.host
143788                     };
143789                     var pluginModule = pluginModuleFactory({ typescript: ts });
143790                     var newLS = pluginModule.create(info);
143791                     for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) {
143792                         var k = _a[_i];
143793                         // eslint-disable-next-line no-in-operator
143794                         if (!(k in newLS)) {
143795                             this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching.");
143796                             newLS[k] = this.languageService[k];
143797                         }
143798                     }
143799                     this.projectService.logger.info("Plugin validation succeded");
143800                     this.languageService = newLS;
143801                     this.plugins.push({ name: configEntry.name, module: pluginModule });
143802                 }
143803                 catch (e) {
143804                     this.projectService.logger.info("Plugin activation failed: " + e);
143805                 }
143806             };
143807             /*@internal*/
143808             Project.prototype.onPluginConfigurationChanged = function (pluginName, configuration) {
143809                 this.plugins.filter(function (plugin) { return plugin.name === pluginName; }).forEach(function (plugin) {
143810                     if (plugin.module.onConfigurationChanged) {
143811                         plugin.module.onConfigurationChanged(configuration);
143812                     }
143813                 });
143814             };
143815             /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */
143816             Project.prototype.refreshDiagnostics = function () {
143817                 this.projectService.sendProjectsUpdatedInBackgroundEvent();
143818             };
143819             /*@internal*/
143820             Project.prototype.getPackageJsonsVisibleToFile = function (fileName, rootDir) {
143821                 var packageJsonCache = this.packageJsonCache;
143822                 var watchPackageJsonFile = this.watchPackageJsonFile.bind(this);
143823                 var toPath = this.toPath.bind(this);
143824                 var rootPath = rootDir && toPath(rootDir);
143825                 var filePath = toPath(fileName);
143826                 var result = [];
143827                 ts.forEachAncestorDirectory(ts.getDirectoryPath(filePath), function processDirectory(directory) {
143828                     switch (packageJsonCache.directoryHasPackageJson(directory)) {
143829                         // Sync and check same directory again
143830                         case 1 /* Maybe */:
143831                             packageJsonCache.searchDirectoryAndAncestors(directory);
143832                             return processDirectory(directory);
143833                         // Check package.json
143834                         case -1 /* True */:
143835                             var packageJsonFileName = ts.combinePaths(directory, "package.json");
143836                             watchPackageJsonFile(packageJsonFileName);
143837                             var info = packageJsonCache.getInDirectory(directory);
143838                             if (info)
143839                                 result.push(info);
143840                     }
143841                     if (rootPath && rootPath === toPath(directory)) {
143842                         return true;
143843                     }
143844                 });
143845                 return result;
143846             };
143847             /*@internal*/
143848             Project.prototype.onAddPackageJson = function (path) {
143849                 this.packageJsonCache.addOrUpdate(path);
143850                 this.watchPackageJsonFile(path);
143851             };
143852             /*@internal*/
143853             Project.prototype.getImportSuggestionsCache = function () {
143854                 return this.importSuggestionsCache;
143855             };
143856             Project.prototype.watchPackageJsonFile = function (path) {
143857                 var _this = this;
143858                 var watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = ts.createMap());
143859                 if (!watchers.has(path)) {
143860                     watchers.set(path, this.projectService.watchFactory.watchFile(this.projectService.host, path, function (fileName, eventKind) {
143861                         var path = _this.toPath(fileName);
143862                         switch (eventKind) {
143863                             case ts.FileWatcherEventKind.Created:
143864                                 return ts.Debug.fail();
143865                             case ts.FileWatcherEventKind.Changed:
143866                                 _this.packageJsonCache.addOrUpdate(path);
143867                                 break;
143868                             case ts.FileWatcherEventKind.Deleted:
143869                                 _this.packageJsonCache.delete(path);
143870                                 watchers.get(path).close();
143871                                 watchers.delete(path);
143872                         }
143873                     }, ts.PollingInterval.Low, this.projectService.getWatchOptions(this), ts.WatchType.PackageJsonFile));
143874                 }
143875             };
143876             return Project;
143877         }());
143878         server.Project = Project;
143879         function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) {
143880             var ambientModules = program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); });
143881             return ts.sortAndDeduplicate(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
143882                 return extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile);
143883             }));
143884         }
143885         function extractUnresolvedImportsFromSourceFile(file, ambientModules, cachedUnresolvedImportsPerFile) {
143886             return ts.getOrUpdate(cachedUnresolvedImportsPerFile, file.path, function () {
143887                 if (!file.resolvedModules)
143888                     return server.emptyArray;
143889                 var unresolvedImports;
143890                 file.resolvedModules.forEach(function (resolvedModule, name) {
143891                     // pick unresolved non-relative names
143892                     if ((!resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) &&
143893                         !ts.isExternalModuleNameRelative(name) &&
143894                         !ambientModules.some(function (m) { return m === name; })) {
143895                         unresolvedImports = ts.append(unresolvedImports, ts.parsePackageName(name).packageName);
143896                     }
143897                 });
143898                 return unresolvedImports || server.emptyArray;
143899             });
143900         }
143901         /**
143902          * If a file is opened and no tsconfig (or jsconfig) is found,
143903          * the file and its imports/references are put into an InferredProject.
143904          */
143905         var InferredProject = /** @class */ (function (_super) {
143906             __extends(InferredProject, _super);
143907             /*@internal*/
143908             function InferredProject(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, pluginConfigOverrides) {
143909                 var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, 
143910                 // TODO: GH#18217
143911                 /*files*/ undefined, 
143912                 /*lastFileExceededProgramSize*/ undefined, compilerOptions, 
143913                 /*compileOnSaveEnabled*/ false, watchOptions, projectService.host, currentDirectory) || this;
143914                 _this._isJsInferredProject = false;
143915                 _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath);
143916                 if (!projectRootPath && !projectService.useSingleInferredProject) {
143917                     _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory);
143918                 }
143919                 _this.enableGlobalPlugins(_this.getCompilerOptions(), pluginConfigOverrides);
143920                 return _this;
143921             }
143922             InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) {
143923                 if (isJsInferredProject !== this._isJsInferredProject) {
143924                     this._isJsInferredProject = isJsInferredProject;
143925                     this.setCompilerOptions();
143926                 }
143927             };
143928             InferredProject.prototype.setCompilerOptions = function (options) {
143929                 // Avoid manipulating the given options directly
143930                 if (!options && !this.getCompilationSettings()) {
143931                     return;
143932                 }
143933                 var newOptions = ts.cloneCompilerOptions(options || this.getCompilationSettings());
143934                 if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") {
143935                     newOptions.maxNodeModuleJsDepth = 2;
143936                 }
143937                 else if (!this._isJsInferredProject) {
143938                     newOptions.maxNodeModuleJsDepth = undefined;
143939                 }
143940                 newOptions.allowJs = true;
143941                 _super.prototype.setCompilerOptions.call(this, newOptions);
143942             };
143943             InferredProject.prototype.addRoot = function (info) {
143944                 ts.Debug.assert(info.isScriptOpen());
143945                 this.projectService.startWatchingConfigFilesForInferredProjectRoot(info);
143946                 if (!this._isJsInferredProject && info.isJavaScript()) {
143947                     this.toggleJsInferredProject(/*isJsInferredProject*/ true);
143948                 }
143949                 _super.prototype.addRoot.call(this, info);
143950             };
143951             InferredProject.prototype.removeRoot = function (info) {
143952                 this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info);
143953                 _super.prototype.removeRoot.call(this, info);
143954                 if (this._isJsInferredProject && info.isJavaScript()) {
143955                     if (ts.every(this.getRootScriptInfos(), function (rootInfo) { return !rootInfo.isJavaScript(); })) {
143956                         this.toggleJsInferredProject(/*isJsInferredProject*/ false);
143957                     }
143958                 }
143959             };
143960             /*@internal*/
143961             InferredProject.prototype.isOrphan = function () {
143962                 return !this.hasRoots();
143963             };
143964             InferredProject.prototype.isProjectWithSingleRoot = function () {
143965                 // - when useSingleInferredProject is not set and projectRootPath is not set,
143966                 //   we can guarantee that this will be the only root
143967                 // - other wise it has single root if it has single root script info
143968                 return (!this.projectRootPath && !this.projectService.useSingleInferredProject) ||
143969                     this.getRootScriptInfos().length === 1;
143970             };
143971             InferredProject.prototype.close = function () {
143972                 var _this = this;
143973                 ts.forEach(this.getRootScriptInfos(), function (info) { return _this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); });
143974                 _super.prototype.close.call(this);
143975             };
143976             InferredProject.prototype.getTypeAcquisition = function () {
143977                 return {
143978                     enable: allRootFilesAreJsOrDts(this),
143979                     include: [],
143980                     exclude: []
143981                 };
143982             };
143983             InferredProject.newName = (function () {
143984                 var nextId = 1;
143985                 return function () {
143986                     var id = nextId;
143987                     nextId++;
143988                     return server.makeInferredProjectName(id);
143989                 };
143990             })();
143991             return InferredProject;
143992         }(Project));
143993         server.InferredProject = InferredProject;
143994         /**
143995          * If a file is opened, the server will look for a tsconfig (or jsconfig)
143996          * and if successful create a ConfiguredProject for it.
143997          * Otherwise it will create an InferredProject.
143998          */
143999         var ConfiguredProject = /** @class */ (function (_super) {
144000             __extends(ConfiguredProject, _super);
144001             /*@internal*/
144002             function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) {
144003                 var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, 
144004                 /*hasExplicitListOfFiles*/ false, 
144005                 /*lastFileExceededProgramSize*/ undefined, 
144006                 /*compilerOptions*/ {}, 
144007                 /*compileOnSaveEnabled*/ false, 
144008                 /*watchOptions*/ undefined, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
144009                 /* @internal */
144010                 _this.openFileWatchTriggered = ts.createMap();
144011                 /*@internal*/
144012                 _this.canConfigFileJsonReportNoInputFiles = false;
144013                 /** Ref count to the project when opened from external project */
144014                 _this.externalProjectRefCount = 0;
144015                 /*@internal*/
144016                 _this.isInitialLoadPending = ts.returnTrue;
144017                 /*@internal*/
144018                 _this.sendLoadingProjectFinish = false;
144019                 _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName));
144020                 return _this;
144021             }
144022             /* @internal */
144023             ConfiguredProject.prototype.setCompilerHost = function (host) {
144024                 this.compilerHost = host;
144025             };
144026             /* @internal */
144027             ConfiguredProject.prototype.getCompilerHost = function () {
144028                 return this.compilerHost;
144029             };
144030             /* @internal */
144031             ConfiguredProject.prototype.useSourceOfProjectReferenceRedirect = function () {
144032                 return this.languageServiceEnabled;
144033             };
144034             /* @internal */
144035             ConfiguredProject.prototype.setWatchOptions = function (watchOptions) {
144036                 var oldOptions = this.getWatchOptions();
144037                 _super.prototype.setWatchOptions.call(this, watchOptions);
144038                 // If watch options different than older options
144039                 if (this.isInitialLoadPending() &&
144040                     !ts.isJsonEqual(oldOptions, this.getWatchOptions())) {
144041                     var oldWatcher = this.configFileWatcher;
144042                     this.createConfigFileWatcher();
144043                     if (oldWatcher)
144044                         oldWatcher.close();
144045                 }
144046             };
144047             /* @internal */
144048             ConfiguredProject.prototype.createConfigFileWatcher = function () {
144049                 var _this = this;
144050                 this.configFileWatcher = this.projectService.watchFactory.watchFile(this.projectService.host, this.getConfigFilePath(), function (_fileName, eventKind) { return _this.projectService.onConfigChangedForConfiguredProject(_this, eventKind); }, ts.PollingInterval.High, this.projectService.getWatchOptions(this), ts.WatchType.ConfigFile, this);
144051             };
144052             /**
144053              * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph
144054              * @returns: true if set of files in the project stays the same and false - otherwise.
144055              */
144056             ConfiguredProject.prototype.updateGraph = function () {
144057                 this.isInitialLoadPending = ts.returnFalse;
144058                 var reloadLevel = this.pendingReload;
144059                 this.pendingReload = ts.ConfigFileProgramReloadLevel.None;
144060                 var result;
144061                 switch (reloadLevel) {
144062                     case ts.ConfigFileProgramReloadLevel.Partial:
144063                         this.openFileWatchTriggered.clear();
144064                         result = this.projectService.reloadFileNamesOfConfiguredProject(this);
144065                         break;
144066                     case ts.ConfigFileProgramReloadLevel.Full:
144067                         this.openFileWatchTriggered.clear();
144068                         var reason = ts.Debug.checkDefined(this.pendingReloadReason);
144069                         this.pendingReloadReason = undefined;
144070                         this.projectService.reloadConfiguredProject(this, reason);
144071                         result = true;
144072                         break;
144073                     default:
144074                         result = _super.prototype.updateGraph.call(this);
144075                 }
144076                 this.compilerHost = undefined;
144077                 this.projectService.sendProjectLoadingFinishEvent(this);
144078                 this.projectService.sendProjectTelemetry(this);
144079                 return result;
144080             };
144081             /*@internal*/
144082             ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () {
144083                 return this.directoryStructureHost;
144084             };
144085             ConfiguredProject.prototype.getConfigFilePath = function () {
144086                 return server.asNormalizedPath(this.getProjectName());
144087             };
144088             ConfiguredProject.prototype.getProjectReferences = function () {
144089                 return this.projectReferences;
144090             };
144091             ConfiguredProject.prototype.updateReferences = function (refs) {
144092                 this.projectReferences = refs;
144093                 this.potentialProjectReferences = undefined;
144094             };
144095             /*@internal*/
144096             ConfiguredProject.prototype.setPotentialProjectReference = function (canonicalConfigPath) {
144097                 ts.Debug.assert(this.isInitialLoadPending());
144098                 (this.potentialProjectReferences || (this.potentialProjectReferences = ts.createMap())).set(canonicalConfigPath, true);
144099             };
144100             /*@internal*/
144101             ConfiguredProject.prototype.getResolvedProjectReferenceToRedirect = function (fileName) {
144102                 var program = this.getCurrentProgram();
144103                 return program && program.getResolvedProjectReferenceToRedirect(fileName);
144104             };
144105             /*@internal*/
144106             ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) {
144107                 var host = this.projectService.host;
144108                 if (!host.require) {
144109                     this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
144110                     return;
144111                 }
144112                 // Search our peer node_modules, then any globally-specified probe paths
144113                 // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
144114                 var searchPaths = __spreadArrays([ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")], this.projectService.pluginProbeLocations);
144115                 if (this.projectService.allowLocalPluginLoads) {
144116                     var local = ts.getDirectoryPath(this.canonicalConfigFilePath);
144117                     this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths");
144118                     searchPaths.unshift(local);
144119                 }
144120                 // Enable tsconfig-specified plugins
144121                 if (options.plugins) {
144122                     for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) {
144123                         var pluginConfigEntry = _a[_i];
144124                         this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides);
144125                     }
144126                 }
144127                 this.enableGlobalPlugins(options, pluginConfigOverrides);
144128             };
144129             /**
144130              * Get the errors that dont have any file name associated
144131              */
144132             ConfiguredProject.prototype.getGlobalProjectErrors = function () {
144133                 return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray;
144134             };
144135             /**
144136              * Get all the project errors
144137              */
144138             ConfiguredProject.prototype.getAllProjectErrors = function () {
144139                 return this.projectErrors || server.emptyArray;
144140             };
144141             ConfiguredProject.prototype.setProjectErrors = function (projectErrors) {
144142                 this.projectErrors = projectErrors;
144143             };
144144             ConfiguredProject.prototype.setTypeAcquisition = function (newTypeAcquisition) {
144145                 this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition);
144146             };
144147             ConfiguredProject.prototype.getTypeAcquisition = function () {
144148                 return this.typeAcquisition;
144149             };
144150             /*@internal*/
144151             ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) {
144152                 var _this = this;
144153                 ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, 
144154                 // Create new directory watcher
144155                 function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); });
144156             };
144157             /*@internal*/
144158             ConfiguredProject.prototype.stopWatchingWildCards = function () {
144159                 if (this.directoriesWatchedForWildcards) {
144160                     ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf);
144161                     this.directoriesWatchedForWildcards = undefined;
144162                 }
144163             };
144164             ConfiguredProject.prototype.close = function () {
144165                 if (this.configFileWatcher) {
144166                     this.configFileWatcher.close();
144167                     this.configFileWatcher = undefined;
144168                 }
144169                 this.stopWatchingWildCards();
144170                 this.projectErrors = undefined;
144171                 this.configFileSpecs = undefined;
144172                 this.openFileWatchTriggered.clear();
144173                 this.compilerHost = undefined;
144174                 _super.prototype.close.call(this);
144175             };
144176             /* @internal */
144177             ConfiguredProject.prototype.addExternalProjectReference = function () {
144178                 this.externalProjectRefCount++;
144179             };
144180             /* @internal */
144181             ConfiguredProject.prototype.deleteExternalProjectReference = function () {
144182                 this.externalProjectRefCount--;
144183             };
144184             /* @internal */
144185             ConfiguredProject.prototype.isSolution = function () {
144186                 return this.getRootFilesMap().size === 0 &&
144187                     !this.canConfigFileJsonReportNoInputFiles;
144188             };
144189             /* @internal */
144190             /** Find the configured project from the project references in this solution which contains the info directly */
144191             ConfiguredProject.prototype.getDefaultChildProjectFromSolution = function (info) {
144192                 ts.Debug.assert(this.isSolution());
144193                 return server.forEachResolvedProjectReferenceProject(this, function (child) { return server.projectContainsInfoDirectly(child, info) ?
144194                     child :
144195                     undefined; }, server.ProjectReferenceProjectLoadKind.Find);
144196             };
144197             /** Returns true if the project is needed by any of the open script info/external project */
144198             /* @internal */
144199             ConfiguredProject.prototype.hasOpenRef = function () {
144200                 var _this = this;
144201                 if (!!this.externalProjectRefCount) {
144202                     return true;
144203                 }
144204                 // Closed project doesnt have any reference
144205                 if (this.isClosed()) {
144206                     return false;
144207                 }
144208                 var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this);
144209                 if (this.projectService.hasPendingProjectUpdate(this)) {
144210                     // If there is pending update for this project,
144211                     // we dont know if this project would be needed by any of the open files impacted by this config file
144212                     // In that case keep the project alive if there are open files impacted by this project
144213                     return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size;
144214                 }
144215                 var isSolution = this.isSolution();
144216                 // If there is no pending update for this project,
144217                 // We know exact set of open files that get impacted by this configured project as the files in the project
144218                 // The project is referenced only if open files impacted by this project are present in this project
144219                 return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return isSolution ?
144220                     !!_this.getDefaultChildProjectFromSolution(_this.projectService.getScriptInfoForPath(infoPath)) :
144221                     _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false;
144222             };
144223             /*@internal*/
144224             ConfiguredProject.prototype.hasExternalProjectRef = function () {
144225                 return !!this.externalProjectRefCount;
144226             };
144227             ConfiguredProject.prototype.getEffectiveTypeRoots = function () {
144228                 return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || [];
144229             };
144230             /*@internal*/
144231             ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) {
144232                 ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles);
144233             };
144234             return ConfiguredProject;
144235         }(Project));
144236         server.ConfiguredProject = ConfiguredProject;
144237         /**
144238          * Project whose configuration is handled externally, such as in a '.csproj'.
144239          * These are created only if a host explicitly calls `openExternalProject`.
144240          */
144241         var ExternalProject = /** @class */ (function (_super) {
144242             __extends(ExternalProject, _super);
144243             /*@internal*/
144244             function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, pluginConfigOverrides, watchOptions) {
144245                 var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, 
144246                 /*hasExplicitListOfFiles*/ true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this;
144247                 _this.externalProjectName = externalProjectName;
144248                 _this.compileOnSaveEnabled = compileOnSaveEnabled;
144249                 _this.excludedFiles = [];
144250                 _this.enableGlobalPlugins(_this.getCompilerOptions(), pluginConfigOverrides);
144251                 return _this;
144252             }
144253             ExternalProject.prototype.updateGraph = function () {
144254                 var result = _super.prototype.updateGraph.call(this);
144255                 this.projectService.sendProjectTelemetry(this);
144256                 return result;
144257             };
144258             ExternalProject.prototype.getExcludedFiles = function () {
144259                 return this.excludedFiles;
144260             };
144261             ExternalProject.prototype.getTypeAcquisition = function () {
144262                 return this.typeAcquisition;
144263             };
144264             ExternalProject.prototype.setTypeAcquisition = function (newTypeAcquisition) {
144265                 ts.Debug.assert(!!newTypeAcquisition, "newTypeAcquisition may not be null/undefined");
144266                 ts.Debug.assert(!!newTypeAcquisition.include, "newTypeAcquisition.include may not be null/undefined");
144267                 ts.Debug.assert(!!newTypeAcquisition.exclude, "newTypeAcquisition.exclude may not be null/undefined");
144268                 ts.Debug.assert(typeof newTypeAcquisition.enable === "boolean", "newTypeAcquisition.enable may not be null/undefined");
144269                 this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition);
144270             };
144271             return ExternalProject;
144272         }(Project));
144273         server.ExternalProject = ExternalProject;
144274         /* @internal */
144275         function isInferredProject(project) {
144276             return project.projectKind === ProjectKind.Inferred;
144277         }
144278         server.isInferredProject = isInferredProject;
144279         /* @internal */
144280         function isConfiguredProject(project) {
144281             return project.projectKind === ProjectKind.Configured;
144282         }
144283         server.isConfiguredProject = isConfiguredProject;
144284         /* @internal */
144285         function isExternalProject(project) {
144286             return project.projectKind === ProjectKind.External;
144287         }
144288         server.isExternalProject = isExternalProject;
144289     })(server = ts.server || (ts.server = {}));
144290 })(ts || (ts = {}));
144291 var ts;
144292 (function (ts) {
144293     var server;
144294     (function (server) {
144295         server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
144296         /*@internal*/
144297         server.maxFileSize = 4 * 1024 * 1024;
144298         server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
144299         server.ProjectLoadingStartEvent = "projectLoadingStart";
144300         server.ProjectLoadingFinishEvent = "projectLoadingFinish";
144301         server.LargeFileReferencedEvent = "largeFileReferenced";
144302         server.ConfigFileDiagEvent = "configFileDiag";
144303         server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
144304         server.ProjectInfoTelemetryEvent = "projectInfo";
144305         server.OpenFileInfoTelemetryEvent = "openFileInfo";
144306         function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) {
144307             var map = ts.createMap();
144308             for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) {
144309                 var option = commandLineOptions_1[_i];
144310                 if (typeof option.type === "object") {
144311                     var optionMap = option.type;
144312                     // verify that map contains only numbers
144313                     optionMap.forEach(function (value) {
144314                         ts.Debug.assert(typeof value === "number");
144315                     });
144316                     map.set(option.name, optionMap);
144317                 }
144318             }
144319             return map;
144320         }
144321         var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations);
144322         var watchOptionsConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionsForWatch);
144323         var indentStyle = ts.createMapFromTemplate({
144324             none: ts.IndentStyle.None,
144325             block: ts.IndentStyle.Block,
144326             smart: ts.IndentStyle.Smart
144327         });
144328         /**
144329          * How to understand this block:
144330          *  * The 'match' property is a regexp that matches a filename.
144331          *  * If 'match' is successful, then:
144332          *     * All files from 'exclude' are removed from the project. See below.
144333          *     * All 'types' are included in ATA
144334          *  * What the heck is 'exclude' ?
144335          *     * An array of an array of strings and numbers
144336          *     * Each array is:
144337          *       * An array of strings and numbers
144338          *       * The strings are literals
144339          *       * The numbers refer to capture group indices from the 'match' regexp
144340          *          * Remember that '1' is the first group
144341          *       * These are concatenated together to form a new regexp
144342          *       * Filenames matching these regexps are excluded from the project
144343          * This default value is tested in tsserverProjectSystem.ts; add tests there
144344          *   if you are changing this so that you can be sure your regexp works!
144345          */
144346         var defaultTypeSafeList = {
144347             "jquery": {
144348                 // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js")
144349                 match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i,
144350                 types: ["jquery"]
144351             },
144352             "WinJS": {
144353                 // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js
144354                 match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i,
144355                 exclude: [["^", 1, "/.*"]],
144356                 types: ["winjs"] // And fetch the @types package for WinJS
144357             },
144358             "Kendo": {
144359                 // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js
144360                 match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i,
144361                 exclude: [["^", 1, "/.*"]],
144362                 types: ["kendo-ui"]
144363             },
144364             "Office Nuget": {
144365                 // e.g. /scripts/Office/1/excel-15.debug.js
144366                 match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i,
144367                 exclude: [["^", 1, "/.*"]],
144368                 types: ["office"] // @types package to fetch instead
144369             },
144370             "References": {
144371                 match: /^(.*\/_references\.js)$/i,
144372                 exclude: [["^", 1, "$"]]
144373             }
144374         };
144375         function convertFormatOptions(protocolOptions) {
144376             if (ts.isString(protocolOptions.indentStyle)) {
144377                 protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase());
144378                 ts.Debug.assert(protocolOptions.indentStyle !== undefined);
144379             }
144380             return protocolOptions;
144381         }
144382         server.convertFormatOptions = convertFormatOptions;
144383         function convertCompilerOptions(protocolOptions) {
144384             compilerOptionConverters.forEach(function (mappedValues, id) {
144385                 var propertyValue = protocolOptions[id];
144386                 if (ts.isString(propertyValue)) {
144387                     protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase());
144388                 }
144389             });
144390             return protocolOptions;
144391         }
144392         server.convertCompilerOptions = convertCompilerOptions;
144393         function convertWatchOptions(protocolOptions) {
144394             var result;
144395             watchOptionsConverters.forEach(function (mappedValues, id) {
144396                 var propertyValue = protocolOptions[id];
144397                 if (propertyValue === undefined)
144398                     return;
144399                 (result || (result = {}))[id] = ts.isString(propertyValue) ?
144400                     mappedValues.get(propertyValue.toLowerCase()) :
144401                     propertyValue;
144402             });
144403             return result;
144404         }
144405         server.convertWatchOptions = convertWatchOptions;
144406         function tryConvertScriptKindName(scriptKindName) {
144407             return ts.isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName;
144408         }
144409         server.tryConvertScriptKindName = tryConvertScriptKindName;
144410         function convertScriptKindName(scriptKindName) {
144411             switch (scriptKindName) {
144412                 case "JS":
144413                     return 1 /* JS */;
144414                 case "JSX":
144415                     return 2 /* JSX */;
144416                 case "TS":
144417                     return 3 /* TS */;
144418                 case "TSX":
144419                     return 4 /* TSX */;
144420                 default:
144421                     return 0 /* Unknown */;
144422             }
144423         }
144424         server.convertScriptKindName = convertScriptKindName;
144425         /*@internal*/
144426         function convertUserPreferences(preferences) {
144427             var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]);
144428             return userPreferences;
144429         }
144430         server.convertUserPreferences = convertUserPreferences;
144431         var fileNamePropertyReader = {
144432             getFileName: function (x) { return x; },
144433             getScriptKind: function (fileName, extraFileExtensions) {
144434                 var result;
144435                 if (extraFileExtensions) {
144436                     var fileExtension_1 = ts.getAnyExtensionFromPath(fileName);
144437                     if (fileExtension_1) {
144438                         ts.some(extraFileExtensions, function (info) {
144439                             if (info.extension === fileExtension_1) {
144440                                 result = info.scriptKind;
144441                                 return true;
144442                             }
144443                             return false;
144444                         });
144445                     }
144446                 }
144447                 return result; // TODO: GH#18217
144448             },
144449             hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); },
144450         };
144451         var externalFilePropertyReader = {
144452             getFileName: function (x) { return x.fileName; },
144453             getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); },
144454             hasMixedContent: function (x) { return !!x.hasMixedContent; },
144455         };
144456         function findProjectByName(projectName, projects) {
144457             for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) {
144458                 var proj = projects_1[_i];
144459                 if (proj.getProjectName() === projectName) {
144460                     return proj;
144461                 }
144462             }
144463         }
144464         var ConfigFileWatcherStatus;
144465         (function (ConfigFileWatcherStatus) {
144466             ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files";
144467             ConfigFileWatcherStatus["ReloadingInferredRootFiles"] = "Reloading configured projects for only inferred root files";
144468             ConfigFileWatcherStatus["UpdatedCallback"] = "Updated the callback";
144469             ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileAdd"] = "File added to open files impacted by this config file";
144470             ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileRemove"] = "File removed from open files impacted by this config file";
144471             ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root";
144472             ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root";
144473         })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {}));
144474         function isOpenScriptInfo(infoOrFileNameOrConfig) {
144475             return !!infoOrFileNameOrConfig.containingProjects;
144476         }
144477         function isAncestorConfigFileInfo(infoOrFileNameOrConfig) {
144478             return !!infoOrFileNameOrConfig.configFileInfo;
144479         }
144480         /*@internal*/
144481         /** Kind of operation to perform to get project reference project */
144482         var ProjectReferenceProjectLoadKind;
144483         (function (ProjectReferenceProjectLoadKind) {
144484             /** Find existing project for project reference */
144485             ProjectReferenceProjectLoadKind[ProjectReferenceProjectLoadKind["Find"] = 0] = "Find";
144486             /** Find existing project or create one for the project reference */
144487             ProjectReferenceProjectLoadKind[ProjectReferenceProjectLoadKind["FindCreate"] = 1] = "FindCreate";
144488             /** Find existing project or create and load it for the project reference */
144489             ProjectReferenceProjectLoadKind[ProjectReferenceProjectLoadKind["FindCreateLoad"] = 2] = "FindCreateLoad";
144490         })(ProjectReferenceProjectLoadKind = server.ProjectReferenceProjectLoadKind || (server.ProjectReferenceProjectLoadKind = {}));
144491         function forEachResolvedProjectReferenceProject(project, cb, projectReferenceProjectLoadKind, reason) {
144492             return forEachResolvedProjectReference(project, function (ref) {
144493                 if (!ref)
144494                     return undefined;
144495                 var configFileName = server.toNormalizedPath(ref.sourceFile.fileName);
144496                 var child = project.projectService.findConfiguredProjectByProjectName(configFileName) || (projectReferenceProjectLoadKind === ProjectReferenceProjectLoadKind.FindCreate ?
144497                     project.projectService.createConfiguredProject(configFileName) :
144498                     projectReferenceProjectLoadKind === ProjectReferenceProjectLoadKind.FindCreateLoad ?
144499                         project.projectService.createAndLoadConfiguredProject(configFileName, reason) :
144500                         undefined);
144501                 return child && cb(child, configFileName);
144502             });
144503         }
144504         server.forEachResolvedProjectReferenceProject = forEachResolvedProjectReferenceProject;
144505         /*@internal*/
144506         function forEachResolvedProjectReference(project, cb) {
144507             var program = project.getCurrentProgram();
144508             return program && program.forEachResolvedProjectReference(cb);
144509         }
144510         server.forEachResolvedProjectReference = forEachResolvedProjectReference;
144511         function forEachPotentialProjectReference(project, cb) {
144512             return project.potentialProjectReferences &&
144513                 ts.forEachKey(project.potentialProjectReferences, cb);
144514         }
144515         function forEachAnyProjectReferenceKind(project, cb, cbProjectRef, cbPotentialProjectRef) {
144516             return project.getCurrentProgram() ?
144517                 forEachResolvedProjectReference(project, cb) :
144518                 project.isInitialLoadPending() ?
144519                     forEachPotentialProjectReference(project, cbPotentialProjectRef) :
144520                     ts.forEach(project.getProjectReferences(), cbProjectRef);
144521         }
144522         function callbackRefProject(project, cb, refPath) {
144523             var refProject = refPath && project.projectService.configuredProjects.get(refPath);
144524             return refProject && cb(refProject);
144525         }
144526         function forEachReferencedProject(project, cb) {
144527             return forEachAnyProjectReferenceKind(project, function (resolvedRef) { return callbackRefProject(project, cb, resolvedRef && resolvedRef.sourceFile.path); }, function (projectRef) { return callbackRefProject(project, cb, project.toPath(projectRef.path)); }, function (potentialProjectRef) { return callbackRefProject(project, cb, potentialProjectRef); });
144528         }
144529         function getDetailWatchInfo(watchType, project) {
144530             return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType;
144531         }
144532         function isScriptInfoWatchedFromNodeModules(info) {
144533             return !info.isScriptOpen() && info.mTime !== undefined;
144534         }
144535         /*@internal*/
144536         /** true if script info is part of project and is not in project because it is referenced from project reference source */
144537         function projectContainsInfoDirectly(project, info) {
144538             return project.containsScriptInfo(info) &&
144539                 !project.isSourceOfProjectReferenceRedirect(info.path);
144540         }
144541         server.projectContainsInfoDirectly = projectContainsInfoDirectly;
144542         /*@internal*/
144543         function updateProjectIfDirty(project) {
144544             return project.dirty && project.updateGraph();
144545         }
144546         server.updateProjectIfDirty = updateProjectIfDirty;
144547         function setProjectOptionsUsed(project) {
144548             if (server.isConfiguredProject(project)) {
144549                 project.projectOptions = true;
144550             }
144551         }
144552         var ProjectService = /** @class */ (function () {
144553             function ProjectService(opts) {
144554                 var _this = this;
144555                 /**
144556                  * Container of all known scripts
144557                  */
144558                 /*@internal*/
144559                 this.filenameToScriptInfo = ts.createMap();
144560                 this.scriptInfoInNodeModulesWatchers = ts.createMap();
144561                 /**
144562                  * Contains all the deleted script info's version information so that
144563                  * it does not reset when creating script info again
144564                  * (and could have potentially collided with version where contents mismatch)
144565                  */
144566                 this.filenameToScriptInfoVersion = ts.createMap();
144567                 // Set of all '.js' files ever opened.
144568                 this.allJsFilesForOpenFileTelemetry = ts.createMap();
144569                 /**
144570                  * maps external project file name to list of config files that were the part of this project
144571                  */
144572                 this.externalProjectToConfiguredProjectMap = ts.createMap();
144573                 /**
144574                  * external projects (configuration and list of root files is not controlled by tsserver)
144575                  */
144576                 this.externalProjects = [];
144577                 /**
144578                  * projects built from openFileRoots
144579                  */
144580                 this.inferredProjects = [];
144581                 /**
144582                  * projects specified by a tsconfig.json file
144583                  */
144584                 this.configuredProjects = ts.createMap();
144585                 /**
144586                  * Open files: with value being project root path, and key being Path of the file that is open
144587                  */
144588                 this.openFiles = ts.createMap();
144589                 /**
144590                  * Map of open files that are opened without complete path but have projectRoot as current directory
144591                  */
144592                 this.openFilesWithNonRootedDiskPath = ts.createMap();
144593                 this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap();
144594                 this.watchOptionsForInferredProjectsPerProjectRoot = ts.createMap();
144595                 /**
144596                  * Project size for configured or external projects
144597                  */
144598                 this.projectToSizeMap = ts.createMap();
144599                 /**
144600                  * This is a map of config file paths existence that doesnt need query to disk
144601                  * - The entry can be present because there is inferred project that needs to watch addition of config file to directory
144602                  *   In this case the exists could be true/false based on config file is present or not
144603                  * - Or it is present if we have configured project open with config file at that location
144604                  *   In this case the exists property is always true
144605                  */
144606                 this.configFileExistenceInfoCache = ts.createMap();
144607                 this.safelist = defaultTypeSafeList;
144608                 this.legacySafelist = ts.createMap();
144609                 this.pendingProjectUpdates = ts.createMap();
144610                 /* @internal */
144611                 this.pendingEnsureProjectForOpenFiles = false;
144612                 /** Tracks projects that we have already sent telemetry for. */
144613                 this.seenProjects = ts.createMap();
144614                 this.host = opts.host;
144615                 this.logger = opts.logger;
144616                 this.cancellationToken = opts.cancellationToken;
144617                 this.useSingleInferredProject = opts.useSingleInferredProject;
144618                 this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot;
144619                 this.typingsInstaller = opts.typingsInstaller || server.nullTypingsInstaller;
144620                 this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds;
144621                 this.eventHandler = opts.eventHandler;
144622                 this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents;
144623                 this.globalPlugins = opts.globalPlugins || server.emptyArray;
144624                 this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray;
144625                 this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads;
144626                 this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation;
144627                 this.syntaxOnly = opts.syntaxOnly;
144628                 ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService");
144629                 if (this.host.realpath) {
144630                     this.realpathToScriptInfos = ts.createMultiMap();
144631                 }
144632                 this.currentDirectory = server.toNormalizedPath(this.host.getCurrentDirectory());
144633                 this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
144634                 this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation
144635                     ? ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation))
144636                     : undefined;
144637                 this.throttledOperations = new server.ThrottledOperations(this.host, this.logger);
144638                 if (this.typesMapLocation) {
144639                     this.loadTypesMap();
144640                 }
144641                 else {
144642                     this.logger.info("No types map provided; using the default");
144643                 }
144644                 this.typingsInstaller.attach(this);
144645                 this.typingsCache = new server.TypingsCache(this.typingsInstaller);
144646                 this.hostConfiguration = {
144647                     formatCodeOptions: ts.getDefaultFormatCodeSettings(this.host.newLine),
144648                     preferences: ts.emptyOptions,
144649                     hostInfo: "Unknown host",
144650                     extraFileExtensions: [],
144651                 };
144652                 this.documentRegistry = ts.createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this);
144653                 var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose :
144654                     this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None;
144655                 var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop;
144656                 this.watchFactory = ts.getWatchFactory(watchLogLevel, log, getDetailWatchInfo);
144657             }
144658             ProjectService.prototype.toPath = function (fileName) {
144659                 return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName);
144660             };
144661             /*@internal*/
144662             ProjectService.prototype.getExecutingFilePath = function () {
144663                 return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath());
144664             };
144665             /*@internal*/
144666             ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) {
144667                 return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory());
144668             };
144669             /*@internal*/
144670             ProjectService.prototype.setDocument = function (key, path, sourceFile) {
144671                 var info = ts.Debug.checkDefined(this.getScriptInfoForPath(path));
144672                 info.cacheSourceFile = { key: key, sourceFile: sourceFile };
144673             };
144674             /*@internal*/
144675             ProjectService.prototype.getDocument = function (key, path) {
144676                 var info = this.getScriptInfoForPath(path);
144677                 return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : undefined;
144678             };
144679             /* @internal */
144680             ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () {
144681                 this.ensureProjectStructuresUptoDate();
144682             };
144683             /* @internal */
144684             ProjectService.prototype.getCompilerOptionsForInferredProjects = function () {
144685                 return this.compilerOptionsForInferredProjects;
144686             };
144687             /* @internal */
144688             ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) {
144689                 if (!this.eventHandler) {
144690                     return;
144691                 }
144692                 var event = {
144693                     eventName: server.ProjectLanguageServiceStateEvent,
144694                     data: { project: project, languageServiceEnabled: languageServiceEnabled }
144695                 };
144696                 this.eventHandler(event);
144697             };
144698             ProjectService.prototype.loadTypesMap = function () {
144699                 try {
144700                     var fileContent = this.host.readFile(this.typesMapLocation); // TODO: GH#18217
144701                     if (fileContent === undefined) {
144702                         this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist");
144703                         return;
144704                     }
144705                     var raw = JSON.parse(fileContent);
144706                     // Parse the regexps
144707                     for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) {
144708                         var k = _a[_i];
144709                         raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i");
144710                     }
144711                     // raw is now fixed and ready
144712                     this.safelist = raw.typesMap;
144713                     for (var key in raw.simpleMap) {
144714                         if (raw.simpleMap.hasOwnProperty(key)) {
144715                             this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase());
144716                         }
144717                     }
144718                 }
144719                 catch (e) {
144720                     this.logger.info("Error loading types map: " + e);
144721                     this.safelist = defaultTypeSafeList;
144722                     this.legacySafelist.clear();
144723                 }
144724             };
144725             ProjectService.prototype.updateTypingsForProject = function (response) {
144726                 var project = this.findProject(response.projectName);
144727                 if (!project) {
144728                     return;
144729                 }
144730                 switch (response.kind) {
144731                     case server.ActionSet:
144732                         // Update the typing files and update the project
144733                         project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings));
144734                         break;
144735                     case server.ActionInvalidate:
144736                         // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results
144737                         this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true);
144738                         return;
144739                 }
144740                 this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
144741             };
144742             ProjectService.prototype.delayEnsureProjectForOpenFiles = function () {
144743                 var _this = this;
144744                 this.pendingEnsureProjectForOpenFiles = true;
144745                 this.throttledOperations.schedule("*ensureProjectForOpenFiles*", /*delay*/ 2500, function () {
144746                     if (_this.pendingProjectUpdates.size !== 0) {
144747                         _this.delayEnsureProjectForOpenFiles();
144748                     }
144749                     else {
144750                         if (_this.pendingEnsureProjectForOpenFiles) {
144751                             _this.ensureProjectForOpenFiles();
144752                             // Send the event to notify that there were background project updates
144753                             // send current list of open files
144754                             _this.sendProjectsUpdatedInBackgroundEvent();
144755                         }
144756                     }
144757                 });
144758             };
144759             ProjectService.prototype.delayUpdateProjectGraph = function (project) {
144760                 var _this = this;
144761                 project.markAsDirty();
144762                 var projectName = project.getProjectName();
144763                 this.pendingProjectUpdates.set(projectName, project);
144764                 this.throttledOperations.schedule(projectName, /*delay*/ 250, function () {
144765                     if (_this.pendingProjectUpdates.delete(projectName)) {
144766                         updateProjectIfDirty(project);
144767                     }
144768                 });
144769             };
144770             /*@internal*/
144771             ProjectService.prototype.hasPendingProjectUpdate = function (project) {
144772                 return this.pendingProjectUpdates.has(project.getProjectName());
144773             };
144774             /* @internal */
144775             ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () {
144776                 var _this = this;
144777                 if (!this.eventHandler) {
144778                     return;
144779                 }
144780                 var event = {
144781                     eventName: server.ProjectsUpdatedInBackgroundEvent,
144782                     data: {
144783                         openFiles: ts.arrayFrom(this.openFiles.keys(), function (path) { return _this.getScriptInfoForPath(path).fileName; })
144784                     }
144785                 };
144786                 this.eventHandler(event);
144787             };
144788             /* @internal */
144789             ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) {
144790                 if (!this.eventHandler) {
144791                     return;
144792                 }
144793                 var event = {
144794                     eventName: server.LargeFileReferencedEvent,
144795                     data: { file: file, fileSize: fileSize, maxFileSize: server.maxFileSize }
144796                 };
144797                 this.eventHandler(event);
144798             };
144799             /* @internal */
144800             ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) {
144801                 if (!this.eventHandler) {
144802                     return;
144803                 }
144804                 project.sendLoadingProjectFinish = true;
144805                 var event = {
144806                     eventName: server.ProjectLoadingStartEvent,
144807                     data: { project: project, reason: reason }
144808                 };
144809                 this.eventHandler(event);
144810             };
144811             /* @internal */
144812             ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) {
144813                 if (!this.eventHandler || !project.sendLoadingProjectFinish) {
144814                     return;
144815                 }
144816                 project.sendLoadingProjectFinish = false;
144817                 var event = {
144818                     eventName: server.ProjectLoadingFinishEvent,
144819                     data: { project: project }
144820                 };
144821                 this.eventHandler(event);
144822             };
144823             /* @internal */
144824             ProjectService.prototype.sendUpdateGraphPerformanceEvent = function (durationMs) {
144825                 if (this.performanceEventHandler) {
144826                     this.performanceEventHandler({ kind: "UpdateGraph", durationMs: durationMs });
144827                 }
144828             };
144829             /* @internal */
144830             ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) {
144831                 this.delayUpdateProjectGraph(project);
144832                 this.delayEnsureProjectForOpenFiles();
144833             };
144834             ProjectService.prototype.delayUpdateProjectGraphs = function (projects, clearSourceMapperCache) {
144835                 if (projects.length) {
144836                     for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) {
144837                         var project = projects_2[_i];
144838                         // Even if program doesnt change, clear the source mapper cache
144839                         if (clearSourceMapperCache)
144840                             project.clearSourceMapperCache();
144841                         this.delayUpdateProjectGraph(project);
144842                     }
144843                     this.delayEnsureProjectForOpenFiles();
144844                 }
144845             };
144846             ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) {
144847                 ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled");
144848                 var compilerOptions = convertCompilerOptions(projectCompilerOptions);
144849                 var watchOptions = convertWatchOptions(projectCompilerOptions);
144850                 // always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside
144851                 // previously we did not expose a way for user to change these settings and this option was enabled by default
144852                 compilerOptions.allowNonTsExtensions = true;
144853                 var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath);
144854                 if (canonicalProjectRootPath) {
144855                     this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions);
144856                     this.watchOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, watchOptions || false);
144857                 }
144858                 else {
144859                     this.compilerOptionsForInferredProjects = compilerOptions;
144860                     this.watchOptionsForInferredProjects = watchOptions;
144861                 }
144862                 for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
144863                     var project = _a[_i];
144864                     // Only update compiler options in the following cases:
144865                     // - Inferred projects without a projectRootPath, if the new options do not apply to
144866                     //   a workspace root
144867                     // - Inferred projects with a projectRootPath, if the new options do not apply to a
144868                     //   workspace root and there is no more specific set of options for that project's
144869                     //   root path
144870                     // - Inferred projects with a projectRootPath, if the new options apply to that
144871                     //   project root path.
144872                     if (canonicalProjectRootPath ?
144873                         project.projectRootPath === canonicalProjectRootPath :
144874                         !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) {
144875                         project.setCompilerOptions(compilerOptions);
144876                         project.setWatchOptions(watchOptions);
144877                         project.compileOnSaveEnabled = compilerOptions.compileOnSave;
144878                         project.markAsDirty();
144879                         this.delayUpdateProjectGraph(project);
144880                     }
144881                 }
144882                 this.delayEnsureProjectForOpenFiles();
144883             };
144884             ProjectService.prototype.findProject = function (projectName) {
144885                 if (projectName === undefined) {
144886                     return undefined;
144887                 }
144888                 if (server.isInferredProjectName(projectName)) {
144889                     return findProjectByName(projectName, this.inferredProjects);
144890                 }
144891                 return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName));
144892             };
144893             /* @internal */
144894             ProjectService.prototype.forEachProject = function (cb) {
144895                 this.externalProjects.forEach(cb);
144896                 this.configuredProjects.forEach(cb);
144897                 this.inferredProjects.forEach(cb);
144898             };
144899             /* @internal */
144900             ProjectService.prototype.forEachEnabledProject = function (cb) {
144901                 this.forEachProject(function (project) {
144902                     if (!project.isOrphan() && project.languageServiceEnabled) {
144903                         cb(project);
144904                     }
144905                 });
144906             };
144907             ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) {
144908                 return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName);
144909             };
144910             /* @internal */
144911             ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) {
144912                 var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
144913                 return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined;
144914             };
144915             /* @internal */
144916             ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) {
144917                 return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName);
144918             };
144919             ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) {
144920                 this.ensureProjectStructuresUptoDate();
144921                 var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
144922                 return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), server.Errors.ThrowNoProject());
144923             };
144924             ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) {
144925                 this.ensureProjectStructuresUptoDate();
144926                 return this.getScriptInfo(uncheckedFileName);
144927             };
144928             /**
144929              * Ensures the project structures are upto date
144930              * This means,
144931              * - we go through all the projects and update them if they are dirty
144932              * - if updates reflect some change in structure or there was pending request to ensure projects for open files
144933              *   ensure that each open script info has project
144934              */
144935             ProjectService.prototype.ensureProjectStructuresUptoDate = function () {
144936                 var hasChanges = this.pendingEnsureProjectForOpenFiles;
144937                 this.pendingProjectUpdates.clear();
144938                 var updateGraph = function (project) {
144939                     hasChanges = updateProjectIfDirty(project) || hasChanges;
144940                 };
144941                 this.externalProjects.forEach(updateGraph);
144942                 this.configuredProjects.forEach(updateGraph);
144943                 this.inferredProjects.forEach(updateGraph);
144944                 if (hasChanges) {
144945                     this.ensureProjectForOpenFiles();
144946                 }
144947             };
144948             ProjectService.prototype.getFormatCodeOptions = function (file) {
144949                 var info = this.getScriptInfoForNormalizedPath(file);
144950                 return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions;
144951             };
144952             ProjectService.prototype.getPreferences = function (file) {
144953                 var info = this.getScriptInfoForNormalizedPath(file);
144954                 return __assign(__assign({}, this.hostConfiguration.preferences), info && info.getPreferences());
144955             };
144956             ProjectService.prototype.getHostFormatCodeOptions = function () {
144957                 return this.hostConfiguration.formatCodeOptions;
144958             };
144959             ProjectService.prototype.getHostPreferences = function () {
144960                 return this.hostConfiguration.preferences;
144961             };
144962             ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind, path) {
144963                 var info = this.getScriptInfoForPath(path);
144964                 if (!info) {
144965                     this.logger.msg("Error: got watch notification for unknown file: " + fileName);
144966                 }
144967                 else {
144968                     if (info.containingProjects) {
144969                         info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); });
144970                     }
144971                     if (eventKind === ts.FileWatcherEventKind.Deleted) {
144972                         // File was deleted
144973                         this.handleDeletedFile(info);
144974                     }
144975                     else if (!info.isScriptOpen()) {
144976                         // file has been changed which might affect the set of referenced files in projects that include
144977                         // this file and set of inferred projects
144978                         info.delayReloadNonMixedContentFile();
144979                         this.delayUpdateProjectGraphs(info.containingProjects, /*clearSourceMapperCache*/ false);
144980                         this.handleSourceMapProjects(info);
144981                     }
144982                 }
144983             };
144984             ProjectService.prototype.handleSourceMapProjects = function (info) {
144985                 // Change in d.ts, update source projects as well
144986                 if (info.sourceMapFilePath) {
144987                     if (ts.isString(info.sourceMapFilePath)) {
144988                         var sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
144989                         this.delayUpdateSourceInfoProjects(sourceMapFileInfo && sourceMapFileInfo.sourceInfos);
144990                     }
144991                     else {
144992                         this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos);
144993                     }
144994                 }
144995                 // Change in mapInfo, update declarationProjects and source projects
144996                 this.delayUpdateSourceInfoProjects(info.sourceInfos);
144997                 if (info.declarationInfoPath) {
144998                     this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath);
144999                 }
145000             };
145001             ProjectService.prototype.delayUpdateSourceInfoProjects = function (sourceInfos) {
145002                 var _this = this;
145003                 if (sourceInfos) {
145004                     sourceInfos.forEach(function (_value, path) { return _this.delayUpdateProjectsOfScriptInfoPath(path); });
145005                 }
145006             };
145007             ProjectService.prototype.delayUpdateProjectsOfScriptInfoPath = function (path) {
145008                 var info = this.getScriptInfoForPath(path);
145009                 if (info) {
145010                     this.delayUpdateProjectGraphs(info.containingProjects, /*clearSourceMapperCache*/ true);
145011                 }
145012             };
145013             ProjectService.prototype.handleDeletedFile = function (info) {
145014                 this.stopWatchingScriptInfo(info);
145015                 if (!info.isScriptOpen()) {
145016                     this.deleteScriptInfo(info);
145017                     // capture list of projects since detachAllProjects will wipe out original list
145018                     var containingProjects = info.containingProjects.slice();
145019                     info.detachAllProjects();
145020                     // update projects to make sure that set of referenced files is correct
145021                     this.delayUpdateProjectGraphs(containingProjects, /*clearSourceMapperCache*/ false);
145022                     this.handleSourceMapProjects(info);
145023                     info.closeSourceMapFileWatcher();
145024                     // need to recalculate source map from declaration file
145025                     if (info.declarationInfoPath) {
145026                         var declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath);
145027                         if (declarationInfo) {
145028                             declarationInfo.sourceMapFilePath = undefined;
145029                         }
145030                     }
145031                 }
145032             };
145033             /**
145034              * This is to watch whenever files are added or removed to the wildcard directories
145035              */
145036             /*@internal*/
145037             ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) {
145038                 var _this = this;
145039                 return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) {
145040                     var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
145041                     var fsResult = project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
145042                     // don't trigger callback on open, existing files
145043                     if (project.fileIsOpen(fileOrDirectoryPath)) {
145044                         if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) {
145045                             var info = ts.Debug.checkDefined(_this.getScriptInfoForPath(fileOrDirectoryPath));
145046                             if (info.isAttached(project)) {
145047                                 project.openFileWatchTriggered.set(fileOrDirectoryPath, true);
145048                             }
145049                             else {
145050                                 project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial;
145051                                 _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
145052                             }
145053                         }
145054                         return;
145055                     }
145056                     fileOrDirectoryPath = ts.removeIgnoredPath(fileOrDirectoryPath);
145057                     if (!fileOrDirectoryPath)
145058                         return;
145059                     var configFilename = project.getConfigFilePath();
145060                     if (ts.getBaseFileName(fileOrDirectoryPath) === "package.json" && !ts.isInsideNodeModules(fileOrDirectoryPath) &&
145061                         (fsResult && fsResult.fileExists || !fsResult && _this.host.fileExists(fileOrDirectoryPath))) {
145062                         _this.logger.info("Project: " + configFilename + " Detected new package.json: " + fileOrDirectory);
145063                         project.onAddPackageJson(fileOrDirectoryPath);
145064                     }
145065                     // If the the added or created file or directory is not supported file name, ignore the file
145066                     // But when watched directory is added/removed, we need to reload the file list
145067                     if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) {
145068                         _this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory);
145069                         return;
145070                     }
145071                     // Reload is pending, do the reload
145072                     if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) {
145073                         project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial;
145074                         _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
145075                     }
145076                 }, flags, this.getWatchOptions(project), ts.WatchType.WildcardDirectory, project);
145077             };
145078             /** Gets the config file existence info for the configured project */
145079             /*@internal*/
145080             ProjectService.prototype.getConfigFileExistenceInfo = function (project) {
145081                 return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath);
145082             };
145083             /*@internal*/
145084             ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) {
145085                 var configFileExistenceInfo = this.getConfigFileExistenceInfo(project);
145086                 if (eventKind === ts.FileWatcherEventKind.Deleted) {
145087                     // Update the cached status
145088                     // We arent updating or removing the cached config file presence info as that will be taken care of by
145089                     // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files)
145090                     configFileExistenceInfo.exists = false;
145091                     this.removeProject(project);
145092                     // Reload the configured projects for the open files in the map as they are affected by this config file
145093                     // Since the configured project was deleted, we want to reload projects for all the open files including files
145094                     // that are not root of the inferred project
145095                     this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */);
145096                     this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false);
145097                 }
145098                 else {
145099                     this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */);
145100                     // Skip refresh if project is not yet loaded
145101                     if (project.isInitialLoadPending())
145102                         return;
145103                     project.pendingReload = ts.ConfigFileProgramReloadLevel.Full;
145104                     project.pendingReloadReason = "Change in config file detected";
145105                     this.delayUpdateProjectGraph(project);
145106                     // As we scheduled the update on configured project graph,
145107                     // we would need to schedule the project reload for only the root of inferred projects
145108                     this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true);
145109                 }
145110             };
145111             /**
145112              * This is the callback function for the config file add/remove/change at any location
145113              * that matters to open script info but doesnt have configured project open
145114              * for the config file
145115              */
145116             ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) {
145117                 // This callback is called only if we dont have config file project for this config file
145118                 var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName);
145119                 var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath);
145120                 configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted);
145121                 this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */);
145122                 // Because there is no configured project open for the config file, the tracking open files map
145123                 // will only have open files that need the re-detection of the project and hence
145124                 // reload projects for all the tracking open files in the map
145125                 this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false);
145126             };
145127             ProjectService.prototype.removeProject = function (project) {
145128                 var _this = this;
145129                 this.logger.info("`remove Project::");
145130                 project.print(/*writeProjectFileNames*/ true);
145131                 project.close();
145132                 if (ts.Debug.shouldAssert(1 /* Normal */)) {
145133                     this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project), "Found script Info still attached to project", function () { return project.projectName + ": ScriptInfos still attached: " + JSON.stringify(ts.arrayFrom(ts.mapDefinedIterator(_this.filenameToScriptInfo.values(), function (info) { return info.isAttached(project) ?
145134                         {
145135                             fileName: info.fileName,
145136                             projects: info.containingProjects.map(function (p) { return p.projectName; }),
145137                             hasMixedContent: info.hasMixedContent
145138                         } : undefined; })), 
145139                     /*replacer*/ undefined, " "); }); });
145140                 }
145141                 // Remove the project from pending project updates
145142                 this.pendingProjectUpdates.delete(project.getProjectName());
145143                 switch (project.projectKind) {
145144                     case server.ProjectKind.External:
145145                         ts.unorderedRemoveItem(this.externalProjects, project);
145146                         this.projectToSizeMap.delete(project.getProjectName());
145147                         break;
145148                     case server.ProjectKind.Configured:
145149                         this.configuredProjects.delete(project.canonicalConfigFilePath);
145150                         this.projectToSizeMap.delete(project.canonicalConfigFilePath);
145151                         this.setConfigFileExistenceInfoByClosedConfiguredProject(project);
145152                         break;
145153                     case server.ProjectKind.Inferred:
145154                         ts.unorderedRemoveItem(this.inferredProjects, project);
145155                         break;
145156                 }
145157             };
145158             /*@internal*/
145159             ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) {
145160                 ts.Debug.assert(info.isOrphan());
145161                 var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) ||
145162                     this.getOrCreateSingleInferredProjectIfEnabled() ||
145163                     this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ?
145164                         projectRootPath || this.currentDirectory :
145165                         ts.getDirectoryPath(ts.isRootedDiskPath(info.fileName) ?
145166                             info.fileName :
145167                             ts.getNormalizedAbsolutePath(info.fileName, projectRootPath ?
145168                                 this.getNormalizedAbsolutePath(projectRootPath) :
145169                                 this.currentDirectory)));
145170                 project.addRoot(info);
145171                 if (info.containingProjects[0] !== project) {
145172                     // Ensure this is first project, we could be in this scenario because info could be part of orphan project
145173                     info.detachFromProject(project);
145174                     info.containingProjects.unshift(project);
145175                 }
145176                 project.updateGraph();
145177                 if (!this.useSingleInferredProject && !project.projectRootPath) {
145178                     var _loop_3 = function (inferredProject) {
145179                         if (inferredProject === project || inferredProject.isOrphan()) {
145180                             return "continue";
145181                         }
145182                         // Remove the inferred project if the root of it is now part of newly created inferred project
145183                         // e.g through references
145184                         // Which means if any root of inferred project is part of more than 1 project can be removed
145185                         // This logic is same as iterating over all open files and calling
145186                         // this.removeRootOfInferredProjectIfNowPartOfOtherProject(f);
145187                         // Since this is also called from refreshInferredProject and closeOpen file
145188                         // to update inferred projects of the open file, this iteration might be faster
145189                         // instead of scanning all open files
145190                         var roots = inferredProject.getRootScriptInfos();
145191                         ts.Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath);
145192                         if (roots.length === 1 && ts.forEach(roots[0].containingProjects, function (p) { return p !== roots[0].containingProjects[0] && !p.isOrphan(); })) {
145193                             inferredProject.removeFile(roots[0], /*fileExists*/ true, /*detachFromProject*/ true);
145194                         }
145195                     };
145196                     // Note that we need to create a copy of the array since the list of project can change
145197                     for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
145198                         var inferredProject = _a[_i];
145199                         _loop_3(inferredProject);
145200                     }
145201                 }
145202                 return project;
145203             };
145204             ProjectService.prototype.assignOrphanScriptInfosToInferredProject = function () {
145205                 var _this = this;
145206                 // collect orphaned files and assign them to inferred project just like we treat open of a file
145207                 this.openFiles.forEach(function (projectRootPath, path) {
145208                     var info = _this.getScriptInfoForPath(path);
145209                     // collect all orphaned script infos from open files
145210                     if (info.isOrphan()) {
145211                         _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
145212                     }
145213                 });
145214             };
145215             /**
145216              * Remove this file from the set of open, non-configured files.
145217              * @param info The file that has been closed or newly configured
145218              */
145219             ProjectService.prototype.closeOpenFile = function (info, skipAssignOrphanScriptInfosToInferredProject) {
145220                 // Closing file should trigger re-reading the file content from disk. This is
145221                 // because the user may chose to discard the buffer content before saving
145222                 // to the disk, and the server's version of the file can be out of sync.
145223                 var fileExists = info.isDynamic ? false : this.host.fileExists(info.fileName);
145224                 info.close(fileExists);
145225                 this.stopWatchingConfigFilesForClosedScriptInfo(info);
145226                 var canonicalFileName = this.toCanonicalFileName(info.fileName);
145227                 if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) {
145228                     this.openFilesWithNonRootedDiskPath.delete(canonicalFileName);
145229                 }
145230                 // collect all projects that should be removed
145231                 var ensureProjectsForOpenFiles = false;
145232                 for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) {
145233                     var p = _a[_i];
145234                     if (server.isConfiguredProject(p)) {
145235                         if (info.hasMixedContent) {
145236                             info.registerFileUpdate();
145237                         }
145238                         // Do not remove the project so that we can reuse this project
145239                         // if it would need to be re-created with next file open
145240                         // If project had open file affecting
145241                         // Reload the root Files from config if its not already scheduled
145242                         if (p.openFileWatchTriggered.has(info.path)) {
145243                             p.openFileWatchTriggered.delete(info.path);
145244                             if (!p.pendingReload) {
145245                                 p.pendingReload = ts.ConfigFileProgramReloadLevel.Partial;
145246                                 p.markFileAsDirty(info.path);
145247                             }
145248                         }
145249                     }
145250                     else if (server.isInferredProject(p) && p.isRoot(info)) {
145251                         // If this was the last open root file of inferred project
145252                         if (p.isProjectWithSingleRoot()) {
145253                             ensureProjectsForOpenFiles = true;
145254                         }
145255                         p.removeFile(info, fileExists, /*detachFromProject*/ true);
145256                         // Do not remove the project even if this was last root of the inferred project
145257                         // so that we can reuse this project, if it would need to be re-created with next file open
145258                     }
145259                     if (!p.languageServiceEnabled) {
145260                         // if project language service is disabled then we create a program only for open files.
145261                         // this means that project should be marked as dirty to force rebuilding of the program
145262                         // on the next request
145263                         p.markAsDirty();
145264                     }
145265                 }
145266                 this.openFiles.delete(info.path);
145267                 if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
145268                     this.assignOrphanScriptInfosToInferredProject();
145269                 }
145270                 // Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project)
145271                 // is postponed to next file open so that if file from same project is opened,
145272                 // we wont end up creating same script infos
145273                 // If the current info is being just closed - add the watcher file to track changes
145274                 // But if file was deleted, handle that part
145275                 if (fileExists) {
145276                     this.watchClosedScriptInfo(info);
145277                 }
145278                 else {
145279                     this.handleDeletedFile(info);
145280                 }
145281                 return ensureProjectsForOpenFiles;
145282             };
145283             ProjectService.prototype.deleteScriptInfo = function (info) {
145284                 this.filenameToScriptInfo.delete(info.path);
145285                 this.filenameToScriptInfoVersion.set(info.path, info.getVersion());
145286                 var realpath = info.getRealpathIfDifferent();
145287                 if (realpath) {
145288                     this.realpathToScriptInfos.remove(realpath, info); // TODO: GH#18217
145289                 }
145290             };
145291             ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) {
145292                 var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
145293                 if (configFileExistenceInfo) {
145294                     // By default the info would get impacted by presence of config file since its in the detection path
145295                     // Only adding the info as a root to inferred project will need the existence to be watched by file watcher
145296                     if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) {
145297                         configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false);
145298                         this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */);
145299                     }
145300                     return configFileExistenceInfo.exists;
145301                 }
145302                 // Theoretically we should be adding watch for the directory here itself.
145303                 // In practice there will be very few scenarios where the config file gets added
145304                 // somewhere inside the another config file directory.
145305                 // And technically we could handle that case in configFile's directory watcher in some cases
145306                 // But given that its a rare scenario it seems like too much overhead. (we werent watching those directories earlier either)
145307                 // So what we are now watching is: configFile if the configured project corresponding to it is open
145308                 // Or the whole chain of config files for the roots of the inferred projects
145309                 // Cache the host value of file exists and add the info to map of open files impacted by this config file
145310                 var exists = this.host.fileExists(configFileName);
145311                 var openFilesImpactedByConfigFile = ts.createMap();
145312                 if (isOpenScriptInfo(info)) {
145313                     openFilesImpactedByConfigFile.set(info.path, false);
145314                 }
145315                 configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile };
145316                 this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
145317                 this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */);
145318                 return exists;
145319             };
145320             ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) {
145321                 var configFileExistenceInfo = this.getConfigFileExistenceInfo(project);
145322                 if (configFileExistenceInfo) {
145323                     // The existence might not be set if the file watcher is not invoked by the time config project is created by external project
145324                     configFileExistenceInfo.exists = true;
145325                     // close existing watcher
145326                     if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) {
145327                         var configFileName = project.getConfigFilePath();
145328                         configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close();
145329                         configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined;
145330                         this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */);
145331                     }
145332                 }
145333                 else {
145334                     // We could be in this scenario if project is the configured project tracked by external project
145335                     // Since that route doesnt check if the config file is present or not
145336                     this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, {
145337                         exists: true,
145338                         openFilesImpactedByConfigFile: ts.createMap()
145339                     });
145340                 }
145341             };
145342             /**
145343              * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project
145344              */
145345             ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) {
145346                 return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; });
145347             };
145348             ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) {
145349                 var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject);
145350                 ts.Debug.assert(!!configFileExistenceInfo);
145351                 if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) {
145352                     var configFileName = closedProject.getConfigFilePath();
145353                     // If there are open files that are impacted by this config file existence
145354                     // but none of them are root of inferred project, the config file watcher will be
145355                     // created when any of the script infos are added as root of inferred project
145356                     if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) {
145357                         ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject);
145358                         this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo);
145359                     }
145360                 }
145361                 else {
145362                     // There is not a single file open thats tracking the status of this config file. Remove from cache
145363                     this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath);
145364                 }
145365             };
145366             ProjectService.prototype.logConfigFileWatchUpdate = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo, status) {
145367                 var _this = this;
145368                 if (!this.logger.hasLevel(server.LogLevel.verbose)) {
145369                     return;
145370                 }
145371                 var inferredRoots = [];
145372                 var otherFiles = [];
145373                 configFileExistenceInfo.openFilesImpactedByConfigFile.forEach(function (isRootOfInferredProject, key) {
145374                     var info = _this.getScriptInfoForPath(key);
145375                     (isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName);
145376                 });
145377                 var watches = [];
145378                 if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) {
145379                     watches.push(configFileExistenceInfo.configFileWatcherForRootOfInferredProject === ts.noopFileWatcher ?
145380                         ts.WatchType.NoopConfigFileForInferredRoot :
145381                         ts.WatchType.ConfigFileForInferredRoot);
145382                 }
145383                 if (this.configuredProjects.has(canonicalConfigFilePath)) {
145384                     watches.push(ts.WatchType.ConfigFile);
145385                 }
145386                 this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status);
145387             };
145388             /**
145389              * Create the watcher for the configFileExistenceInfo
145390              */
145391             ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) {
145392                 var _this = this;
145393                 configFileExistenceInfo.configFileWatcherForRootOfInferredProject =
145394                     ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath)) ?
145395                         this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, this.hostConfiguration.watchOptions, ts.WatchType.ConfigFileForInferredRoot) :
145396                         ts.noopFileWatcher;
145397                 this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */);
145398             };
145399             /**
145400              * Close the config file watcher in the cached ConfigFileExistenceInfo
145401              *   if there arent any open files that are root of inferred project
145402              */
145403             ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) {
145404                 // Close the config file watcher if there are no more open files that are root of inferred project
145405                 if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject &&
145406                     !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) {
145407                     configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close();
145408                     configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined;
145409                 }
145410             };
145411             /**
145412              * This is called on file close, so that we stop watching the config file for this script info
145413              */
145414             ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) {
145415                 var _this = this;
145416                 ts.Debug.assert(!info.isScriptOpen());
145417                 this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) {
145418                     var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
145419                     if (configFileExistenceInfo) {
145420                         var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path);
145421                         // Delete the info from map, since this file is no more open
145422                         configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path);
145423                         _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file" /* OpenFilesImpactedByConfigFileRemove */);
145424                         // If the script info was not root of inferred project,
145425                         // there wont be config file watch open because of this script info
145426                         if (infoIsRootOfInferredProject) {
145427                             // But if it is a root, it could be the last script info that is root of inferred project
145428                             // and hence we would need to close the config file watcher
145429                             _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo);
145430                         }
145431                         // If there are no open files that are impacted by configFileExistenceInfo after closing this script info
145432                         // there is no configured project present, remove the cached existence info
145433                         if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size &&
145434                             !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) {
145435                             ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject);
145436                             _this.configFileExistenceInfoCache.delete(canonicalConfigFilePath);
145437                         }
145438                     }
145439                 });
145440             };
145441             /**
145442              * This is called by inferred project whenever script info is added as a root
145443              */
145444             /* @internal */
145445             ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info) {
145446                 var _this = this;
145447                 ts.Debug.assert(info.isScriptOpen());
145448                 this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) {
145449                     var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
145450                     if (!configFileExistenceInfo) {
145451                         // Create the cache
145452                         configFileExistenceInfo = {
145453                             exists: _this.host.fileExists(configFileName),
145454                             openFilesImpactedByConfigFile: ts.createMap()
145455                         };
145456                         _this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
145457                     }
145458                     // Set this file as the root of inferred project
145459                     configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true);
145460                     _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root" /* RootOfInferredProjectTrue */);
145461                     // If there is no configured project for this config file, add the file watcher
145462                     if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject &&
145463                         !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) {
145464                         _this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo);
145465                     }
145466                 });
145467             };
145468             /**
145469              * This is called by inferred project whenever root script info is removed from it
145470              */
145471             /* @internal */
145472             ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) {
145473                 var _this = this;
145474                 this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) {
145475                     var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
145476                     if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) {
145477                         ts.Debug.assert(info.isScriptOpen());
145478                         // Info is not root of inferred project any more
145479                         configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false);
145480                         _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root" /* RootOfInferredProjectFalse */);
145481                         // Close the config file watcher
145482                         _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo);
145483                     }
145484                 });
145485             };
145486             /**
145487              * This function tries to search for a tsconfig.json for the given file.
145488              * This is different from the method the compiler uses because
145489              * the compiler can assume it will always start searching in the
145490              * current directory (the directory in which tsc was invoked).
145491              * The server must start searching from the directory containing
145492              * the newly opened file.
145493              */
145494             ProjectService.prototype.forEachConfigFileLocation = function (info, action) {
145495                 var _this = this;
145496                 if (this.syntaxOnly) {
145497                     return undefined;
145498                 }
145499                 ts.Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path));
145500                 var projectRootPath = this.openFiles.get(info.path);
145501                 var scriptInfo = ts.Debug.checkDefined(this.getScriptInfo(info.path));
145502                 if (scriptInfo.isDynamic)
145503                     return undefined;
145504                 var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName));
145505                 var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); };
145506                 // If projectRootPath doesn't contain info.path, then do normal search for config file
145507                 var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot();
145508                 // For ancestor of config file always ignore its own directory since its going to result in itself
145509                 var searchInDirectory = !isAncestorConfigFileInfo(info);
145510                 do {
145511                     if (searchInDirectory) {
145512                         var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName);
145513                         var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json"));
145514                         var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json"));
145515                         if (result)
145516                             return tsconfigFileName;
145517                         var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json"));
145518                         result = action(jsconfigFileName, ts.combinePaths(canonicalSearchPath, "jsconfig.json"));
145519                         if (result)
145520                             return jsconfigFileName;
145521                         // If we started within node_modules, don't look outside node_modules.
145522                         // Otherwise, we might pick up a very large project and pull in the world,
145523                         // causing an editor delay.
145524                         if (ts.isNodeModulesDirectory(canonicalSearchPath)) {
145525                             break;
145526                         }
145527                     }
145528                     var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath));
145529                     if (parentPath === searchPath)
145530                         break;
145531                     searchPath = parentPath;
145532                     searchInDirectory = true;
145533                 } while (anySearchPathOk || isSearchPathInProjectRoot());
145534                 return undefined;
145535             };
145536             /*@internal*/
145537             ProjectService.prototype.findDefaultConfiguredProject = function (info) {
145538                 if (!info.isScriptOpen())
145539                     return undefined;
145540                 var configFileName = this.getConfigFileNameForFile(info);
145541                 var project = configFileName &&
145542                     this.findConfiguredProjectByProjectName(configFileName);
145543                 return (project === null || project === void 0 ? void 0 : project.isSolution()) ?
145544                     project.getDefaultChildProjectFromSolution(info) :
145545                     project && projectContainsInfoDirectly(project, info) ?
145546                         project :
145547                         undefined;
145548             };
145549             /**
145550              * This function tries to search for a tsconfig.json for the given file.
145551              * This is different from the method the compiler uses because
145552              * the compiler can assume it will always start searching in the
145553              * current directory (the directory in which tsc was invoked).
145554              * The server must start searching from the directory containing
145555              * the newly opened file.
145556              * If script info is passed in, it is asserted to be open script info
145557              * otherwise just file name
145558              */
145559             ProjectService.prototype.getConfigFileNameForFile = function (info) {
145560                 var _this = this;
145561                 if (isOpenScriptInfo(info))
145562                     ts.Debug.assert(info.isScriptOpen());
145563                 this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName));
145564                 var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) {
145565                     return _this.configFileExists(configFileName, canonicalConfigFilePath, info);
145566                 });
145567                 if (configFileName) {
145568                     this.logger.info("For info: " + info.fileName + " :: Config file name: " + configFileName);
145569                 }
145570                 else {
145571                     this.logger.info("For info: " + info.fileName + " :: No config files found.");
145572                 }
145573                 return configFileName;
145574             };
145575             ProjectService.prototype.printProjects = function () {
145576                 var _this = this;
145577                 if (!this.logger.hasLevel(server.LogLevel.normal)) {
145578                     return;
145579                 }
145580                 this.logger.startGroup();
145581                 this.externalProjects.forEach(printProjectWithoutFileNames);
145582                 this.configuredProjects.forEach(printProjectWithoutFileNames);
145583                 this.inferredProjects.forEach(printProjectWithoutFileNames);
145584                 this.logger.info("Open files: ");
145585                 this.openFiles.forEach(function (projectRootPath, path) {
145586                     var info = _this.getScriptInfoForPath(path);
145587                     _this.logger.info("\tFileName: " + info.fileName + " ProjectRootPath: " + projectRootPath);
145588                     _this.logger.info("\t\tProjects: " + info.containingProjects.map(function (p) { return p.getProjectName(); }));
145589                 });
145590                 this.logger.endGroup();
145591             };
145592             /*@internal*/
145593             ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) {
145594                 // make sure that casing of config file name is consistent
145595                 var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName));
145596                 return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath);
145597             };
145598             ProjectService.prototype.getConfiguredProjectByCanonicalConfigFilePath = function (canonicalConfigFilePath) {
145599                 return this.configuredProjects.get(canonicalConfigFilePath);
145600             };
145601             ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) {
145602                 return findProjectByName(projectFileName, this.externalProjects);
145603             };
145604             /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */
145605             ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) {
145606                 if (options && options.disableSizeLimit || !this.host.getFileSize) {
145607                     return;
145608                 }
145609                 var availableSpace = server.maxProgramSizeForNonTsFiles;
145610                 this.projectToSizeMap.set(name, 0);
145611                 this.projectToSizeMap.forEach(function (val) { return (availableSpace -= (val || 0)); });
145612                 var totalNonTsFileSize = 0;
145613                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
145614                     var f = fileNames_1[_i];
145615                     var fileName = propertyReader.getFileName(f);
145616                     if (ts.hasTSFileExtension(fileName)) {
145617                         continue;
145618                     }
145619                     totalNonTsFileSize += this.host.getFileSize(fileName);
145620                     if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) {
145621                         this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
145622                         // Keep the size as zero since it's disabled
145623                         return fileName;
145624                     }
145625                 }
145626                 this.projectToSizeMap.set(name, totalNonTsFileSize);
145627                 return;
145628                 function getExceedLimitMessage(context, totalNonTsFileSize) {
145629                     var files = getTop5LargestFiles(context);
145630                     return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", ");
145631                 }
145632                 function getTop5LargestFiles(_a) {
145633                     var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host;
145634                     return fileNames.map(function (f) { return propertyReader.getFileName(f); })
145635                         .filter(function (name) { return hasTSFileExtension(name); })
145636                         .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217
145637                         .sort(function (a, b) { return b.size - a.size; })
145638                         .slice(0, 5);
145639                 }
145640             };
145641             ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) {
145642                 var compilerOptions = convertCompilerOptions(options);
145643                 var watchOptions = convertWatchOptions(options);
145644                 var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, 
145645                 /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave, 
145646                 /*projectFilePath*/ undefined, this.currentPluginConfigOverrides, watchOptions);
145647                 project.excludedFiles = excludedFiles;
145648                 this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition);
145649                 this.externalProjects.push(project);
145650                 return project;
145651             };
145652             /*@internal*/
145653             ProjectService.prototype.sendProjectTelemetry = function (project) {
145654                 if (this.seenProjects.has(project.projectName)) {
145655                     setProjectOptionsUsed(project);
145656                     return;
145657                 }
145658                 this.seenProjects.set(project.projectName, true);
145659                 if (!this.eventHandler || !this.host.createSHA256Hash) {
145660                     setProjectOptionsUsed(project);
145661                     return;
145662                 }
145663                 var projectOptions = server.isConfiguredProject(project) ? project.projectOptions : undefined;
145664                 setProjectOptionsUsed(project);
145665                 var data = {
145666                     projectId: this.host.createSHA256Hash(project.projectName),
145667                     fileStats: server.countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ true),
145668                     compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
145669                     typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()),
145670                     extends: projectOptions && projectOptions.configHasExtendsProperty,
145671                     files: projectOptions && projectOptions.configHasFilesProperty,
145672                     include: projectOptions && projectOptions.configHasIncludeProperty,
145673                     exclude: projectOptions && projectOptions.configHasExcludeProperty,
145674                     compileOnSave: project.compileOnSaveEnabled,
145675                     configFileName: configFileName(),
145676                     projectType: project instanceof server.ExternalProject ? "external" : "configured",
145677                     languageServiceEnabled: project.languageServiceEnabled,
145678                     version: ts.version,
145679                 };
145680                 this.eventHandler({ eventName: server.ProjectInfoTelemetryEvent, data: data });
145681                 function configFileName() {
145682                     if (!server.isConfiguredProject(project)) {
145683                         return "other";
145684                     }
145685                     return server.getBaseConfigFileName(project.getConfigFilePath()) || "other";
145686                 }
145687                 function convertTypeAcquisition(_a) {
145688                     var enable = _a.enable, include = _a.include, exclude = _a.exclude;
145689                     return {
145690                         enable: enable,
145691                         include: include !== undefined && include.length !== 0,
145692                         exclude: exclude !== undefined && exclude.length !== 0,
145693                     };
145694                 }
145695             };
145696             ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) {
145697                 this.updateNonInferredProjectFiles(project, files, propertyReader);
145698                 project.setTypeAcquisition(typeAcquisition);
145699             };
145700             /* @internal */
145701             ProjectService.prototype.createConfiguredProject = function (configFileName) {
145702                 var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217
145703                 this.logger.info("Opened configuration file " + configFileName);
145704                 var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost);
145705                 // TODO: We probably should also watch the configFiles that are extended
145706                 project.createConfigFileWatcher();
145707                 this.configuredProjects.set(project.canonicalConfigFilePath, project);
145708                 this.setConfigFileExistenceByNewConfiguredProject(project);
145709                 return project;
145710             };
145711             /* @internal */
145712             ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) {
145713                 var project = this.createConfiguredProject(configFileName);
145714                 project.pendingReload = ts.ConfigFileProgramReloadLevel.Full;
145715                 project.pendingReloadReason = reason;
145716                 return project;
145717             };
145718             /* @internal */
145719             ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) {
145720                 var project = this.createConfiguredProject(configFileName);
145721                 this.loadConfiguredProject(project, reason);
145722                 return project;
145723             };
145724             /* @internal */
145725             ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) {
145726                 var project = this.createAndLoadConfiguredProject(configFileName, reason);
145727                 project.updateGraph();
145728                 return project;
145729             };
145730             /**
145731              * Read the config file of the project, and update the project root file names.
145732              */
145733             /* @internal */
145734             ProjectService.prototype.loadConfiguredProject = function (project, reason) {
145735                 var _this = this;
145736                 this.sendProjectLoadingStartEvent(project, reason);
145737                 // Read updated contents from disk
145738                 var configFilename = ts.normalizePath(project.getConfigFilePath());
145739                 var configFileContent = ts.tryReadFile(configFilename, function (fileName) { return _this.host.readFile(fileName); });
145740                 var result = ts.parseJsonText(configFilename, ts.isString(configFileContent) ? configFileContent : "");
145741                 if (!result.endOfFileToken) {
145742                     result.endOfFileToken = { kind: 1 /* EndOfFileToken */ };
145743                 }
145744                 var configFileErrors = result.parseDiagnostics;
145745                 if (!ts.isString(configFileContent))
145746                     configFileErrors.push(configFileContent);
145747                 var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), 
145748                 /*existingOptions*/ {}, configFilename, 
145749                 /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions, 
145750                 /*extendedConfigCache*/ undefined);
145751                 if (parsedCommandLine.errors.length) {
145752                     configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors);
145753                 }
145754                 this.logger.info("Config: " + configFilename + " : " + JSON.stringify({
145755                     rootNames: parsedCommandLine.fileNames,
145756                     options: parsedCommandLine.options,
145757                     projectReferences: parsedCommandLine.projectReferences
145758                 }, /*replacer*/ undefined, " "));
145759                 ts.Debug.assert(!!parsedCommandLine.fileNames);
145760                 var compilerOptions = parsedCommandLine.options;
145761                 // Update the project
145762                 if (!project.projectOptions) {
145763                     project.projectOptions = {
145764                         configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined,
145765                         configHasFilesProperty: parsedCommandLine.raw.files !== undefined,
145766                         configHasIncludeProperty: parsedCommandLine.raw.include !== undefined,
145767                         configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined
145768                     };
145769                 }
145770                 project.configFileSpecs = parsedCommandLine.configFileSpecs;
145771                 project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw);
145772                 project.setProjectErrors(configFileErrors);
145773                 project.updateReferences(parsedCommandLine.projectReferences);
145774                 var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader);
145775                 if (lastFileExceededProgramSize) {
145776                     project.disableLanguageService(lastFileExceededProgramSize);
145777                     project.stopWatchingWildCards();
145778                 }
145779                 else {
145780                     project.setCompilerOptions(compilerOptions);
145781                     project.setWatchOptions(parsedCommandLine.watchOptions);
145782                     project.enableLanguageService();
145783                     project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217
145784                 }
145785                 project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides);
145786                 var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles());
145787                 this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions);
145788             };
145789             ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) {
145790                 var projectRootFilesMap = project.getRootFilesMap();
145791                 var newRootScriptInfoMap = ts.createMap();
145792                 for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
145793                     var f = files_1[_i];
145794                     var newRootFile = propertyReader.getFileName(f);
145795                     var fileName = server.toNormalizedPath(newRootFile);
145796                     var isDynamic = server.isDynamicFileName(fileName);
145797                     var path = void 0;
145798                     // Use the project's fileExists so that it can use caching instead of reaching to disk for the query
145799                     if (!isDynamic && !project.fileExists(newRootFile)) {
145800                         path = server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName);
145801                         var existingValue = projectRootFilesMap.get(path);
145802                         if (existingValue) {
145803                             if (existingValue.info) {
145804                                 project.removeFile(existingValue.info, /*fileExists*/ false, /*detachFromProject*/ true);
145805                                 existingValue.info = undefined;
145806                             }
145807                             existingValue.fileName = fileName;
145808                         }
145809                         else {
145810                             projectRootFilesMap.set(path, { fileName: fileName });
145811                         }
145812                     }
145813                     else {
145814                         var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions);
145815                         var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
145816                         var scriptInfo = ts.Debug.checkDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost));
145817                         path = scriptInfo.path;
145818                         var existingValue = projectRootFilesMap.get(path);
145819                         // If this script info is not already a root add it
145820                         if (!existingValue || existingValue.info !== scriptInfo) {
145821                             project.addRoot(scriptInfo, fileName);
145822                             if (scriptInfo.isScriptOpen()) {
145823                                 // if file is already root in some inferred project
145824                                 // - remove the file from that project and delete the project if necessary
145825                                 this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo);
145826                             }
145827                         }
145828                         else {
145829                             // Already root update the fileName
145830                             existingValue.fileName = fileName;
145831                         }
145832                     }
145833                     newRootScriptInfoMap.set(path, true);
145834                 }
145835                 // project's root file map size is always going to be same or larger than new roots map
145836                 // as we have already all the new files to the project
145837                 if (projectRootFilesMap.size > newRootScriptInfoMap.size) {
145838                     projectRootFilesMap.forEach(function (value, path) {
145839                         if (!newRootScriptInfoMap.has(path)) {
145840                             if (value.info) {
145841                                 project.removeFile(value.info, project.fileExists(path), /*detachFromProject*/ true);
145842                             }
145843                             else {
145844                                 projectRootFilesMap.delete(path);
145845                             }
145846                         }
145847                     });
145848                 }
145849                 // Just to ensure that even if root files dont change, the changes to the non root file are picked up,
145850                 // mark the project as dirty unconditionally
145851                 project.markAsDirty();
145852             };
145853             ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, watchOptions) {
145854                 project.setCompilerOptions(newOptions);
145855                 project.setWatchOptions(watchOptions);
145856                 // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently
145857                 // therefore if it is undefined, it should not be updated.
145858                 if (compileOnSave !== undefined) {
145859                     project.compileOnSaveEnabled = compileOnSave;
145860                 }
145861                 this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition);
145862             };
145863             /**
145864              * Reload the file names from config file specs and update the project graph
145865              */
145866             /*@internal*/
145867             ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) {
145868                 var configFileSpecs = project.configFileSpecs; // TODO: GH#18217
145869                 var configFileName = project.getConfigFilePath();
145870                 var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions);
145871                 project.updateErrorOnNoInputFiles(fileNamesResult);
145872                 this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader);
145873                 return project.updateGraph();
145874             };
145875             /**
145876              * Read the config file of the project again by clearing the cache and update the project graph
145877              */
145878             /* @internal */
145879             ProjectService.prototype.reloadConfiguredProject = function (project, reason) {
145880                 // At this point, there is no reason to not have configFile in the host
145881                 var host = project.getCachedDirectoryStructureHost();
145882                 // Clear the cache since we are reloading the project from disk
145883                 host.clearCache();
145884                 var configFileName = project.getConfigFilePath();
145885                 this.logger.info("Reloading configured project " + configFileName);
145886                 // Load project from the disk
145887                 this.loadConfiguredProject(project, reason);
145888                 project.updateGraph();
145889                 this.sendConfigFileDiagEvent(project, configFileName);
145890             };
145891             ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) {
145892                 if (!this.eventHandler || this.suppressDiagnosticEvents) {
145893                     return;
145894                 }
145895                 var diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics();
145896                 diagnostics.push.apply(diagnostics, project.getAllProjectErrors());
145897                 this.eventHandler({
145898                     eventName: server.ConfigFileDiagEvent,
145899                     data: { configFileName: project.getConfigFilePath(), diagnostics: diagnostics, triggerFile: triggerFile }
145900                 });
145901             };
145902             ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) {
145903                 if (!this.useInferredProjectPerProjectRoot ||
145904                     // Its a dynamic info opened without project root
145905                     (info.isDynamic && projectRootPath === undefined)) {
145906                     return undefined;
145907                 }
145908                 if (projectRootPath) {
145909                     var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath);
145910                     // if we have an explicit project root path, find (or create) the matching inferred project.
145911                     for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
145912                         var project = _a[_i];
145913                         if (project.projectRootPath === canonicalProjectRootPath) {
145914                             return project;
145915                         }
145916                     }
145917                     return this.createInferredProject(projectRootPath, /*isSingleInferredProject*/ false, projectRootPath);
145918                 }
145919                 // we don't have an explicit root path, so we should try to find an inferred project
145920                 // that more closely contains the file.
145921                 var bestMatch;
145922                 for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) {
145923                     var project = _c[_b];
145924                     // ignore single inferred projects (handled elsewhere)
145925                     if (!project.projectRootPath)
145926                         continue;
145927                     // ignore inferred projects that don't contain the root's path
145928                     if (!ts.containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames))
145929                         continue;
145930                     // ignore inferred projects that are higher up in the project root.
145931                     // TODO(rbuckton): Should we add the file as a root to these as well?
145932                     if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length)
145933                         continue;
145934                     bestMatch = project;
145935                 }
145936                 return bestMatch;
145937             };
145938             ProjectService.prototype.getOrCreateSingleInferredProjectIfEnabled = function () {
145939                 if (!this.useSingleInferredProject) {
145940                     return undefined;
145941                 }
145942                 // If `useInferredProjectPerProjectRoot` is not enabled, then there will only be one
145943                 // inferred project for all files. If `useInferredProjectPerProjectRoot` is enabled
145944                 // then we want to put all files that are not opened with a `projectRootPath` into
145945                 // the same inferred project.
145946                 //
145947                 // To avoid the cost of searching through the array and to optimize for the case where
145948                 // `useInferredProjectPerProjectRoot` is not enabled, we will always put the inferred
145949                 // project for non-rooted files at the front of the array.
145950                 if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) {
145951                     return this.inferredProjects[0];
145952                 }
145953                 // Single inferred project does not have a project root and hence no current directory
145954                 return this.createInferredProject(/*currentDirectory*/ undefined, /*isSingleInferredProject*/ true);
145955             };
145956             ProjectService.prototype.getOrCreateSingleInferredWithoutProjectRoot = function (currentDirectory) {
145957                 ts.Debug.assert(!this.useSingleInferredProject);
145958                 var expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory || ""));
145959                 // Reuse the project with same current directory but no roots
145960                 for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
145961                     var inferredProject = _a[_i];
145962                     if (!inferredProject.projectRootPath &&
145963                         inferredProject.isOrphan() &&
145964                         inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory) {
145965                         return inferredProject;
145966                     }
145967                 }
145968                 return this.createInferredProject(currentDirectory);
145969             };
145970             ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) {
145971                 var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; // TODO: GH#18217
145972                 var watchOptions;
145973                 if (projectRootPath) {
145974                     watchOptions = this.watchOptionsForInferredProjectsPerProjectRoot.get(projectRootPath);
145975                 }
145976                 if (watchOptions === undefined) {
145977                     watchOptions = this.watchOptionsForInferredProjects;
145978                 }
145979                 var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, watchOptions || undefined, projectRootPath, currentDirectory, this.currentPluginConfigOverrides);
145980                 if (isSingleInferredProject) {
145981                     this.inferredProjects.unshift(project);
145982                 }
145983                 else {
145984                     this.inferredProjects.push(project);
145985                 }
145986                 return project;
145987             };
145988             /*@internal*/
145989             ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClient = function (uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) {
145990                 return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, /*scriptKind*/ undefined, 
145991                 /*hasMixedContent*/ undefined, hostToQueryFileExistsOn);
145992             };
145993             ProjectService.prototype.getScriptInfo = function (uncheckedFileName) {
145994                 return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
145995             };
145996             /* @internal */
145997             ProjectService.prototype.getScriptInfoOrConfig = function (uncheckedFileName) {
145998                 var path = server.toNormalizedPath(uncheckedFileName);
145999                 var info = this.getScriptInfoForNormalizedPath(path);
146000                 if (info)
146001                     return info;
146002                 var configProject = this.configuredProjects.get(this.toPath(uncheckedFileName));
146003                 return configProject && configProject.getCompilerOptions().configFile;
146004             };
146005             /* @internal */
146006             ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) {
146007                 var names = ts.arrayFrom(this.filenameToScriptInfo.entries()).map(function (_a) {
146008                     var path = _a[0], scriptInfo = _a[1];
146009                     return ({ path: path, fileName: scriptInfo.fileName });
146010                 });
146011                 this.logger.msg("Could not find file " + JSON.stringify(fileName) + ".\nAll files are: " + JSON.stringify(names), server.Msg.Err);
146012             };
146013             /**
146014              * Returns the projects that contain script info through SymLink
146015              * Note that this does not return projects in info.containingProjects
146016              */
146017             /*@internal*/
146018             ProjectService.prototype.getSymlinkedProjects = function (info) {
146019                 var projects;
146020                 if (this.realpathToScriptInfos) {
146021                     var realpath = info.getRealpathIfDifferent();
146022                     if (realpath) {
146023                         ts.forEach(this.realpathToScriptInfos.get(realpath), combineProjects);
146024                     }
146025                     ts.forEach(this.realpathToScriptInfos.get(info.path), combineProjects);
146026                 }
146027                 return projects;
146028                 function combineProjects(toAddInfo) {
146029                     if (toAddInfo !== info) {
146030                         var _loop_4 = function (project) {
146031                             // Add the projects only if they can use symLink targets and not already in the list
146032                             if (project.languageServiceEnabled &&
146033                                 !project.isOrphan() &&
146034                                 !project.getCompilerOptions().preserveSymlinks &&
146035                                 !info.isAttached(project)) {
146036                                 if (!projects) {
146037                                     projects = ts.createMultiMap();
146038                                     projects.add(toAddInfo.path, project);
146039                                 }
146040                                 else if (!ts.forEachEntry(projects, function (projs, path) { return path === toAddInfo.path ? false : ts.contains(projs, project); })) {
146041                                     projects.add(toAddInfo.path, project);
146042                                 }
146043                             }
146044                         };
146045                         for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) {
146046                             var project = _a[_i];
146047                             _loop_4(project);
146048                         }
146049                     }
146050                 }
146051             };
146052             ProjectService.prototype.watchClosedScriptInfo = function (info) {
146053                 var _this = this;
146054                 ts.Debug.assert(!info.fileWatcher);
146055                 // do not watch files with mixed content - server doesn't know how to interpret it
146056                 // do not watch files in the global cache location
146057                 if (!info.isDynamicOrHasMixedContent() &&
146058                     (!this.globalCacheLocationDirectoryPath ||
146059                         !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) {
146060                     var indexOfNodeModules = info.path.indexOf("/node_modules/");
146061                     if (!this.host.getModifiedTime || indexOfNodeModules === -1) {
146062                         info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, this.hostConfiguration.watchOptions, info.path, ts.WatchType.ClosedScriptInfo);
146063                     }
146064                     else {
146065                         info.mTime = this.getModifiedTime(info);
146066                         info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules));
146067                     }
146068                 }
146069             };
146070             ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) {
146071                 var _this = this;
146072                 // Watch only directory
146073                 var existing = this.scriptInfoInNodeModulesWatchers.get(dir);
146074                 if (existing) {
146075                     existing.refCount++;
146076                     return existing;
146077                 }
146078                 var watchDir = dir + "/node_modules";
146079                 var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) {
146080                     var fileOrDirectoryPath = ts.removeIgnoredPath(_this.toPath(fileOrDirectory));
146081                     if (!fileOrDirectoryPath)
146082                         return;
146083                     // Has extension
146084                     ts.Debug.assert(result.refCount > 0);
146085                     if (watchDir === fileOrDirectoryPath) {
146086                         _this.refreshScriptInfosInDirectory(watchDir);
146087                     }
146088                     else {
146089                         var info = _this.getScriptInfoForPath(fileOrDirectoryPath);
146090                         if (info) {
146091                             if (isScriptInfoWatchedFromNodeModules(info)) {
146092                                 _this.refreshScriptInfo(info);
146093                             }
146094                         }
146095                         // Folder
146096                         else if (!ts.hasExtension(fileOrDirectoryPath)) {
146097                             _this.refreshScriptInfosInDirectory(fileOrDirectoryPath);
146098                         }
146099                     }
146100                 }, 1 /* Recursive */, this.hostConfiguration.watchOptions, ts.WatchType.NodeModulesForClosedScriptInfo);
146101                 var result = {
146102                     close: function () {
146103                         if (result.refCount === 1) {
146104                             watcher.close();
146105                             _this.scriptInfoInNodeModulesWatchers.delete(dir);
146106                         }
146107                         else {
146108                             result.refCount--;
146109                         }
146110                     },
146111                     refCount: 1
146112                 };
146113                 this.scriptInfoInNodeModulesWatchers.set(dir, result);
146114                 return result;
146115             };
146116             ProjectService.prototype.getModifiedTime = function (info) {
146117                 return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime();
146118             };
146119             ProjectService.prototype.refreshScriptInfo = function (info) {
146120                 var mTime = this.getModifiedTime(info);
146121                 if (mTime !== info.mTime) {
146122                     var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime);
146123                     info.mTime = mTime;
146124                     this.onSourceFileChanged(info.fileName, eventKind, info.path);
146125                 }
146126             };
146127             ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) {
146128                 var _this = this;
146129                 dir = dir + ts.directorySeparator;
146130                 this.filenameToScriptInfo.forEach(function (info) {
146131                     if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) {
146132                         _this.refreshScriptInfo(info);
146133                     }
146134                 });
146135             };
146136             ProjectService.prototype.stopWatchingScriptInfo = function (info) {
146137                 if (info.fileWatcher) {
146138                     info.fileWatcher.close();
146139                     info.fileWatcher = undefined;
146140                 }
146141             };
146142             ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
146143                 if (ts.isRootedDiskPath(fileName) || server.isDynamicFileName(fileName)) {
146144                     return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
146145                 }
146146                 // This is non rooted path with different current directory than project service current directory
146147                 // Only paths recognized are open relative file paths
146148                 var info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName));
146149                 if (info) {
146150                     return info;
146151                 }
146152                 // This means triple slash references wont be resolved in dynamic and unsaved files
146153                 // which is intentional since we dont know what it means to be relative to non disk files
146154                 return undefined;
146155             };
146156             ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) {
146157                 return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ true, fileContent, scriptKind, hasMixedContent);
146158             };
146159             ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
146160                 return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
146161             };
146162             ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
146163                 var _this = this;
146164                 ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content");
146165                 var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName);
146166                 var info = this.getScriptInfoForPath(path);
146167                 if (!info) {
146168                     var isDynamic = server.isDynamicFileName(fileName);
146169                     ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; });
146170                     ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; });
146171                     ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath."; });
146172                     // If the file is not opened by client and the file doesnot exist on the disk, return
146173                     if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) {
146174                         return;
146175                     }
146176                     info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path)); // TODO: GH#18217
146177                     this.filenameToScriptInfo.set(info.path, info);
146178                     this.filenameToScriptInfoVersion.delete(info.path);
146179                     if (!openedByClient) {
146180                         this.watchClosedScriptInfo(info);
146181                     }
146182                     else if (!ts.isRootedDiskPath(fileName) && (!isDynamic || this.currentDirectory !== currentDirectory)) {
146183                         // File that is opened by user but isn't rooted disk path
146184                         this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info);
146185                     }
146186                 }
146187                 if (openedByClient) {
146188                     // Opening closed script info
146189                     // either it was created just now, or was part of projects but was closed
146190                     this.stopWatchingScriptInfo(info);
146191                     info.open(fileContent);
146192                     if (hasMixedContent) {
146193                         info.registerFileUpdate();
146194                     }
146195                 }
146196                 return info;
146197             };
146198             /**
146199              * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred
146200              */
146201             ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) {
146202                 return !ts.isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) ||
146203                     this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName));
146204             };
146205             ProjectService.prototype.getScriptInfoForPath = function (fileName) {
146206                 return this.filenameToScriptInfo.get(fileName);
146207             };
146208             /*@internal*/
146209             ProjectService.prototype.getDocumentPositionMapper = function (project, generatedFileName, sourceFileName) {
146210                 var _this = this;
146211                 // Since declaration info and map file watches arent updating project's directory structure host (which can cache file structure) use host
146212                 var declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host);
146213                 if (!declarationInfo) {
146214                     if (sourceFileName) {
146215                         // Project contains source file and it generates the generated file name
146216                         project.addGeneratedFileWatch(generatedFileName, sourceFileName);
146217                     }
146218                     return undefined;
146219                 }
146220                 // Try to get from cache
146221                 declarationInfo.getSnapshot(); // Ensure synchronized
146222                 if (ts.isString(declarationInfo.sourceMapFilePath)) {
146223                     // Ensure mapper is synchronized
146224                     var sourceMapFileInfo_1 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
146225                     if (sourceMapFileInfo_1) {
146226                         sourceMapFileInfo_1.getSnapshot();
146227                         if (sourceMapFileInfo_1.documentPositionMapper !== undefined) {
146228                             sourceMapFileInfo_1.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo_1.sourceInfos);
146229                             return sourceMapFileInfo_1.documentPositionMapper ? sourceMapFileInfo_1.documentPositionMapper : undefined;
146230                         }
146231                     }
146232                     declarationInfo.sourceMapFilePath = undefined;
146233                 }
146234                 else if (declarationInfo.sourceMapFilePath) {
146235                     declarationInfo.sourceMapFilePath.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, declarationInfo.sourceMapFilePath.sourceInfos);
146236                     return undefined;
146237                 }
146238                 else if (declarationInfo.sourceMapFilePath !== undefined) {
146239                     // Doesnt have sourceMap
146240                     return undefined;
146241                 }
146242                 // Create the mapper
146243                 var sourceMapFileInfo;
146244                 var mapFileNameFromDeclarationInfo;
146245                 var readMapFile = function (mapFileName, mapFileNameFromDts) {
146246                     var mapInfo = _this.getOrCreateScriptInfoNotOpenedByClient(mapFileName, project.currentDirectory, _this.host);
146247                     if (!mapInfo) {
146248                         mapFileNameFromDeclarationInfo = mapFileNameFromDts;
146249                         return undefined;
146250                     }
146251                     sourceMapFileInfo = mapInfo;
146252                     var snap = mapInfo.getSnapshot();
146253                     if (mapInfo.documentPositionMapper !== undefined)
146254                         return mapInfo.documentPositionMapper;
146255                     return snap.getText(0, snap.getLength());
146256                 };
146257                 var projectName = project.projectName;
146258                 var documentPositionMapper = ts.getDocumentPositionMapper({ getCanonicalFileName: this.toCanonicalFileName, log: function (s) { return _this.logger.info(s); }, getSourceFileLike: function (f) { return _this.getSourceFileLike(f, projectName, declarationInfo); } }, declarationInfo.fileName, declarationInfo.getLineInfo(), readMapFile);
146259                 readMapFile = undefined; // Remove ref to project
146260                 if (sourceMapFileInfo) {
146261                     declarationInfo.sourceMapFilePath = sourceMapFileInfo.path;
146262                     sourceMapFileInfo.declarationInfoPath = declarationInfo.path;
146263                     sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false;
146264                     sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos);
146265                 }
146266                 else if (mapFileNameFromDeclarationInfo) {
146267                     declarationInfo.sourceMapFilePath = {
146268                         watcher: this.addMissingSourceMapFile(project.currentDirectory === this.currentDirectory ?
146269                             mapFileNameFromDeclarationInfo :
146270                             ts.getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory), declarationInfo.path),
146271                         sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project)
146272                     };
146273                 }
146274                 else {
146275                     declarationInfo.sourceMapFilePath = false;
146276                 }
146277                 return documentPositionMapper;
146278             };
146279             ProjectService.prototype.addSourceInfoToSourceMap = function (sourceFileName, project, sourceInfos) {
146280                 if (sourceFileName) {
146281                     // Attach as source
146282                     var sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost);
146283                     (sourceInfos || (sourceInfos = ts.createMap())).set(sourceInfo.path, true);
146284                 }
146285                 return sourceInfos;
146286             };
146287             ProjectService.prototype.addMissingSourceMapFile = function (mapFileName, declarationInfoPath) {
146288                 var _this = this;
146289                 var fileWatcher = this.watchFactory.watchFile(this.host, mapFileName, function () {
146290                     var declarationInfo = _this.getScriptInfoForPath(declarationInfoPath);
146291                     if (declarationInfo && declarationInfo.sourceMapFilePath && !ts.isString(declarationInfo.sourceMapFilePath)) {
146292                         // Update declaration and source projects
146293                         _this.delayUpdateProjectGraphs(declarationInfo.containingProjects, /*clearSourceMapperCache*/ true);
146294                         _this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos);
146295                         declarationInfo.closeSourceMapFileWatcher();
146296                     }
146297                 }, ts.PollingInterval.High, this.hostConfiguration.watchOptions, ts.WatchType.MissingSourceMapFile);
146298                 return fileWatcher;
146299             };
146300             /*@internal*/
146301             ProjectService.prototype.getSourceFileLike = function (fileName, projectNameOrProject, declarationInfo) {
146302                 var project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject);
146303                 if (project) {
146304                     var path = project.toPath(fileName);
146305                     var sourceFile = project.getSourceFile(path);
146306                     if (sourceFile && sourceFile.resolvedPath === path)
146307                         return sourceFile;
146308                 }
146309                 // Need to look for other files.
146310                 var info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host);
146311                 if (!info)
146312                     return undefined;
146313                 // Attach as source
146314                 if (declarationInfo && ts.isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) {
146315                     var sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
146316                     if (sourceMapInfo) {
146317                         (sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = ts.createMap())).set(info.path, true);
146318                     }
146319                 }
146320                 // Key doesnt matter since its only for text and lines
146321                 if (info.cacheSourceFile)
146322                     return info.cacheSourceFile.sourceFile;
146323                 // Create sourceFileLike
146324                 if (!info.sourceFileLike) {
146325                     info.sourceFileLike = {
146326                         get text() {
146327                             ts.Debug.fail("shouldnt need text");
146328                             return "";
146329                         },
146330                         getLineAndCharacterOfPosition: function (pos) {
146331                             var lineOffset = info.positionToLineOffset(pos);
146332                             return { line: lineOffset.line - 1, character: lineOffset.offset - 1 };
146333                         },
146334                         getPositionOfLineAndCharacter: function (line, character, allowEdits) { return info.lineOffsetToPosition(line + 1, character + 1, allowEdits); }
146335                     };
146336                 }
146337                 return info.sourceFileLike;
146338             };
146339             /*@internal*/
146340             ProjectService.prototype.setPerformanceEventHandler = function (performanceEventHandler) {
146341                 this.performanceEventHandler = performanceEventHandler;
146342             };
146343             ProjectService.prototype.setHostConfiguration = function (args) {
146344                 var _this = this;
146345                 if (args.file) {
146346                     var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file));
146347                     if (info) {
146348                         info.setOptions(convertFormatOptions(args.formatOptions), args.preferences);
146349                         this.logger.info("Host configuration update for file " + args.file);
146350                     }
146351                 }
146352                 else {
146353                     if (args.hostInfo !== undefined) {
146354                         this.hostConfiguration.hostInfo = args.hostInfo;
146355                         this.logger.info("Host information " + args.hostInfo);
146356                     }
146357                     if (args.formatOptions) {
146358                         this.hostConfiguration.formatCodeOptions = __assign(__assign({}, this.hostConfiguration.formatCodeOptions), convertFormatOptions(args.formatOptions));
146359                         this.logger.info("Format host information updated");
146360                     }
146361                     if (args.preferences) {
146362                         var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject;
146363                         this.hostConfiguration.preferences = __assign(__assign({}, this.hostConfiguration.preferences), args.preferences);
146364                         if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) {
146365                             // Load configured projects for external projects that are pending reload
146366                             this.configuredProjects.forEach(function (project) {
146367                                 if (project.hasExternalProjectRef() &&
146368                                     project.pendingReload === ts.ConfigFileProgramReloadLevel.Full &&
146369                                     !_this.pendingProjectUpdates.has(project.getProjectName())) {
146370                                     project.updateGraph();
146371                                 }
146372                             });
146373                         }
146374                     }
146375                     if (args.extraFileExtensions) {
146376                         this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
146377                         // We need to update the project structures again as it is possible that existing
146378                         // project structure could have more or less files depending on extensions permitted
146379                         this.reloadProjects();
146380                         this.logger.info("Host file extension mappings updated");
146381                     }
146382                     if (args.watchOptions) {
146383                         this.hostConfiguration.watchOptions = convertWatchOptions(args.watchOptions);
146384                         this.logger.info("Host watch options changed to " + JSON.stringify(this.hostConfiguration.watchOptions) + ", it will be take effect for next watches.");
146385                     }
146386                 }
146387             };
146388             /*@internal*/
146389             ProjectService.prototype.getWatchOptions = function (project) {
146390                 var projectOptions = project.getWatchOptions();
146391                 return projectOptions && this.hostConfiguration.watchOptions ? __assign(__assign({}, this.hostConfiguration.watchOptions), projectOptions) :
146392                     projectOptions || this.hostConfiguration.watchOptions;
146393             };
146394             ProjectService.prototype.closeLog = function () {
146395                 this.logger.close();
146396             };
146397             /**
146398              * This function rebuilds the project for every file opened by the client
146399              * This does not reload contents of open files from disk. But we could do that if needed
146400              */
146401             ProjectService.prototype.reloadProjects = function () {
146402                 this.logger.info("reload projects.");
146403                 // If we want this to also reload open files from disk, we could do that,
146404                 // but then we need to make sure we arent calling this function
146405                 // (and would separate out below reloading of projects to be called when immediate reload is needed)
146406                 // as there is no need to load contents of the files from the disk
146407                 // Reload Projects
146408                 this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue, "User requested reload projects");
146409                 this.ensureProjectForOpenFiles();
146410             };
146411             ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) {
146412                 // Get open files to reload projects for
146413                 this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, 
146414                 /*delayReload*/ true, ignoreIfNotRootOfInferredProject ?
146415                     function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project
146416                     ts.returnTrue, // Reload all the open files impacted by config file
146417                 "Change in config file detected");
146418                 this.delayEnsureProjectForOpenFiles();
146419             };
146420             /**
146421              * This function goes through all the openFiles and tries to file the config file for them.
146422              * If the config file is found and it refers to existing project, it reloads it either immediately
146423              * or schedules it for reload depending on delayReload option
146424              * If the there is no existing project it just opens the configured project for the config file
146425              * reloadForInfo provides a way to filter out files to reload configured project for
146426              */
146427             ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) {
146428                 var _this = this;
146429                 var updatedProjects = ts.createMap();
146430                 // try to reload config file for all open files
146431                 openFiles.forEach(function (openFileValue, path) {
146432                     // Filter out the files that need to be ignored
146433                     if (!shouldReloadProjectFor(openFileValue)) {
146434                         return;
146435                     }
146436                     var info = _this.getScriptInfoForPath(path); // TODO: GH#18217
146437                     ts.Debug.assert(info.isScriptOpen());
146438                     // This tries to search for a tsconfig.json for the given file. If we found it,
146439                     // we first detect if there is already a configured project created for it: if so,
146440                     // we re- read the tsconfig file content and update the project only if we havent already done so
146441                     // otherwise we create a new one.
146442                     var configFileName = _this.getConfigFileNameForFile(info);
146443                     if (configFileName) {
146444                         var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName);
146445                         if (!updatedProjects.has(project.canonicalConfigFilePath)) {
146446                             updatedProjects.set(project.canonicalConfigFilePath, true);
146447                             if (delayReload) {
146448                                 project.pendingReload = ts.ConfigFileProgramReloadLevel.Full;
146449                                 project.pendingReloadReason = reason;
146450                                 _this.delayUpdateProjectGraph(project);
146451                             }
146452                             else {
146453                                 // reload from the disk
146454                                 _this.reloadConfiguredProject(project, reason);
146455                                 // If this is solution, reload the project till the reloaded project contains the script info directly
146456                                 if (!project.containsScriptInfo(info) && project.isSolution()) {
146457                                     forEachResolvedProjectReferenceProject(project, function (child) {
146458                                         if (!updatedProjects.has(child.canonicalConfigFilePath)) {
146459                                             updatedProjects.set(child.canonicalConfigFilePath, true);
146460                                             _this.reloadConfiguredProject(child, reason);
146461                                         }
146462                                         return projectContainsInfoDirectly(child, info);
146463                                     }, ProjectReferenceProjectLoadKind.FindCreate);
146464                                 }
146465                             }
146466                         }
146467                     }
146468                 });
146469             };
146470             /**
146471              * Remove the root of inferred project if script info is part of another project
146472              */
146473             ProjectService.prototype.removeRootOfInferredProjectIfNowPartOfOtherProject = function (info) {
146474                 // If the script info is root of inferred project, it could only be first containing project
146475                 // since info is added as root to the inferred project only when there are no other projects containing it
146476                 // So when it is root of the inferred project and after project structure updates its now part
146477                 // of multiple project it needs to be removed from that inferred project because:
146478                 // - references in inferred project supersede the root part
146479                 // - root / reference in non - inferred project beats root in inferred project
146480                 // eg. say this is structure /a/b/a.ts /a/b/c.ts where c.ts references a.ts
146481                 // When a.ts is opened, since there is no configured project/external project a.ts can be part of
146482                 // a.ts is added as root to inferred project.
146483                 // Now at time of opening c.ts, c.ts is also not aprt of any existing project,
146484                 // so it will be added to inferred project as a root. (for sake of this example assume single inferred project is false)
146485                 // So at this poing a.ts is part of first inferred project and second inferred project (of which c.ts is root)
146486                 // And hence it needs to be removed from the first inferred project.
146487                 ts.Debug.assert(info.containingProjects.length > 0);
146488                 var firstProject = info.containingProjects[0];
146489                 if (!firstProject.isOrphan() &&
146490                     server.isInferredProject(firstProject) &&
146491                     firstProject.isRoot(info) &&
146492                     ts.forEach(info.containingProjects, function (p) { return p !== firstProject && !p.isOrphan(); })) {
146493                     firstProject.removeFile(info, /*fileExists*/ true, /*detachFromProject*/ true);
146494                 }
146495             };
146496             /**
146497              * This function is to update the project structure for every inferred project.
146498              * It is called on the premise that all the configured projects are
146499              * up to date.
146500              * This will go through open files and assign them to inferred project if open file is not part of any other project
146501              * After that all the inferred project graphs are updated
146502              */
146503             ProjectService.prototype.ensureProjectForOpenFiles = function () {
146504                 var _this = this;
146505                 this.logger.info("Before ensureProjectForOpenFiles:");
146506                 this.printProjects();
146507                 this.openFiles.forEach(function (projectRootPath, path) {
146508                     var info = _this.getScriptInfoForPath(path);
146509                     // collect all orphaned script infos from open files
146510                     if (info.isOrphan()) {
146511                         _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
146512                     }
146513                     else {
146514                         // Or remove the root of inferred project if is referenced in more than one projects
146515                         _this.removeRootOfInferredProjectIfNowPartOfOtherProject(info);
146516                     }
146517                 });
146518                 this.pendingEnsureProjectForOpenFiles = false;
146519                 this.inferredProjects.forEach(updateProjectIfDirty);
146520                 this.logger.info("After ensureProjectForOpenFiles:");
146521                 this.printProjects();
146522             };
146523             /**
146524              * Open file whose contents is managed by the client
146525              * @param filename is absolute pathname
146526              * @param fileContent is a known version of the file content that is more up to date than the one on disk
146527              */
146528             ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) {
146529                 return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined);
146530             };
146531             /*@internal*/
146532             ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) {
146533                 var _this = this;
146534                 var originalLocation = project.isSourceOfProjectReferenceRedirect(location.fileName) ?
146535                     location :
146536                     project.getSourceMapper().tryGetSourcePosition(location);
146537                 if (!originalLocation)
146538                     return undefined;
146539                 var fileName = originalLocation.fileName;
146540                 if (!this.getScriptInfo(fileName) && !this.host.fileExists(fileName))
146541                     return undefined;
146542                 var originalFileInfo = { fileName: server.toNormalizedPath(fileName), path: this.toPath(fileName) };
146543                 var configFileName = this.getConfigFileNameForFile(originalFileInfo);
146544                 if (!configFileName)
146545                     return undefined;
146546                 var configuredProject = this.findConfiguredProjectByProjectName(configFileName) ||
146547                     this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + (location !== originalLocation ? " for location: " + location.fileName : ""));
146548                 updateProjectIfDirty(configuredProject);
146549                 if (configuredProject.isSolution()) {
146550                     // Find the project that is referenced from this solution that contains the script info directly
146551                     configuredProject = forEachResolvedProjectReferenceProject(configuredProject, function (child) {
146552                         updateProjectIfDirty(child);
146553                         var info = _this.getScriptInfo(fileName);
146554                         return info && projectContainsInfoDirectly(child, info) ? child : undefined;
146555                     }, ProjectReferenceProjectLoadKind.FindCreateLoad, "Creating project referenced in solution " + configuredProject.projectName + " to find possible configured project for original file: " + originalFileInfo.fileName + (location !== originalLocation ? " for location: " + location.fileName : ""));
146556                     if (!configuredProject)
146557                         return undefined;
146558                     if (configuredProject === project)
146559                         return originalLocation;
146560                 }
146561                 // Keep this configured project as referenced from project
146562                 addOriginalConfiguredProject(configuredProject);
146563                 var originalScriptInfo = this.getScriptInfo(fileName);
146564                 if (!originalScriptInfo || !originalScriptInfo.containingProjects.length)
146565                     return undefined;
146566                 // Add configured projects as referenced
146567                 originalScriptInfo.containingProjects.forEach(function (project) {
146568                     if (server.isConfiguredProject(project)) {
146569                         addOriginalConfiguredProject(project);
146570                     }
146571                 });
146572                 return originalLocation;
146573                 function addOriginalConfiguredProject(originalProject) {
146574                     if (!project.originalConfiguredProjects) {
146575                         project.originalConfiguredProjects = ts.createMap();
146576                     }
146577                     project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true);
146578                 }
146579             };
146580             /** @internal */
146581             ProjectService.prototype.fileExists = function (fileName) {
146582                 return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName);
146583             };
146584             ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) {
146585                 return ts.find(this.externalProjects, function (proj) {
146586                     // Ensure project structure is up-to-date to check if info is present in external project
146587                     updateProjectIfDirty(proj);
146588                     return proj.containsScriptInfo(info);
146589                 });
146590             };
146591             ProjectService.prototype.getOrCreateOpenScriptInfo = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
146592                 var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217
146593                 this.openFiles.set(info.path, projectRootPath);
146594                 return info;
146595             };
146596             ProjectService.prototype.assignProjectToOpenedScriptInfo = function (info) {
146597                 var _this = this;
146598                 var configFileName;
146599                 var configFileErrors;
146600                 var project = this.findExternalProjectContainingOpenScriptInfo(info);
146601                 var defaultConfigProject;
146602                 var retainProjects;
146603                 if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization
146604                     configFileName = this.getConfigFileNameForFile(info);
146605                     if (configFileName) {
146606                         project = this.findConfiguredProjectByProjectName(configFileName);
146607                         if (!project) {
146608                             project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + info.fileName + " to open");
146609                             // Send the event only if the project got created as part of this open request and info is part of the project
146610                             if (!project.containsScriptInfo(info)) {
146611                                 // Since the file isnt part of configured project, do not send config file info
146612                                 configFileName = undefined;
146613                             }
146614                             else {
146615                                 configFileErrors = project.getAllProjectErrors();
146616                                 this.sendConfigFileDiagEvent(project, info.fileName);
146617                             }
146618                         }
146619                         else {
146620                             // Ensure project is ready to check if it contains opened script info
146621                             updateProjectIfDirty(project);
146622                         }
146623                         defaultConfigProject = project;
146624                         retainProjects = defaultConfigProject;
146625                         // If this configured project doesnt contain script info but
146626                         // it is solution with project references, try those project references
146627                         if (!project.containsScriptInfo(info) && project.isSolution()) {
146628                             forEachResolvedProjectReferenceProject(project, function (child, childConfigFileName) {
146629                                 updateProjectIfDirty(child);
146630                                 // Retain these projects
146631                                 if (!ts.isArray(retainProjects)) {
146632                                     retainProjects = [project, child];
146633                                 }
146634                                 else {
146635                                     retainProjects.push(child);
146636                                 }
146637                                 // If script info belongs to this child project, use this as default config project
146638                                 if (projectContainsInfoDirectly(child, info)) {
146639                                     configFileName = childConfigFileName;
146640                                     configFileErrors = child.getAllProjectErrors();
146641                                     _this.sendConfigFileDiagEvent(child, info.fileName);
146642                                     return child;
146643                                 }
146644                             }, ProjectReferenceProjectLoadKind.FindCreateLoad, "Creating project referenced in solution " + project.projectName + " to find possible configured project for " + info.fileName + " to open");
146645                         }
146646                         else {
146647                             // Create ancestor configured project
146648                             this.createAncestorProjects(info, defaultConfigProject || project);
146649                         }
146650                     }
146651                 }
146652                 // Project we have at this point is going to be updated since its either found through
146653                 // - external project search, which updates the project before checking if info is present in it
146654                 // - configured project - either created or updated to ensure we know correct status of info
146655                 // At this point we need to ensure that containing projects of the info are uptodate
146656                 // This will ensure that later question of info.isOrphan() will return correct answer
146657                 // and we correctly create inferred project for the info
146658                 info.containingProjects.forEach(updateProjectIfDirty);
146659                 // At this point if file is part of any any configured or external project, then it would be present in the containing projects
146660                 // So if it still doesnt have any containing projects, it needs to be part of inferred project
146661                 if (info.isOrphan()) {
146662                     // Even though this info did not belong to any of the configured projects, send the config file diag
146663                     if (ts.isArray(retainProjects)) {
146664                         retainProjects.forEach(function (project) { return _this.sendConfigFileDiagEvent(project, info.fileName); });
146665                     }
146666                     else if (retainProjects) {
146667                         this.sendConfigFileDiagEvent(retainProjects, info.fileName);
146668                     }
146669                     ts.Debug.assert(this.openFiles.has(info.path));
146670                     this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
146671                 }
146672                 ts.Debug.assert(!info.isOrphan());
146673                 return { configFileName: configFileName, configFileErrors: configFileErrors, retainProjects: retainProjects };
146674             };
146675             ProjectService.prototype.createAncestorProjects = function (info, project) {
146676                 // Skip if info is not part of default configured project
146677                 if (!info.isAttached(project))
146678                     return;
146679                 // Create configured project till project root
146680                 while (true) {
146681                     // Skip if project is not composite
146682                     if (!project.isInitialLoadPending() &&
146683                         (!project.getCompilerOptions().composite ||
146684                             project.getCompilerOptions().disableSolutionSearching))
146685                         return;
146686                     // Get config file name
146687                     var configFileName = this.getConfigFileNameForFile({
146688                         fileName: project.getConfigFilePath(),
146689                         path: info.path,
146690                         configFileInfo: true
146691                     });
146692                     if (!configFileName)
146693                         return;
146694                     // find or delay load the project
146695                     var ancestor = this.findConfiguredProjectByProjectName(configFileName) ||
146696                         this.createConfiguredProjectWithDelayLoad(configFileName, "Creating project possibly referencing default composite project " + project.getProjectName() + " of open file " + info.fileName);
146697                     if (ancestor.isInitialLoadPending()) {
146698                         // Set a potential project reference
146699                         ancestor.setPotentialProjectReference(project.canonicalConfigFilePath);
146700                     }
146701                     project = ancestor;
146702                 }
146703             };
146704             /*@internal*/
146705             ProjectService.prototype.loadAncestorProjectTree = function (forProjects) {
146706                 forProjects = forProjects || ts.mapDefinedMap(this.configuredProjects, function (project) { return !project.isInitialLoadPending() || undefined; });
146707                 var seenProjects = ts.createMap();
146708                 // Work on array copy as we could add more projects as part of callback
146709                 for (var _i = 0, _a = ts.arrayFrom(this.configuredProjects.values()); _i < _a.length; _i++) {
146710                     var project = _a[_i];
146711                     // If this project has potential project reference for any of the project we are loading ancestor tree for
146712                     // we need to load this project tree
146713                     if (forEachPotentialProjectReference(project, function (potentialRefPath) { return forProjects.has(potentialRefPath); }) || (project.isSolution() && forEachResolvedProjectReference(project, function (_ref, resolvedPath) { return forProjects.has(resolvedPath); }))) {
146714                         // Load children
146715                         this.ensureProjectChildren(project, seenProjects);
146716                     }
146717                 }
146718             };
146719             ProjectService.prototype.ensureProjectChildren = function (project, seenProjects) {
146720                 var _this = this;
146721                 if (!ts.addToSeen(seenProjects, project.canonicalConfigFilePath))
146722                     return;
146723                 // Update the project
146724                 updateProjectIfDirty(project);
146725                 // Create tree because project is uptodate we only care of resolved references
146726                 forEachResolvedProjectReferenceProject(project, function (child) { return _this.ensureProjectChildren(child, seenProjects); }, ProjectReferenceProjectLoadKind.FindCreateLoad, "Creating project for reference of project: " + project.projectName);
146727             };
146728             ProjectService.prototype.cleanupAfterOpeningFile = function (toRetainConfigProjects) {
146729                 // This was postponed from closeOpenFile to after opening next file,
146730                 // so that we can reuse the project if we need to right away
146731                 this.removeOrphanConfiguredProjects(toRetainConfigProjects);
146732                 // Remove orphan inferred projects now that we have reused projects
146733                 // We need to create a duplicate because we cant guarantee order after removal
146734                 for (var _i = 0, _a = this.inferredProjects.slice(); _i < _a.length; _i++) {
146735                     var inferredProject = _a[_i];
146736                     if (inferredProject.isOrphan()) {
146737                         this.removeProject(inferredProject);
146738                     }
146739                 }
146740                 // Delete the orphan files here because there might be orphan script infos (which are not part of project)
146741                 // when some file/s were closed which resulted in project removal.
146742                 // It was then postponed to cleanup these script infos so that they can be reused if
146743                 // the file from that old project is reopened because of opening file from here.
146744                 this.removeOrphanScriptInfos();
146745             };
146746             ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
146747                 var info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
146748                 var _a = this.assignProjectToOpenedScriptInfo(info), retainProjects = _a.retainProjects, result = __rest(_a, ["retainProjects"]);
146749                 this.cleanupAfterOpeningFile(retainProjects);
146750                 this.telemetryOnOpenFile(info);
146751                 this.printProjects();
146752                 return result;
146753             };
146754             ProjectService.prototype.removeOrphanConfiguredProjects = function (toRetainConfiguredProjects) {
146755                 var _this = this;
146756                 var toRemoveConfiguredProjects = ts.cloneMap(this.configuredProjects);
146757                 var markOriginalProjectsAsUsed = function (project) {
146758                     if (!project.isOrphan() && project.originalConfiguredProjects) {
146759                         project.originalConfiguredProjects.forEach(function (_value, configuredProjectPath) {
146760                             var project = _this.getConfiguredProjectByCanonicalConfigFilePath(configuredProjectPath);
146761                             return project && retainConfiguredProject(project);
146762                         });
146763                     }
146764                 };
146765                 if (toRetainConfiguredProjects) {
146766                     if (ts.isArray(toRetainConfiguredProjects)) {
146767                         toRetainConfiguredProjects.forEach(retainConfiguredProject);
146768                     }
146769                     else {
146770                         retainConfiguredProject(toRetainConfiguredProjects);
146771                     }
146772                 }
146773                 // Do not remove configured projects that are used as original projects of other
146774                 this.inferredProjects.forEach(markOriginalProjectsAsUsed);
146775                 this.externalProjects.forEach(markOriginalProjectsAsUsed);
146776                 this.configuredProjects.forEach(function (project) {
146777                     // If project has open ref (there are more than zero references from external project/open file), keep it alive as well as any project it references
146778                     if (project.hasOpenRef()) {
146779                         retainConfiguredProject(project);
146780                     }
146781                     else if (toRemoveConfiguredProjects.has(project.canonicalConfigFilePath)) {
146782                         // If the configured project for project reference has more than zero references, keep it alive
146783                         forEachReferencedProject(project, function (ref) { return isRetained(ref) && retainConfiguredProject(project); });
146784                     }
146785                 });
146786                 // Remove all the non marked projects
146787                 toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); });
146788                 function isRetained(project) {
146789                     return project.hasOpenRef() || !toRemoveConfiguredProjects.has(project.canonicalConfigFilePath);
146790                 }
146791                 function retainConfiguredProject(project) {
146792                     if (toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath)) {
146793                         // Keep original projects used
146794                         markOriginalProjectsAsUsed(project);
146795                         // Keep all the references alive
146796                         forEachReferencedProject(project, retainConfiguredProject);
146797                     }
146798                 }
146799             };
146800             ProjectService.prototype.removeOrphanScriptInfos = function () {
146801                 var _this = this;
146802                 var toRemoveScriptInfos = ts.cloneMap(this.filenameToScriptInfo);
146803                 this.filenameToScriptInfo.forEach(function (info) {
146804                     // If script info is open or orphan, retain it and its dependencies
146805                     if (!info.isScriptOpen() && info.isOrphan()) {
146806                         // Otherwise if there is any source info that is alive, this alive too
146807                         if (!info.sourceMapFilePath)
146808                             return;
146809                         var sourceInfos = void 0;
146810                         if (ts.isString(info.sourceMapFilePath)) {
146811                             var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath);
146812                             sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos;
146813                         }
146814                         else {
146815                             sourceInfos = info.sourceMapFilePath.sourceInfos;
146816                         }
146817                         if (!sourceInfos)
146818                             return;
146819                         if (!ts.forEachKey(sourceInfos, function (path) {
146820                             var info = _this.getScriptInfoForPath(path);
146821                             return !!info && (info.isScriptOpen() || !info.isOrphan());
146822                         })) {
146823                             return;
146824                         }
146825                     }
146826                     // Retain this script info
146827                     toRemoveScriptInfos.delete(info.path);
146828                     if (info.sourceMapFilePath) {
146829                         var sourceInfos = void 0;
146830                         if (ts.isString(info.sourceMapFilePath)) {
146831                             // And map file info and source infos
146832                             toRemoveScriptInfos.delete(info.sourceMapFilePath);
146833                             var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath);
146834                             sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos;
146835                         }
146836                         else {
146837                             sourceInfos = info.sourceMapFilePath.sourceInfos;
146838                         }
146839                         if (sourceInfos) {
146840                             sourceInfos.forEach(function (_value, path) { return toRemoveScriptInfos.delete(path); });
146841                         }
146842                     }
146843                 });
146844                 toRemoveScriptInfos.forEach(function (info) {
146845                     // if there are not projects that include this script info - delete it
146846                     _this.stopWatchingScriptInfo(info);
146847                     _this.deleteScriptInfo(info);
146848                     info.closeSourceMapFileWatcher();
146849                 });
146850             };
146851             ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) {
146852                 if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) {
146853                     return;
146854                 }
146855                 var project = scriptInfo.getDefaultProject();
146856                 if (!project.languageServiceEnabled) {
146857                     return;
146858                 }
146859                 var sourceFile = project.getSourceFile(scriptInfo.path);
146860                 var checkJs = !!sourceFile && !!sourceFile.checkJsDirective;
146861                 this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: { checkJs: checkJs } } });
146862             };
146863             ProjectService.prototype.closeClientFile = function (uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) {
146864                 var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
146865                 var result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
146866                 if (!skipAssignOrphanScriptInfosToInferredProject) {
146867                     this.printProjects();
146868                 }
146869                 return result;
146870             };
146871             ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, includeProjectReferenceRedirectInfo, result) {
146872                 var _loop_5 = function (proj) {
146873                     var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); });
146874                     result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo));
146875                 };
146876                 for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) {
146877                     var proj = currentProjects_1[_i];
146878                     _loop_5(proj);
146879                 }
146880             };
146881             /* @internal */
146882             ProjectService.prototype.synchronizeProjectList = function (knownProjects, includeProjectReferenceRedirectInfo) {
146883                 var files = [];
146884                 this.collectChanges(knownProjects, this.externalProjects, includeProjectReferenceRedirectInfo, files);
146885                 this.collectChanges(knownProjects, ts.arrayFrom(this.configuredProjects.values()), includeProjectReferenceRedirectInfo, files);
146886                 this.collectChanges(knownProjects, this.inferredProjects, includeProjectReferenceRedirectInfo, files);
146887                 return files;
146888             };
146889             /* @internal */
146890             ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
146891                 var _this = this;
146892                 var openScriptInfos;
146893                 var assignOrphanScriptInfosToInferredProject = false;
146894                 if (openFiles) {
146895                     while (true) {
146896                         var iterResult = openFiles.next();
146897                         if (iterResult.done)
146898                             break;
146899                         var file = iterResult.value;
146900                         // Create script infos so we have the new content for all the open files before we do any updates to projects
146901                         var info = this.getOrCreateOpenScriptInfo(server.toNormalizedPath(file.fileName), file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent, file.projectRootPath ? server.toNormalizedPath(file.projectRootPath) : undefined);
146902                         (openScriptInfos || (openScriptInfos = [])).push(info);
146903                     }
146904                 }
146905                 if (changedFiles) {
146906                     while (true) {
146907                         var iterResult = changedFiles.next();
146908                         if (iterResult.done)
146909                             break;
146910                         var file = iterResult.value;
146911                         var scriptInfo = this.getScriptInfo(file.fileName);
146912                         ts.Debug.assert(!!scriptInfo);
146913                         // Make edits to script infos and marks containing project as dirty
146914                         this.applyChangesToFile(scriptInfo, file.changes);
146915                     }
146916                 }
146917                 if (closedFiles) {
146918                     for (var _i = 0, closedFiles_1 = closedFiles; _i < closedFiles_1.length; _i++) {
146919                         var file = closedFiles_1[_i];
146920                         // Close files, but dont assign projects to orphan open script infos, that part comes later
146921                         assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ true) || assignOrphanScriptInfosToInferredProject;
146922                     }
146923                 }
146924                 // All the script infos now exist, so ok to go update projects for open files
146925                 var retainProjects;
146926                 if (openScriptInfos) {
146927                     retainProjects = ts.flatMap(openScriptInfos, function (info) { return _this.assignProjectToOpenedScriptInfo(info).retainProjects; });
146928                 }
146929                 // While closing files there could be open files that needed assigning new inferred projects, do it now
146930                 if (assignOrphanScriptInfosToInferredProject) {
146931                     this.assignOrphanScriptInfosToInferredProject();
146932                 }
146933                 if (openScriptInfos) {
146934                     // Cleanup projects
146935                     this.cleanupAfterOpeningFile(retainProjects);
146936                     // Telemetry
146937                     openScriptInfos.forEach(function (info) { return _this.telemetryOnOpenFile(info); });
146938                     this.printProjects();
146939                 }
146940                 else if (ts.length(closedFiles)) {
146941                     this.printProjects();
146942                 }
146943             };
146944             /* @internal */
146945             ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) {
146946                 while (true) {
146947                     var iterResult = changes.next();
146948                     if (iterResult.done)
146949                         break;
146950                     var change = iterResult.value;
146951                     scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
146952                 }
146953             };
146954             ProjectService.prototype.closeConfiguredProjectReferencedFromExternalProject = function (configFile) {
146955                 var configuredProject = this.findConfiguredProjectByProjectName(configFile);
146956                 if (configuredProject) {
146957                     configuredProject.deleteExternalProjectReference();
146958                     if (!configuredProject.hasOpenRef()) {
146959                         this.removeProject(configuredProject);
146960                         return;
146961                     }
146962                 }
146963             };
146964             ProjectService.prototype.closeExternalProject = function (uncheckedFileName) {
146965                 var fileName = server.toNormalizedPath(uncheckedFileName);
146966                 var configFiles = this.externalProjectToConfiguredProjectMap.get(fileName);
146967                 if (configFiles) {
146968                     for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) {
146969                         var configFile = configFiles_1[_i];
146970                         this.closeConfiguredProjectReferencedFromExternalProject(configFile);
146971                     }
146972                     this.externalProjectToConfiguredProjectMap.delete(fileName);
146973                 }
146974                 else {
146975                     // close external project
146976                     var externalProject = this.findExternalProjectByProjectName(uncheckedFileName);
146977                     if (externalProject) {
146978                         this.removeProject(externalProject);
146979                     }
146980                 }
146981             };
146982             ProjectService.prototype.openExternalProjects = function (projects) {
146983                 var _this = this;
146984                 // record project list before the update
146985                 var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; });
146986                 ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) {
146987                     projectsToClose.set(externalProjectName, true);
146988                 });
146989                 for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) {
146990                     var externalProject = projects_3[_i];
146991                     this.openExternalProject(externalProject);
146992                     // delete project that is present in input list
146993                     projectsToClose.delete(externalProject.projectFileName);
146994                 }
146995                 // close projects that were missing in the input list
146996                 ts.forEachKey(projectsToClose, function (externalProjectName) {
146997                     _this.closeExternalProject(externalProjectName);
146998                 });
146999             };
147000             ProjectService.escapeFilenameForRegex = function (filename) {
147001                 return filename.replace(this.filenameEscapeRegexp, "\\$&");
147002             };
147003             ProjectService.prototype.resetSafeList = function () {
147004                 this.safelist = defaultTypeSafeList;
147005             };
147006             ProjectService.prototype.applySafeList = function (proj) {
147007                 var _this = this;
147008                 var rootFiles = proj.rootFiles;
147009                 var typeAcquisition = proj.typeAcquisition;
147010                 ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now");
147011                 // If type acquisition has been explicitly disabled, do not exclude anything from the project
147012                 if (typeAcquisition.enable === false) {
147013                     return [];
147014                 }
147015                 var typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []);
147016                 var excludeRules = [];
147017                 var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); });
147018                 var excludedFiles = [];
147019                 var _loop_6 = function (name) {
147020                     var rule = this_2.safelist[name];
147021                     for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) {
147022                         var root = normalizedNames_1[_i];
147023                         if (rule.match.test(root)) {
147024                             this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'");
147025                             // If the file matches, collect its types packages and exclude rules
147026                             if (rule.types) {
147027                                 for (var _a = 0, _b = rule.types; _a < _b.length; _a++) {
147028                                     var type = _b[_a];
147029                                     // Best-effort de-duping here - doesn't need to be unduplicated but
147030                                     // we don't want the list to become a 400-element array of just 'kendo'
147031                                     if (typeAcqInclude.indexOf(type) < 0) {
147032                                         typeAcqInclude.push(type);
147033                                     }
147034                                 }
147035                             }
147036                             if (rule.exclude) {
147037                                 var _loop_8 = function (exclude) {
147038                                     var processedRule = root.replace(rule.match, function () {
147039                                         var groups = [];
147040                                         for (var _i = 0; _i < arguments.length; _i++) {
147041                                             groups[_i] = arguments[_i];
147042                                         }
147043                                         return exclude.map(function (groupNumberOrString) {
147044                                             // RegExp group numbers are 1-based, but the first element in groups
147045                                             // is actually the original string, so it all works out in the end.
147046                                             if (typeof groupNumberOrString === "number") {
147047                                                 if (!ts.isString(groups[groupNumberOrString])) {
147048                                                     // Specification was wrong - exclude nothing!
147049                                                     _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups");
147050                                                     // * can't appear in a filename; escape it because it's feeding into a RegExp
147051                                                     return "\\*";
147052                                                 }
147053                                                 return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]);
147054                                             }
147055                                             return groupNumberOrString;
147056                                         }).join("");
147057                                     });
147058                                     if (excludeRules.indexOf(processedRule) === -1) {
147059                                         excludeRules.push(processedRule);
147060                                     }
147061                                 };
147062                                 for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) {
147063                                     var exclude = _d[_c];
147064                                     _loop_8(exclude);
147065                                 }
147066                             }
147067                             else {
147068                                 // If not rules listed, add the default rule to exclude the matched file
147069                                 var escaped = ProjectService.escapeFilenameForRegex(root);
147070                                 if (excludeRules.indexOf(escaped) < 0) {
147071                                     excludeRules.push(escaped);
147072                                 }
147073                             }
147074                         }
147075                     }
147076                 };
147077                 var this_2 = this;
147078                 for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) {
147079                     var name = _a[_i];
147080                     _loop_6(name);
147081                 }
147082                 var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); });
147083                 var filesToKeep = [];
147084                 var _loop_7 = function (i) {
147085                     if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) {
147086                         excludedFiles.push(normalizedNames[i]);
147087                     }
147088                     else {
147089                         var exclude = false;
147090                         if (typeAcquisition.enable || typeAcquisition.enableAutoDiscovery) {
147091                             var baseName = ts.getBaseFileName(ts.toFileNameLowerCase(normalizedNames[i]));
147092                             if (ts.fileExtensionIs(baseName, "js")) {
147093                                 var inferredTypingName = ts.removeFileExtension(baseName);
147094                                 var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
147095                                 var typeName = this_3.legacySafelist.get(cleanedTypingName);
147096                                 if (typeName !== undefined) {
147097                                     this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist");
147098                                     excludedFiles.push(normalizedNames[i]);
147099                                     // *exclude* it from the project...
147100                                     exclude = true;
147101                                     // ... but *include* it in the list of types to acquire
147102                                     // Same best-effort dedupe as above
147103                                     if (typeAcqInclude.indexOf(typeName) < 0) {
147104                                         typeAcqInclude.push(typeName);
147105                                     }
147106                                 }
147107                             }
147108                         }
147109                         if (!exclude) {
147110                             // Exclude any minified files that get this far
147111                             if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) {
147112                                 excludedFiles.push(normalizedNames[i]);
147113                             }
147114                             else {
147115                                 filesToKeep.push(proj.rootFiles[i]);
147116                             }
147117                         }
147118                     }
147119                 };
147120                 var this_3 = this;
147121                 for (var i = 0; i < proj.rootFiles.length; i++) {
147122                     _loop_7(i);
147123                 }
147124                 proj.rootFiles = filesToKeep;
147125                 return excludedFiles;
147126             };
147127             ProjectService.prototype.openExternalProject = function (proj) {
147128                 // typingOptions has been deprecated and is only supported for backward compatibility
147129                 // purposes. It should be removed in future releases - use typeAcquisition instead.
147130                 if (proj.typingOptions && !proj.typeAcquisition) {
147131                     var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions);
147132                     proj.typeAcquisition = typeAcquisition;
147133                 }
147134                 proj.typeAcquisition = proj.typeAcquisition || {};
147135                 proj.typeAcquisition.include = proj.typeAcquisition.include || [];
147136                 proj.typeAcquisition.exclude = proj.typeAcquisition.exclude || [];
147137                 if (proj.typeAcquisition.enable === undefined) {
147138                     proj.typeAcquisition.enable = server.hasNoTypeScriptSource(proj.rootFiles.map(function (f) { return f.fileName; }));
147139                 }
147140                 var excludedFiles = this.applySafeList(proj);
147141                 var tsConfigFiles;
147142                 var rootFiles = [];
147143                 for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) {
147144                     var file = _a[_i];
147145                     var normalized = server.toNormalizedPath(file.fileName);
147146                     if (server.getBaseConfigFileName(normalized)) {
147147                         if (!this.syntaxOnly && this.host.fileExists(normalized)) {
147148                             (tsConfigFiles || (tsConfigFiles = [])).push(normalized);
147149                         }
147150                     }
147151                     else {
147152                         rootFiles.push(file);
147153                     }
147154                 }
147155                 // sort config files to simplify comparison later
147156                 if (tsConfigFiles) {
147157                     tsConfigFiles.sort();
147158                 }
147159                 var externalProject = this.findExternalProjectByProjectName(proj.projectFileName);
147160                 var exisingConfigFiles;
147161                 if (externalProject) {
147162                     externalProject.excludedFiles = excludedFiles;
147163                     if (!tsConfigFiles) {
147164                         var compilerOptions = convertCompilerOptions(proj.options);
147165                         var watchOptions = convertWatchOptions(proj.options);
147166                         var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, proj.rootFiles, externalFilePropertyReader);
147167                         if (lastFileExceededProgramSize) {
147168                             externalProject.disableLanguageService(lastFileExceededProgramSize);
147169                         }
147170                         else {
147171                             externalProject.enableLanguageService();
147172                         }
147173                         // external project already exists and not config files were added - update the project and return;
147174                         // The graph update here isnt postponed since any file open operation needs all updated external projects
147175                         this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, watchOptions);
147176                         externalProject.updateGraph();
147177                         return;
147178                     }
147179                     // some config files were added to external project (that previously were not there)
147180                     // close existing project and later we'll open a set of configured projects for these files
147181                     this.closeExternalProject(proj.projectFileName);
147182                 }
147183                 else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) {
147184                     // this project used to include config files
147185                     if (!tsConfigFiles) {
147186                         // config files were removed from the project - close existing external project which in turn will close configured projects
147187                         this.closeExternalProject(proj.projectFileName);
147188                     }
147189                     else {
147190                         // project previously had some config files - compare them with new set of files and close all configured projects that correspond to unused files
147191                         var oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName);
147192                         var iNew = 0;
147193                         var iOld = 0;
147194                         while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) {
147195                             var newConfig = tsConfigFiles[iNew];
147196                             var oldConfig = oldConfigFiles[iOld];
147197                             if (oldConfig < newConfig) {
147198                                 this.closeConfiguredProjectReferencedFromExternalProject(oldConfig);
147199                                 iOld++;
147200                             }
147201                             else if (oldConfig > newConfig) {
147202                                 iNew++;
147203                             }
147204                             else {
147205                                 // record existing config files so avoid extra add-refs
147206                                 (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig);
147207                                 iOld++;
147208                                 iNew++;
147209                             }
147210                         }
147211                         for (var i = iOld; i < oldConfigFiles.length; i++) {
147212                             // projects for all remaining old config files should be closed
147213                             this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]);
147214                         }
147215                     }
147216                 }
147217                 if (tsConfigFiles) {
147218                     // store the list of tsconfig files that belong to the external project
147219                     this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles);
147220                     for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) {
147221                         var tsconfigFile = tsConfigFiles_1[_b];
147222                         var project = this.findConfiguredProjectByProjectName(tsconfigFile);
147223                         if (!project) {
147224                             // errors are stored in the project, do not need to update the graph
147225                             project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ?
147226                                 this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) :
147227                                 this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName);
147228                         }
147229                         if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) {
147230                             // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project
147231                             project.addExternalProjectReference();
147232                         }
147233                     }
147234                 }
147235                 else {
147236                     // no config files - remove the item from the collection
147237                     // Create external project and update its graph, do not delay update since
147238                     // any file open operation needs all updated external projects
147239                     this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName);
147240                     var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles);
147241                     project.updateGraph();
147242                 }
147243             };
147244             ProjectService.prototype.hasDeferredExtension = function () {
147245                 for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { // TODO: GH#18217
147246                     var extension = _a[_i];
147247                     if (extension.scriptKind === 7 /* Deferred */) {
147248                         return true;
147249                     }
147250                 }
147251                 return false;
147252             };
147253             ProjectService.prototype.configurePlugin = function (args) {
147254                 // For any projects that already have the plugin loaded, configure the plugin
147255                 this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); });
147256                 // Also save the current configuration to pass on to any projects that are yet to be loaded.
147257                 // If a plugin is configured twice, only the latest configuration will be remembered.
147258                 this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || ts.createMap();
147259                 this.currentPluginConfigOverrides.set(args.pluginName, args.configuration);
147260             };
147261             /** Makes a filename safe to insert in a RegExp */
147262             ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g;
147263             return ProjectService;
147264         }());
147265         server.ProjectService = ProjectService;
147266         /* @internal */
147267         function isConfigFile(config) {
147268             return config.kind !== undefined;
147269         }
147270         server.isConfigFile = isConfigFile;
147271         function printProjectWithoutFileNames(project) {
147272             project.print(/*writeProjectFileNames*/ false);
147273         }
147274     })(server = ts.server || (ts.server = {}));
147275 })(ts || (ts = {}));
147276 /*@internal*/
147277 var ts;
147278 (function (ts) {
147279     var server;
147280     (function (server) {
147281         function createPackageJsonCache(project) {
147282             var packageJsons = ts.createMap();
147283             var directoriesWithoutPackageJson = ts.createMap();
147284             return {
147285                 addOrUpdate: addOrUpdate,
147286                 delete: function (fileName) {
147287                     packageJsons.delete(fileName);
147288                     directoriesWithoutPackageJson.set(ts.getDirectoryPath(fileName), true);
147289                 },
147290                 getInDirectory: function (directory) {
147291                     return packageJsons.get(ts.combinePaths(directory, "package.json")) || undefined;
147292                 },
147293                 directoryHasPackageJson: directoryHasPackageJson,
147294                 searchDirectoryAndAncestors: function (directory) {
147295                     ts.forEachAncestorDirectory(directory, function (ancestor) {
147296                         if (directoryHasPackageJson(ancestor) !== 1 /* Maybe */) {
147297                             return true;
147298                         }
147299                         var packageJsonFileName = project.toPath(ts.combinePaths(ancestor, "package.json"));
147300                         if (ts.tryFileExists(project, packageJsonFileName)) {
147301                             addOrUpdate(packageJsonFileName);
147302                         }
147303                         else {
147304                             directoriesWithoutPackageJson.set(ancestor, true);
147305                         }
147306                     });
147307                 },
147308             };
147309             function addOrUpdate(fileName) {
147310                 var packageJsonInfo = ts.createPackageJsonInfo(fileName, project);
147311                 if (packageJsonInfo !== undefined) {
147312                     packageJsons.set(fileName, packageJsonInfo);
147313                     directoriesWithoutPackageJson.delete(ts.getDirectoryPath(fileName));
147314                 }
147315             }
147316             function directoryHasPackageJson(directory) {
147317                 return packageJsons.has(ts.combinePaths(directory, "package.json")) ? -1 /* True */ :
147318                     directoriesWithoutPackageJson.has(directory) ? 0 /* False */ :
147319                         1 /* Maybe */;
147320             }
147321         }
147322         server.createPackageJsonCache = createPackageJsonCache;
147323     })(server = ts.server || (ts.server = {}));
147324 })(ts || (ts = {}));
147325 var ts;
147326 (function (ts) {
147327     var server;
147328     (function (server) {
147329         server.nullCancellationToken = {
147330             isCancellationRequested: function () { return false; },
147331             setRequest: function () { return void 0; },
147332             resetRequest: function () { return void 0; }
147333         };
147334         function hrTimeToMilliseconds(time) {
147335             var seconds = time[0];
147336             var nanoseconds = time[1];
147337             return ((1e9 * seconds) + nanoseconds) / 1000000.0;
147338         }
147339         function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) {
147340             // Checking for semantic diagnostics is an expensive process. We want to avoid it if we
147341             // know for sure it is not needed.
147342             // For instance, .d.ts files injected by ATA automatically do not produce any relevant
147343             // errors to a JS- only project.
147344             //
147345             // Note that configured projects can set skipLibCheck (on by default in jsconfig.json) to
147346             // disable checking for declaration files. We only need to verify for inferred projects (e.g.
147347             // miscellaneous context in VS) and external projects(e.g.VS.csproj project) with only JS
147348             // files.
147349             //
147350             // We still want to check .js files in a JS-only inferred or external project (e.g. if the
147351             // file has '// @ts-check').
147352             if ((server.isInferredProject(project) || server.isExternalProject(project)) &&
147353                 project.isJsOnlyProject()) {
147354                 var scriptInfo = project.getScriptInfoForNormalizedPath(file);
147355                 return scriptInfo && !scriptInfo.isJavaScript();
147356             }
147357             return false;
147358         }
147359         function dtsChangeCanAffectEmit(compilationSettings) {
147360             return ts.getEmitDeclarations(compilationSettings) || !!compilationSettings.emitDecoratorMetadata;
147361         }
147362         function formatDiag(fileName, project, diag) {
147363             var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); // TODO: GH#18217
147364             return {
147365                 start: scriptInfo.positionToLineOffset(diag.start),
147366                 end: scriptInfo.positionToLineOffset(diag.start + diag.length),
147367                 text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"),
147368                 code: diag.code,
147369                 category: ts.diagnosticCategoryName(diag),
147370                 reportsUnnecessary: diag.reportsUnnecessary,
147371                 source: diag.source,
147372                 relatedInformation: ts.map(diag.relatedInformation, formatRelatedInformation),
147373             };
147374         }
147375         function formatRelatedInformation(info) {
147376             if (!info.file) {
147377                 return {
147378                     message: ts.flattenDiagnosticMessageText(info.messageText, "\n"),
147379                     category: ts.diagnosticCategoryName(info),
147380                     code: info.code
147381                 };
147382             }
147383             return {
147384                 span: {
147385                     start: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start)),
147386                     end: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start + info.length)),
147387                     file: info.file.fileName
147388                 },
147389                 message: ts.flattenDiagnosticMessageText(info.messageText, "\n"),
147390                 category: ts.diagnosticCategoryName(info),
147391                 code: info.code
147392             };
147393         }
147394         function convertToLocation(lineAndCharacter) {
147395             return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 };
147396         }
147397         function formatDiagnosticToProtocol(diag, includeFileName) {
147398             var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); // TODO: GH#18217
147399             var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length))); // TODO: GH#18217
147400             var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n");
147401             var code = diag.code, source = diag.source;
147402             var category = ts.diagnosticCategoryName(diag);
147403             var common = {
147404                 start: start,
147405                 end: end,
147406                 text: text,
147407                 code: code,
147408                 category: category,
147409                 reportsUnnecessary: diag.reportsUnnecessary,
147410                 source: source,
147411                 relatedInformation: ts.map(diag.relatedInformation, formatRelatedInformation),
147412             };
147413             return includeFileName
147414                 ? __assign(__assign({}, common), { fileName: diag.file && diag.file.fileName }) : common;
147415         }
147416         function allEditsBeforePos(edits, pos) {
147417             return edits.every(function (edit) { return ts.textSpanEnd(edit.span) < pos; });
147418         }
147419         server.CommandNames = server.protocol.CommandTypes;
147420         function formatMessage(msg, logger, byteLength, newLine) {
147421             var verboseLogging = logger.hasLevel(server.LogLevel.verbose);
147422             var json = JSON.stringify(msg);
147423             if (verboseLogging) {
147424                 logger.info(msg.type + ":" + server.indent(json));
147425             }
147426             var len = byteLength(json, "utf8");
147427             return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine;
147428         }
147429         server.formatMessage = formatMessage;
147430         /**
147431          * Represents operation that can schedule its next step to be executed later.
147432          * Scheduling is done via instance of NextStep. If on current step subsequent step was not scheduled - operation is assumed to be completed.
147433          */
147434         var MultistepOperation = /** @class */ (function () {
147435             function MultistepOperation(operationHost) {
147436                 this.operationHost = operationHost;
147437             }
147438             MultistepOperation.prototype.startNew = function (action) {
147439                 this.complete();
147440                 this.requestId = this.operationHost.getCurrentRequestId();
147441                 this.executeAction(action);
147442             };
147443             MultistepOperation.prototype.complete = function () {
147444                 if (this.requestId !== undefined) {
147445                     this.operationHost.sendRequestCompletedEvent(this.requestId);
147446                     this.requestId = undefined;
147447                 }
147448                 this.setTimerHandle(undefined);
147449                 this.setImmediateId(undefined);
147450             };
147451             MultistepOperation.prototype.immediate = function (action) {
147452                 var _this = this;
147453                 var requestId = this.requestId;
147454                 ts.Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id");
147455                 this.setImmediateId(this.operationHost.getServerHost().setImmediate(function () {
147456                     _this.immediateId = undefined;
147457                     _this.operationHost.executeWithRequestId(requestId, function () { return _this.executeAction(action); });
147458                 }));
147459             };
147460             MultistepOperation.prototype.delay = function (ms, action) {
147461                 var _this = this;
147462                 var requestId = this.requestId;
147463                 ts.Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id");
147464                 this.setTimerHandle(this.operationHost.getServerHost().setTimeout(function () {
147465                     _this.timerHandle = undefined;
147466                     _this.operationHost.executeWithRequestId(requestId, function () { return _this.executeAction(action); });
147467                 }, ms));
147468             };
147469             MultistepOperation.prototype.executeAction = function (action) {
147470                 var stop = false;
147471                 try {
147472                     if (this.operationHost.isCancellationRequested()) {
147473                         stop = true;
147474                     }
147475                     else {
147476                         action(this);
147477                     }
147478                 }
147479                 catch (e) {
147480                     stop = true;
147481                     // ignore cancellation request
147482                     if (!(e instanceof ts.OperationCanceledException)) {
147483                         this.operationHost.logError(e, "delayed processing of request " + this.requestId);
147484                     }
147485                 }
147486                 if (stop || !this.hasPendingWork()) {
147487                     this.complete();
147488                 }
147489             };
147490             MultistepOperation.prototype.setTimerHandle = function (timerHandle) {
147491                 if (this.timerHandle !== undefined) {
147492                     this.operationHost.getServerHost().clearTimeout(this.timerHandle);
147493                 }
147494                 this.timerHandle = timerHandle;
147495             };
147496             MultistepOperation.prototype.setImmediateId = function (immediateId) {
147497                 if (this.immediateId !== undefined) {
147498                     this.operationHost.getServerHost().clearImmediate(this.immediateId);
147499                 }
147500                 this.immediateId = immediateId;
147501             };
147502             MultistepOperation.prototype.hasPendingWork = function () {
147503                 return !!this.timerHandle || !!this.immediateId;
147504             };
147505             return MultistepOperation;
147506         }());
147507         /** @internal */
147508         function toEvent(eventName, body) {
147509             return {
147510                 seq: 0,
147511                 type: "event",
147512                 event: eventName,
147513                 body: body
147514             };
147515         }
147516         server.toEvent = toEvent;
147517         /**
147518          * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project.
147519          */
147520         function combineProjectOutput(defaultValue, getValue, projects, action) {
147521             var outputs = ts.flatMapToMutable(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); });
147522             if (!ts.isArray(projects) && projects.symLinkedProjects) {
147523                 projects.symLinkedProjects.forEach(function (projects, path) {
147524                     var value = getValue(path);
147525                     outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); }));
147526                 });
147527             }
147528             return ts.deduplicate(outputs, ts.equateValues);
147529         }
147530         function combineProjectOutputFromEveryProject(projectService, action, areEqual) {
147531             var outputs = [];
147532             projectService.loadAncestorProjectTree();
147533             projectService.forEachEnabledProject(function (project) {
147534                 var theseOutputs = action(project);
147535                 outputs.push.apply(outputs, theseOutputs.filter(function (output) { return !outputs.some(function (o) { return areEqual(o, output); }); }));
147536             });
147537             return outputs;
147538         }
147539         function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) {
147540             var outputs = [];
147541             combineProjectOutputWorker(projects, defaultProject, 
147542             /*initialLocation*/ undefined, function (project, _, tryAddToTodo) {
147543                 for (var _i = 0, _a = action(project); _i < _a.length; _i++) {
147544                     var output = _a[_i];
147545                     if (!ts.contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) {
147546                         outputs.push(output);
147547                     }
147548                 }
147549             });
147550             return outputs;
147551         }
147552         function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, hostPreferences) {
147553             var outputs = [];
147554             combineProjectOutputWorker(projects, defaultProject, initialLocation, function (project, location, tryAddToTodo) {
147555                 for (var _i = 0, _a = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || server.emptyArray; _i < _a.length; _i++) {
147556                     var output = _a[_i];
147557                     if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) {
147558                         outputs.push(output);
147559                     }
147560                 }
147561             });
147562             return outputs;
147563         }
147564         function getDefinitionLocation(defaultProject, initialLocation) {
147565             var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos);
147566             var info = infos && ts.firstOrUndefined(infos);
147567             return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : undefined;
147568         }
147569         function combineProjectOutputForReferences(projects, defaultProject, initialLocation) {
147570             var outputs = [];
147571             combineProjectOutputWorker(projects, defaultProject, initialLocation, function (project, location, getMappedLocation) {
147572                 var _loop_9 = function (outputReferencedSymbol) {
147573                     var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition));
147574                     var definition = mappedDefinitionFile === undefined ?
147575                         outputReferencedSymbol.definition : __assign(__assign({}, outputReferencedSymbol.definition), { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName, contextSpan: getMappedContextSpan(outputReferencedSymbol.definition, project) });
147576                     var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); });
147577                     if (!symbolToAddTo) {
147578                         symbolToAddTo = { definition: definition, references: [] };
147579                         outputs.push(symbolToAddTo);
147580                     }
147581                     for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) {
147582                         var ref = _a[_i];
147583                         // If it's in a mapped file, that is added to the todo list by `getMappedLocation`.
147584                         if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) {
147585                             symbolToAddTo.references.push(ref);
147586                         }
147587                     }
147588                 };
147589                 for (var _i = 0, _a = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _a.length; _i++) {
147590                     var outputReferencedSymbol = _a[_i];
147591                     _loop_9(outputReferencedSymbol);
147592                 }
147593             });
147594             return outputs.filter(function (o) { return o.references.length !== 0; });
147595         }
147596         function forEachProjectInProjects(projects, path, cb) {
147597             for (var _i = 0, _a = ts.isArray(projects) ? projects : projects.projects; _i < _a.length; _i++) {
147598                 var project = _a[_i];
147599                 cb(project, path);
147600             }
147601             if (!ts.isArray(projects) && projects.symLinkedProjects) {
147602                 projects.symLinkedProjects.forEach(function (symlinkedProjects, symlinkedPath) {
147603                     for (var _i = 0, symlinkedProjects_1 = symlinkedProjects; _i < symlinkedProjects_1.length; _i++) {
147604                         var project = symlinkedProjects_1[_i];
147605                         cb(project, symlinkedPath);
147606                     }
147607                 });
147608             }
147609         }
147610         function combineProjectOutputWorker(projects, defaultProject, initialLocation, cb) {
147611             var projectService = defaultProject.projectService;
147612             var toDo;
147613             var seenProjects = ts.createMap();
147614             forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) {
147615                 // TLocation should be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid.
147616                 var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined);
147617                 toDo = callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb);
147618             });
147619             // After initial references are collected, go over every other project and see if it has a reference for the symbol definition.
147620             if (initialLocation) {
147621                 var defaultDefinition_1 = getDefinitionLocation(defaultProject, initialLocation);
147622                 if (defaultDefinition_1) {
147623                     var getGeneratedDefinition_1 = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition_1.fileName) ?
147624                         defaultDefinition_1 :
147625                         defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition_1); });
147626                     var getSourceDefinition_1 = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition_1.fileName) ?
147627                         defaultDefinition_1 :
147628                         defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition_1); });
147629                     projectService.loadAncestorProjectTree(seenProjects);
147630                     projectService.forEachEnabledProject(function (project) {
147631                         if (!addToSeen(seenProjects, project))
147632                             return;
147633                         var definition = mapDefinitionInProject(defaultDefinition_1, project, getGeneratedDefinition_1, getSourceDefinition_1);
147634                         if (definition) {
147635                             toDo = callbackProjectAndLocation(project, definition, projectService, toDo, seenProjects, cb);
147636                         }
147637                     });
147638                 }
147639             }
147640             while (toDo && toDo.length) {
147641                 var next = toDo.pop();
147642                 ts.Debug.assertIsDefined(next);
147643                 toDo = callbackProjectAndLocation(next.project, next.location, projectService, toDo, seenProjects, cb);
147644             }
147645         }
147646         function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) {
147647             // If the definition is actually from the project, definition is correct as is
147648             if (project.containsFile(server.toNormalizedPath(definition.fileName)) &&
147649                 !isLocationProjectReferenceRedirect(project, definition)) {
147650                 return definition;
147651             }
147652             var generatedDefinition = getGeneratedDefinition();
147653             if (generatedDefinition && project.containsFile(server.toNormalizedPath(generatedDefinition.fileName)))
147654                 return generatedDefinition;
147655             var sourceDefinition = getSourceDefinition();
147656             return sourceDefinition && project.containsFile(server.toNormalizedPath(sourceDefinition.fileName)) ? sourceDefinition : undefined;
147657         }
147658         function isLocationProjectReferenceRedirect(project, location) {
147659             if (!location)
147660                 return false;
147661             var program = project.getLanguageService().getProgram();
147662             if (!program)
147663                 return false;
147664             var sourceFile = program.getSourceFile(location.fileName);
147665             // It is possible that location is attached to project but
147666             // the program actually includes its redirect instead.
147667             // This happens when rootFile in project is one of the file from referenced project
147668             // Thus root is attached but program doesnt have the actual .ts file but .d.ts
147669             // If this is not the file we were actually looking, return rest of the toDo
147670             return !!sourceFile &&
147671                 sourceFile.resolvedPath !== sourceFile.path &&
147672                 sourceFile.resolvedPath !== project.toPath(location.fileName);
147673         }
147674         function callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb) {
147675             if (project.getCancellationToken().isCancellationRequested())
147676                 return undefined; // Skip rest of toDo if cancelled
147677             // If this is not the file we were actually looking, return rest of the toDo
147678             if (isLocationProjectReferenceRedirect(project, location))
147679                 return toDo;
147680             cb(project, location, function (innerProject, location) {
147681                 addToSeen(seenProjects, project);
147682                 var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(innerProject, location);
147683                 if (!originalLocation)
147684                     return undefined;
147685                 var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName);
147686                 toDo = toDo || [];
147687                 for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) {
147688                     var project_1 = _a[_i];
147689                     addToTodo(project_1, originalLocation, toDo, seenProjects);
147690                 }
147691                 var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo);
147692                 if (symlinkedProjectsMap) {
147693                     symlinkedProjectsMap.forEach(function (symlinkedProjects, symlinkedPath) {
147694                         for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) {
147695                             var symlinkedProject = symlinkedProjects_2[_i];
147696                             addToTodo(symlinkedProject, { fileName: symlinkedPath, pos: originalLocation.pos }, toDo, seenProjects);
147697                         }
147698                     });
147699                 }
147700                 return originalLocation === location ? undefined : originalLocation;
147701             });
147702             return toDo;
147703         }
147704         function addToTodo(project, location, toDo, seenProjects) {
147705             if (addToSeen(seenProjects, project))
147706                 toDo.push({ project: project, location: location });
147707         }
147708         function addToSeen(seenProjects, project) {
147709             return ts.addToSeen(seenProjects, getProjectKey(project));
147710         }
147711         function getProjectKey(project) {
147712             return server.isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName();
147713         }
147714         function documentSpanLocation(_a) {
147715             var fileName = _a.fileName, textSpan = _a.textSpan;
147716             return { fileName: fileName, pos: textSpan.start };
147717         }
147718         function getMappedLocation(location, project) {
147719             var mapsTo = project.getSourceMapper().tryGetSourcePosition(location);
147720             return mapsTo && project.projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined;
147721         }
147722         function getMappedDocumentSpan(documentSpan, project) {
147723             var newPosition = getMappedLocation(documentSpanLocation(documentSpan), project);
147724             if (!newPosition)
147725                 return undefined;
147726             return {
147727                 fileName: newPosition.fileName,
147728                 textSpan: {
147729                     start: newPosition.pos,
147730                     length: documentSpan.textSpan.length
147731                 },
147732                 originalFileName: documentSpan.fileName,
147733                 originalTextSpan: documentSpan.textSpan,
147734                 contextSpan: getMappedContextSpan(documentSpan, project),
147735                 originalContextSpan: documentSpan.contextSpan
147736             };
147737         }
147738         function getMappedContextSpan(documentSpan, project) {
147739             var contextSpanStart = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, project);
147740             var contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, project);
147741             return contextSpanStart && contextSpanEnd ?
147742                 { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } :
147743                 undefined;
147744         }
147745         var Session = /** @class */ (function () {
147746             function Session(opts) {
147747                 var _a;
147748                 var _this = this;
147749                 this.changeSeq = 0;
147750                 this.handlers = ts.createMapFromTemplate((_a = {},
147751                     _a[server.CommandNames.Status] = function () {
147752                         var response = { version: ts.version }; // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
147753                         return _this.requiredResponse(response);
147754                     },
147755                     _a[server.CommandNames.OpenExternalProject] = function (request) {
147756                         _this.projectService.openExternalProject(request.arguments);
147757                         // TODO: GH#20447 report errors
147758                         return _this.requiredResponse(/*response*/ true);
147759                     },
147760                     _a[server.CommandNames.OpenExternalProjects] = function (request) {
147761                         _this.projectService.openExternalProjects(request.arguments.projects);
147762                         // TODO: GH#20447 report errors
147763                         return _this.requiredResponse(/*response*/ true);
147764                     },
147765                     _a[server.CommandNames.CloseExternalProject] = function (request) {
147766                         _this.projectService.closeExternalProject(request.arguments.projectFileName);
147767                         // TODO: GH#20447 report errors
147768                         return _this.requiredResponse(/*response*/ true);
147769                     },
147770                     _a[server.CommandNames.SynchronizeProjectList] = function (request) {
147771                         var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects, request.arguments.includeProjectReferenceRedirectInfo);
147772                         if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) {
147773                             return _this.requiredResponse(result);
147774                         }
147775                         var converted = ts.map(result, function (p) {
147776                             if (!p.projectErrors || p.projectErrors.length === 0) {
147777                                 return p;
147778                             }
147779                             return {
147780                                 info: p.info,
147781                                 changes: p.changes,
147782                                 files: p.files,
147783                                 projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ undefined)
147784                             };
147785                         });
147786                         return _this.requiredResponse(converted);
147787                     },
147788                     _a[server.CommandNames.UpdateOpen] = function (request) {
147789                         _this.changeSeq++;
147790                         _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.mapIterator(ts.arrayIterator(request.arguments.openFiles), function (file) { return ({
147791                             fileName: file.file,
147792                             content: file.fileContent,
147793                             scriptKind: file.scriptKindName,
147794                             projectRootPath: file.projectRootPath
147795                         }); }), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
147796                             fileName: file.fileName,
147797                             changes: ts.mapDefinedIterator(ts.arrayReverseIterator(file.textChanges), function (change) {
147798                                 var scriptInfo = ts.Debug.checkDefined(_this.projectService.getScriptInfo(file.fileName));
147799                                 var start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
147800                                 var end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
147801                                 return start >= 0 ? { span: { start: start, length: end - start }, newText: change.newText } : undefined;
147802                             })
147803                         }); }), request.arguments.closedFiles);
147804                         return _this.requiredResponse(/*response*/ true);
147805                     },
147806                     _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) {
147807                         _this.changeSeq++;
147808                         _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.arrayIterator(request.arguments.openFiles), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
147809                             fileName: file.fileName,
147810                             // apply changes in reverse order
147811                             changes: ts.arrayReverseIterator(file.changes)
147812                         }); }), request.arguments.closedFiles);
147813                         // TODO: report errors
147814                         return _this.requiredResponse(/*response*/ true);
147815                     },
147816                     _a[server.CommandNames.Exit] = function () {
147817                         _this.exit();
147818                         return _this.notRequired();
147819                     },
147820                     _a[server.CommandNames.Definition] = function (request) {
147821                         return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ true));
147822                     },
147823                     _a[server.CommandNames.DefinitionFull] = function (request) {
147824                         return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ false));
147825                     },
147826                     _a[server.CommandNames.DefinitionAndBoundSpan] = function (request) {
147827                         return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ true));
147828                     },
147829                     _a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) {
147830                         return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ false));
147831                     },
147832                     _a[server.CommandNames.EmitOutput] = function (request) {
147833                         return _this.requiredResponse(_this.getEmitOutput(request.arguments));
147834                     },
147835                     _a[server.CommandNames.TypeDefinition] = function (request) {
147836                         return _this.requiredResponse(_this.getTypeDefinition(request.arguments));
147837                     },
147838                     _a[server.CommandNames.Implementation] = function (request) {
147839                         return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ true));
147840                     },
147841                     _a[server.CommandNames.ImplementationFull] = function (request) {
147842                         return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ false));
147843                     },
147844                     _a[server.CommandNames.References] = function (request) {
147845                         return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ true));
147846                     },
147847                     _a[server.CommandNames.ReferencesFull] = function (request) {
147848                         return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ false));
147849                     },
147850                     _a[server.CommandNames.Rename] = function (request) {
147851                         return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ true));
147852                     },
147853                     _a[server.CommandNames.RenameLocationsFull] = function (request) {
147854                         return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ false));
147855                     },
147856                     _a[server.CommandNames.RenameInfoFull] = function (request) {
147857                         return _this.requiredResponse(_this.getRenameInfo(request.arguments));
147858                     },
147859                     _a[server.CommandNames.Open] = function (request) {
147860                         _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), // TODO: GH#18217
147861                         request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined);
147862                         return _this.notRequired();
147863                     },
147864                     _a[server.CommandNames.Quickinfo] = function (request) {
147865                         return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ true));
147866                     },
147867                     _a[server.CommandNames.QuickinfoFull] = function (request) {
147868                         return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ false));
147869                     },
147870                     _a[server.CommandNames.GetOutliningSpans] = function (request) {
147871                         return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ true));
147872                     },
147873                     _a[server.CommandNames.GetOutliningSpansFull] = function (request) {
147874                         return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ false));
147875                     },
147876                     _a[server.CommandNames.TodoComments] = function (request) {
147877                         return _this.requiredResponse(_this.getTodoComments(request.arguments));
147878                     },
147879                     _a[server.CommandNames.Indentation] = function (request) {
147880                         return _this.requiredResponse(_this.getIndentation(request.arguments));
147881                     },
147882                     _a[server.CommandNames.NameOrDottedNameSpan] = function (request) {
147883                         return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments));
147884                     },
147885                     _a[server.CommandNames.BreakpointStatement] = function (request) {
147886                         return _this.requiredResponse(_this.getBreakpointStatement(request.arguments));
147887                     },
147888                     _a[server.CommandNames.BraceCompletion] = function (request) {
147889                         return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments));
147890                     },
147891                     _a[server.CommandNames.DocCommentTemplate] = function (request) {
147892                         return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments));
147893                     },
147894                     _a[server.CommandNames.GetSpanOfEnclosingComment] = function (request) {
147895                         return _this.requiredResponse(_this.getSpanOfEnclosingComment(request.arguments));
147896                     },
147897                     _a[server.CommandNames.Format] = function (request) {
147898                         return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments));
147899                     },
147900                     _a[server.CommandNames.Formatonkey] = function (request) {
147901                         return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments));
147902                     },
147903                     _a[server.CommandNames.FormatFull] = function (request) {
147904                         return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments));
147905                     },
147906                     _a[server.CommandNames.FormatonkeyFull] = function (request) {
147907                         return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments));
147908                     },
147909                     _a[server.CommandNames.FormatRangeFull] = function (request) {
147910                         return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments));
147911                     },
147912                     _a[server.CommandNames.CompletionInfo] = function (request) {
147913                         return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionInfo));
147914                     },
147915                     _a[server.CommandNames.Completions] = function (request) {
147916                         return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.Completions));
147917                     },
147918                     _a[server.CommandNames.CompletionsFull] = function (request) {
147919                         return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull));
147920                     },
147921                     _a[server.CommandNames.CompletionDetails] = function (request) {
147922                         return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true));
147923                     },
147924                     _a[server.CommandNames.CompletionDetailsFull] = function (request) {
147925                         return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false));
147926                     },
147927                     _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) {
147928                         return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments));
147929                     },
147930                     _a[server.CommandNames.CompileOnSaveEmitFile] = function (request) {
147931                         return _this.requiredResponse(_this.emitFile(request.arguments));
147932                     },
147933                     _a[server.CommandNames.SignatureHelp] = function (request) {
147934                         return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ true));
147935                     },
147936                     _a[server.CommandNames.SignatureHelpFull] = function (request) {
147937                         return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ false));
147938                     },
147939                     _a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) {
147940                         return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments));
147941                     },
147942                     _a[server.CommandNames.EncodedSyntacticClassificationsFull] = function (request) {
147943                         return _this.requiredResponse(_this.getEncodedSyntacticClassifications(request.arguments));
147944                     },
147945                     _a[server.CommandNames.EncodedSemanticClassificationsFull] = function (request) {
147946                         return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments));
147947                     },
147948                     _a[server.CommandNames.Cleanup] = function () {
147949                         _this.cleanup();
147950                         return _this.requiredResponse(/*response*/ true);
147951                     },
147952                     _a[server.CommandNames.SemanticDiagnosticsSync] = function (request) {
147953                         return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments));
147954                     },
147955                     _a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) {
147956                         return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments));
147957                     },
147958                     _a[server.CommandNames.SuggestionDiagnosticsSync] = function (request) {
147959                         return _this.requiredResponse(_this.getSuggestionDiagnosticsSync(request.arguments));
147960                     },
147961                     _a[server.CommandNames.Geterr] = function (request) {
147962                         _this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); });
147963                         return _this.notRequired();
147964                     },
147965                     _a[server.CommandNames.GeterrForProject] = function (request) {
147966                         _this.errorCheck.startNew(function (next) { return _this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file); });
147967                         return _this.notRequired();
147968                     },
147969                     _a[server.CommandNames.Change] = function (request) {
147970                         _this.change(request.arguments);
147971                         return _this.notRequired();
147972                     },
147973                     _a[server.CommandNames.Configure] = function (request) {
147974                         _this.projectService.setHostConfiguration(request.arguments);
147975                         _this.doOutput(/*info*/ undefined, server.CommandNames.Configure, request.seq, /*success*/ true);
147976                         return _this.notRequired();
147977                     },
147978                     _a[server.CommandNames.Reload] = function (request) {
147979                         _this.reload(request.arguments, request.seq);
147980                         return _this.requiredResponse({ reloadFinished: true });
147981                     },
147982                     _a[server.CommandNames.Saveto] = function (request) {
147983                         var savetoArgs = request.arguments;
147984                         _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
147985                         return _this.notRequired();
147986                     },
147987                     _a[server.CommandNames.Close] = function (request) {
147988                         var closeArgs = request.arguments;
147989                         _this.closeClientFile(closeArgs.file);
147990                         return _this.notRequired();
147991                     },
147992                     _a[server.CommandNames.Navto] = function (request) {
147993                         return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ true));
147994                     },
147995                     _a[server.CommandNames.NavtoFull] = function (request) {
147996                         return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ false));
147997                     },
147998                     _a[server.CommandNames.Brace] = function (request) {
147999                         return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ true));
148000                     },
148001                     _a[server.CommandNames.BraceFull] = function (request) {
148002                         return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ false));
148003                     },
148004                     _a[server.CommandNames.NavBar] = function (request) {
148005                         return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ true));
148006                     },
148007                     _a[server.CommandNames.NavBarFull] = function (request) {
148008                         return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ false));
148009                     },
148010                     _a[server.CommandNames.NavTree] = function (request) {
148011                         return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ true));
148012                     },
148013                     _a[server.CommandNames.NavTreeFull] = function (request) {
148014                         return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ false));
148015                     },
148016                     _a[server.CommandNames.Occurrences] = function (request) {
148017                         return _this.requiredResponse(_this.getOccurrences(request.arguments));
148018                     },
148019                     _a[server.CommandNames.DocumentHighlights] = function (request) {
148020                         return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ true));
148021                     },
148022                     _a[server.CommandNames.DocumentHighlightsFull] = function (request) {
148023                         return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false));
148024                     },
148025                     _a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) {
148026                         _this.setCompilerOptionsForInferredProjects(request.arguments);
148027                         return _this.requiredResponse(/*response*/ true);
148028                     },
148029                     _a[server.CommandNames.ProjectInfo] = function (request) {
148030                         return _this.requiredResponse(_this.getProjectInfo(request.arguments));
148031                     },
148032                     _a[server.CommandNames.ReloadProjects] = function () {
148033                         _this.projectService.reloadProjects();
148034                         return _this.notRequired();
148035                     },
148036                     _a[server.CommandNames.JsxClosingTag] = function (request) {
148037                         return _this.requiredResponse(_this.getJsxClosingTag(request.arguments));
148038                     },
148039                     _a[server.CommandNames.GetCodeFixes] = function (request) {
148040                         return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ true));
148041                     },
148042                     _a[server.CommandNames.GetCodeFixesFull] = function (request) {
148043                         return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ false));
148044                     },
148045                     _a[server.CommandNames.GetCombinedCodeFix] = function (request) {
148046                         return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ true));
148047                     },
148048                     _a[server.CommandNames.GetCombinedCodeFixFull] = function (request) {
148049                         return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ false));
148050                     },
148051                     _a[server.CommandNames.ApplyCodeActionCommand] = function (request) {
148052                         return _this.requiredResponse(_this.applyCodeActionCommand(request.arguments));
148053                     },
148054                     _a[server.CommandNames.GetSupportedCodeFixes] = function () {
148055                         return _this.requiredResponse(_this.getSupportedCodeFixes());
148056                     },
148057                     _a[server.CommandNames.GetApplicableRefactors] = function (request) {
148058                         return _this.requiredResponse(_this.getApplicableRefactors(request.arguments));
148059                     },
148060                     _a[server.CommandNames.GetEditsForRefactor] = function (request) {
148061                         return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ true));
148062                     },
148063                     _a[server.CommandNames.GetEditsForRefactorFull] = function (request) {
148064                         return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ false));
148065                     },
148066                     _a[server.CommandNames.OrganizeImports] = function (request) {
148067                         return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ true));
148068                     },
148069                     _a[server.CommandNames.OrganizeImportsFull] = function (request) {
148070                         return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ false));
148071                     },
148072                     _a[server.CommandNames.GetEditsForFileRename] = function (request) {
148073                         return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ true));
148074                     },
148075                     _a[server.CommandNames.GetEditsForFileRenameFull] = function (request) {
148076                         return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ false));
148077                     },
148078                     _a[server.CommandNames.ConfigurePlugin] = function (request) {
148079                         _this.configurePlugin(request.arguments);
148080                         _this.doOutput(/*info*/ undefined, server.CommandNames.ConfigurePlugin, request.seq, /*success*/ true);
148081                         return _this.notRequired();
148082                     },
148083                     _a[server.CommandNames.SelectionRange] = function (request) {
148084                         return _this.requiredResponse(_this.getSmartSelectionRange(request.arguments, /*simplifiedResult*/ true));
148085                     },
148086                     _a[server.CommandNames.SelectionRangeFull] = function (request) {
148087                         return _this.requiredResponse(_this.getSmartSelectionRange(request.arguments, /*simplifiedResult*/ false));
148088                     },
148089                     _a[server.CommandNames.PrepareCallHierarchy] = function (request) {
148090                         return _this.requiredResponse(_this.prepareCallHierarchy(request.arguments));
148091                     },
148092                     _a[server.CommandNames.ProvideCallHierarchyIncomingCalls] = function (request) {
148093                         return _this.requiredResponse(_this.provideCallHierarchyIncomingCalls(request.arguments));
148094                     },
148095                     _a[server.CommandNames.ProvideCallHierarchyOutgoingCalls] = function (request) {
148096                         return _this.requiredResponse(_this.provideCallHierarchyOutgoingCalls(request.arguments));
148097                     },
148098                     _a));
148099                 this.host = opts.host;
148100                 this.cancellationToken = opts.cancellationToken;
148101                 this.typingsInstaller = opts.typingsInstaller;
148102                 this.byteLength = opts.byteLength;
148103                 this.hrtime = opts.hrtime;
148104                 this.logger = opts.logger;
148105                 this.canUseEvents = opts.canUseEvents;
148106                 this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents;
148107                 this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate;
148108                 var throttleWaitMilliseconds = opts.throttleWaitMilliseconds;
148109                 this.eventHandler = this.canUseEvents
148110                     ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); })
148111                     : undefined;
148112                 var multistepOperationHost = {
148113                     executeWithRequestId: function (requestId, action) { return _this.executeWithRequestId(requestId, action); },
148114                     getCurrentRequestId: function () { return _this.currentRequestId; },
148115                     getServerHost: function () { return _this.host; },
148116                     logError: function (err, cmd) { return _this.logError(err, cmd); },
148117                     sendRequestCompletedEvent: function (requestId) { return _this.sendRequestCompletedEvent(requestId); },
148118                     isCancellationRequested: function () { return _this.cancellationToken.isCancellationRequested(); }
148119                 };
148120                 this.errorCheck = new MultistepOperation(multistepOperationHost);
148121                 var settings = {
148122                     host: this.host,
148123                     logger: this.logger,
148124                     cancellationToken: this.cancellationToken,
148125                     useSingleInferredProject: opts.useSingleInferredProject,
148126                     useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot,
148127                     typingsInstaller: this.typingsInstaller,
148128                     throttleWaitMilliseconds: throttleWaitMilliseconds,
148129                     eventHandler: this.eventHandler,
148130                     suppressDiagnosticEvents: this.suppressDiagnosticEvents,
148131                     globalPlugins: opts.globalPlugins,
148132                     pluginProbeLocations: opts.pluginProbeLocations,
148133                     allowLocalPluginLoads: opts.allowLocalPluginLoads,
148134                     typesMapLocation: opts.typesMapLocation,
148135                     syntaxOnly: opts.syntaxOnly,
148136                 };
148137                 this.projectService = new server.ProjectService(settings);
148138                 this.projectService.setPerformanceEventHandler(this.performanceEventHandler.bind(this));
148139                 this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger);
148140             }
148141             Session.prototype.sendRequestCompletedEvent = function (requestId) {
148142                 this.event({ request_seq: requestId }, "requestCompleted");
148143             };
148144             Session.prototype.performanceEventHandler = function (event) {
148145                 switch (event.kind) {
148146                     case "UpdateGraph": {
148147                         this.updateGraphDurationMs = (this.updateGraphDurationMs || 0) + event.durationMs;
148148                         break;
148149                     }
148150                 }
148151             };
148152             Session.prototype.defaultEventHandler = function (event) {
148153                 switch (event.eventName) {
148154                     case server.ProjectsUpdatedInBackgroundEvent:
148155                         var openFiles = event.data.openFiles;
148156                         this.projectsUpdatedInBackgroundEvent(openFiles);
148157                         break;
148158                     case server.ProjectLoadingStartEvent:
148159                         var _a = event.data, project = _a.project, reason = _a.reason;
148160                         this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent);
148161                         break;
148162                     case server.ProjectLoadingFinishEvent:
148163                         var finishProject = event.data.project;
148164                         this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingFinishEvent);
148165                         break;
148166                     case server.LargeFileReferencedEvent:
148167                         var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize;
148168                         this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent);
148169                         break;
148170                     case server.ConfigFileDiagEvent:
148171                         var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics;
148172                         var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatDiagnosticToProtocol(diagnostic, /*includeFileName*/ true); });
148173                         this.event({
148174                             triggerFile: triggerFile,
148175                             configFile: configFile,
148176                             diagnostics: bakedDiags
148177                         }, server.ConfigFileDiagEvent);
148178                         break;
148179                     case server.ProjectLanguageServiceStateEvent: {
148180                         var eventName = server.ProjectLanguageServiceStateEvent;
148181                         this.event({
148182                             projectName: event.data.project.getProjectName(),
148183                             languageServiceEnabled: event.data.languageServiceEnabled
148184                         }, eventName);
148185                         break;
148186                     }
148187                     case server.ProjectInfoTelemetryEvent: {
148188                         var eventName = "telemetry";
148189                         this.event({
148190                             telemetryEventName: event.eventName,
148191                             payload: event.data,
148192                         }, eventName);
148193                         break;
148194                     }
148195                 }
148196             };
148197             Session.prototype.projectsUpdatedInBackgroundEvent = function (openFiles) {
148198                 var _this = this;
148199                 this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles);
148200                 if (openFiles.length) {
148201                     if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) {
148202                         // For now only queue error checking for open files. We can change this to include non open files as well
148203                         this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, openFiles, 100, /*requireOpen*/ true); });
148204                     }
148205                     // Send project changed event
148206                     this.event({
148207                         openFiles: openFiles
148208                     }, server.ProjectsUpdatedInBackgroundEvent);
148209                 }
148210             };
148211             Session.prototype.logError = function (err, cmd) {
148212                 this.logErrorWorker(err, cmd);
148213             };
148214             Session.prototype.logErrorWorker = function (err, cmd, fileRequest) {
148215                 var msg = "Exception on executing command " + cmd;
148216                 if (err.message) {
148217                     msg += ":\n" + server.indent(err.message);
148218                     if (err.stack) {
148219                         msg += "\n" + server.indent(err.stack);
148220                     }
148221                 }
148222                 if (this.logger.hasLevel(server.LogLevel.verbose)) {
148223                     if (fileRequest) {
148224                         try {
148225                             var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project;
148226                             var scriptInfo = project.getScriptInfoForNormalizedPath(file);
148227                             if (scriptInfo) {
148228                                 var text = ts.getSnapshotText(scriptInfo.getSnapshot());
148229                                 msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n";
148230                             }
148231                         }
148232                         catch (_b) { } // eslint-disable-line no-empty
148233                     }
148234                     if (err.ProgramFiles) {
148235                         msg += "\n\nProgram files: " + JSON.stringify(err.ProgramFiles) + "\n";
148236                         msg += "\n\nProjects::\n";
148237                         var counter_1 = 0;
148238                         var addProjectInfo = function (project) {
148239                             msg += "\nProject '" + project.projectName + "' (" + server.ProjectKind[project.projectKind] + ") " + counter_1 + "\n";
148240                             msg += project.filesToString(/*writeProjectFileNames*/ true);
148241                             msg += "\n-----------------------------------------------\n";
148242                             counter_1++;
148243                         };
148244                         this.projectService.externalProjects.forEach(addProjectInfo);
148245                         this.projectService.configuredProjects.forEach(addProjectInfo);
148246                         this.projectService.inferredProjects.forEach(addProjectInfo);
148247                     }
148248                 }
148249                 this.logger.msg(msg, server.Msg.Err);
148250             };
148251             Session.prototype.send = function (msg) {
148252                 if (msg.type === "event" && !this.canUseEvents) {
148253                     if (this.logger.hasLevel(server.LogLevel.verbose)) {
148254                         this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg));
148255                     }
148256                     return;
148257                 }
148258                 var msgText = formatMessage(msg, this.logger, this.byteLength, this.host.newLine);
148259                 ts.perfLogger.logEvent("Response message size: " + msgText.length);
148260                 this.host.write(msgText);
148261             };
148262             Session.prototype.event = function (body, eventName) {
148263                 this.send(toEvent(eventName, body));
148264             };
148265             // For backwards-compatibility only.
148266             /** @deprecated */
148267             Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) {
148268                 this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); // TODO: GH#18217
148269             };
148270             Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) {
148271                 var res = {
148272                     seq: 0,
148273                     type: "response",
148274                     command: cmdName,
148275                     request_seq: reqSeq,
148276                     success: success,
148277                     performanceData: !this.updateGraphDurationMs
148278                         ? undefined
148279                         : {
148280                             updateGraphDurationMs: this.updateGraphDurationMs,
148281                         },
148282                 };
148283                 if (success) {
148284                     var metadata = void 0;
148285                     if (ts.isArray(info)) {
148286                         res.body = info;
148287                         metadata = info.metadata;
148288                         delete info.metadata;
148289                     }
148290                     else if (typeof info === "object") {
148291                         if (info.metadata) {
148292                             var _a = info, infoMetadata = _a.metadata, body = __rest(_a, ["metadata"]);
148293                             res.body = body;
148294                             metadata = infoMetadata;
148295                         }
148296                         else {
148297                             res.body = info;
148298                         }
148299                     }
148300                     else {
148301                         res.body = info;
148302                     }
148303                     if (metadata)
148304                         res.metadata = metadata;
148305                 }
148306                 else {
148307                     ts.Debug.assert(info === undefined);
148308                 }
148309                 if (message) {
148310                     res.message = message;
148311                 }
148312                 this.send(res);
148313             };
148314             Session.prototype.semanticCheck = function (file, project) {
148315                 var diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file)
148316                     ? server.emptyArray
148317                     : project.getLanguageService().getSemanticDiagnostics(file).filter(function (d) { return !!d.file; });
148318                 this.sendDiagnosticsEvent(file, project, diags, "semanticDiag");
148319             };
148320             Session.prototype.syntacticCheck = function (file, project) {
148321                 this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag");
148322             };
148323             Session.prototype.suggestionCheck = function (file, project) {
148324                 this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag");
148325             };
148326             Session.prototype.sendDiagnosticsEvent = function (file, project, diagnostics, kind) {
148327                 try {
148328                     this.event({ file: file, diagnostics: diagnostics.map(function (diag) { return formatDiag(file, project, diag); }) }, kind);
148329                 }
148330                 catch (err) {
148331                     this.logError(err, kind);
148332                 }
148333             };
148334             /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */
148335             Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) {
148336                 var _this = this;
148337                 if (requireOpen === void 0) { requireOpen = true; }
148338                 ts.Debug.assert(!this.suppressDiagnosticEvents); // Caller's responsibility
148339                 var seq = this.changeSeq;
148340                 var followMs = Math.min(ms, 200);
148341                 var index = 0;
148342                 var goNext = function () {
148343                     index++;
148344                     if (checkList.length > index) {
148345                         next.delay(followMs, checkOne);
148346                     }
148347                 };
148348                 var checkOne = function () {
148349                     if (_this.changeSeq !== seq) {
148350                         return;
148351                     }
148352                     var item = checkList[index];
148353                     if (ts.isString(item)) {
148354                         // Find out project for the file name
148355                         item = _this.toPendingErrorCheck(item);
148356                         if (!item) {
148357                             // Ignore file if there is no project for the file
148358                             goNext();
148359                             return;
148360                         }
148361                     }
148362                     var fileName = item.fileName, project = item.project;
148363                     // Ensure the project is upto date before checking if this file is present in the project
148364                     server.updateProjectIfDirty(project);
148365                     if (!project.containsFile(fileName, requireOpen)) {
148366                         return;
148367                     }
148368                     _this.syntacticCheck(fileName, project);
148369                     if (_this.changeSeq !== seq) {
148370                         return;
148371                     }
148372                     next.immediate(function () {
148373                         _this.semanticCheck(fileName, project);
148374                         if (_this.changeSeq !== seq) {
148375                             return;
148376                         }
148377                         if (_this.getPreferences(fileName).disableSuggestions) {
148378                             goNext();
148379                         }
148380                         else {
148381                             next.immediate(function () {
148382                                 _this.suggestionCheck(fileName, project);
148383                                 goNext();
148384                             });
148385                         }
148386                     });
148387                 };
148388                 if (checkList.length > index && this.changeSeq === seq) {
148389                     next.delay(ms, checkOne);
148390                 }
148391             };
148392             Session.prototype.cleanProjects = function (caption, projects) {
148393                 if (!projects) {
148394                     return;
148395                 }
148396                 this.logger.info("cleaning " + caption);
148397                 for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) {
148398                     var p = projects_4[_i];
148399                     p.getLanguageService(/*ensureSynchronized*/ false).cleanupSemanticCache();
148400                 }
148401             };
148402             Session.prototype.cleanup = function () {
148403                 this.cleanProjects("inferred projects", this.projectService.inferredProjects);
148404                 this.cleanProjects("configured projects", ts.arrayFrom(this.projectService.configuredProjects.values()));
148405                 this.cleanProjects("external projects", this.projectService.externalProjects);
148406                 if (this.host.gc) {
148407                     this.logger.info("host.gc()");
148408                     this.host.gc();
148409                 }
148410             };
148411             Session.prototype.getEncodedSyntacticClassifications = function (args) {
148412                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148413                 return languageService.getEncodedSyntacticClassifications(file, args);
148414             };
148415             Session.prototype.getEncodedSemanticClassifications = function (args) {
148416                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148417                 return project.getLanguageService().getEncodedSemanticClassifications(file, args);
148418             };
148419             Session.prototype.getProject = function (projectFileName) {
148420                 return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName);
148421             };
148422             Session.prototype.getConfigFileAndProject = function (args) {
148423                 var project = this.getProject(args.projectFileName);
148424                 var file = server.toNormalizedPath(args.file);
148425                 return {
148426                     configFile: project && project.hasConfigFile(file) ? file : undefined,
148427                     project: project
148428                 };
148429             };
148430             Session.prototype.getConfigFileDiagnostics = function (configFile, project, includeLinePosition) {
148431                 var projectErrors = project.getAllProjectErrors();
148432                 var optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics();
148433                 var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return !!diagnostic.file && diagnostic.file.fileName === configFile; });
148434                 return includeLinePosition ?
148435                     this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) :
148436                     ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatDiagnosticToProtocol(diagnostic, /*includeFileName*/ false); });
148437             };
148438             Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) {
148439                 var _this = this;
148440                 return diagnostics.map(function (d) { return ({
148441                     message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine),
148442                     start: d.start,
148443                     length: d.length,
148444                     category: ts.diagnosticCategoryName(d),
148445                     code: d.code,
148446                     source: d.source,
148447                     startLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start))),
148448                     endLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))),
148449                     reportsUnnecessary: d.reportsUnnecessary,
148450                     relatedInformation: ts.map(d.relatedInformation, formatRelatedInformation)
148451                 }); });
148452             };
148453             Session.prototype.getCompilerOptionsDiagnostics = function (args) {
148454                 var project = this.getProject(args.projectFileName);
148455                 // Get diagnostics that dont have associated file with them
148456                 // The diagnostics which have file would be in config file and
148457                 // would be reported as part of configFileDiagnostics
148458                 return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), 
148459                 /*scriptInfo*/ undefined);
148460             };
148461             Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) {
148462                 var _this = this;
148463                 return diagnostics.map(function (d) { return ({
148464                     message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine),
148465                     start: d.start,
148466                     length: d.length,
148467                     category: ts.diagnosticCategoryName(d),
148468                     code: d.code,
148469                     source: d.source,
148470                     startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start),
148471                     endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length),
148472                     reportsUnnecessary: d.reportsUnnecessary,
148473                     relatedInformation: ts.map(d.relatedInformation, formatRelatedInformation),
148474                 }); });
148475             };
148476             Session.prototype.getDiagnosticsWorker = function (args, isSemantic, selector, includeLinePosition) {
148477                 var _a = this.getFileAndProject(args), project = _a.project, file = _a.file;
148478                 if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) {
148479                     return server.emptyArray;
148480                 }
148481                 var scriptInfo = project.getScriptInfoForNormalizedPath(file);
148482                 var diagnostics = selector(project, file);
148483                 return includeLinePosition
148484                     ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo)
148485                     : diagnostics.map(function (d) { return formatDiag(file, project, d); });
148486             };
148487             Session.prototype.getDefinition = function (args, simplifiedResult) {
148488                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148489                 var position = this.getPositionInFile(args, file);
148490                 var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || server.emptyArray, project);
148491                 return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(Session.mapToOriginalLocation);
148492             };
148493             Session.prototype.mapDefinitionInfoLocations = function (definitions, project) {
148494                 return definitions.map(function (info) {
148495                     var newDocumentSpan = getMappedDocumentSpan(info, project);
148496                     return !newDocumentSpan ? info : __assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name });
148497                 });
148498             };
148499             Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) {
148500                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148501                 var position = this.getPositionInFile(args, file);
148502                 var scriptInfo = ts.Debug.checkDefined(project.getScriptInfo(file));
148503                 var unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position);
148504                 if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) {
148505                     return {
148506                         definitions: server.emptyArray,
148507                         textSpan: undefined // TODO: GH#18217
148508                     };
148509                 }
148510                 var definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project);
148511                 var textSpan = unmappedDefinitionAndBoundSpan.textSpan;
148512                 if (simplifiedResult) {
148513                     return {
148514                         definitions: this.mapDefinitionInfo(definitions, project),
148515                         textSpan: toProtocolTextSpan(textSpan, scriptInfo)
148516                     };
148517                 }
148518                 return {
148519                     definitions: definitions.map(Session.mapToOriginalLocation),
148520                     textSpan: textSpan,
148521                 };
148522             };
148523             Session.prototype.getEmitOutput = function (args) {
148524                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148525                 if (!project.shouldEmitFile(project.getScriptInfo(file))) {
148526                     return { emitSkipped: true, outputFiles: [], diagnostics: [] };
148527                 }
148528                 var result = project.getLanguageService().getEmitOutput(file);
148529                 return args.richResponse ? __assign(__assign({}, result), { diagnostics: args.includeLinePosition ?
148530                         this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(result.diagnostics) :
148531                         result.diagnostics.map(function (d) { return formatDiagnosticToProtocol(d, /*includeFileName*/ true); }) }) :
148532                     result;
148533             };
148534             Session.prototype.mapDefinitionInfo = function (definitions, project) {
148535                 var _this = this;
148536                 return definitions.map(function (def) { return _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project); });
148537             };
148538             /*
148539              * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in
148540              * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols.
148541              * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a
148542              * set of additional fields, and does the reverse for VS (store the .d.ts location where
148543              * it used to be and stores the .ts location in the additional fields).
148544             */
148545             Session.mapToOriginalLocation = function (def) {
148546                 if (def.originalFileName) {
148547                     ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is");
148548                     return __assign(__assign({}, def), { fileName: def.originalFileName, textSpan: def.originalTextSpan, targetFileName: def.fileName, targetTextSpan: def.textSpan, contextSpan: def.originalContextSpan, targetContextSpan: def.contextSpan });
148549                 }
148550                 return def;
148551             };
148552             Session.prototype.toFileSpan = function (fileName, textSpan, project) {
148553                 var ls = project.getLanguageService();
148554                 var start = ls.toLineColumnOffset(fileName, textSpan.start); // TODO: GH#18217
148555                 var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan));
148556                 return {
148557                     file: fileName,
148558                     start: { line: start.line + 1, offset: start.character + 1 },
148559                     end: { line: end.line + 1, offset: end.character + 1 }
148560                 };
148561             };
148562             Session.prototype.toFileSpanWithContext = function (fileName, textSpan, contextSpan, project) {
148563                 var fileSpan = this.toFileSpan(fileName, textSpan, project);
148564                 var context = contextSpan && this.toFileSpan(fileName, contextSpan, project);
148565                 return context ? __assign(__assign({}, fileSpan), { contextStart: context.start, contextEnd: context.end }) :
148566                     fileSpan;
148567             };
148568             Session.prototype.getTypeDefinition = function (args) {
148569                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148570                 var position = this.getPositionInFile(args, file);
148571                 var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || server.emptyArray, project);
148572                 return this.mapDefinitionInfo(definitions, project);
148573             };
148574             Session.prototype.mapImplementationLocations = function (implementations, project) {
148575                 return implementations.map(function (info) {
148576                     var newDocumentSpan = getMappedDocumentSpan(info, project);
148577                     return !newDocumentSpan ? info : __assign(__assign({}, newDocumentSpan), { kind: info.kind, displayParts: info.displayParts });
148578                 });
148579             };
148580             Session.prototype.getImplementation = function (args, simplifiedResult) {
148581                 var _this = this;
148582                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148583                 var position = this.getPositionInFile(args, file);
148584                 var implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || server.emptyArray, project);
148585                 return simplifiedResult ?
148586                     implementations.map(function (_a) {
148587                         var fileName = _a.fileName, textSpan = _a.textSpan, contextSpan = _a.contextSpan;
148588                         return _this.toFileSpanWithContext(fileName, textSpan, contextSpan, project);
148589                     }) :
148590                     implementations.map(Session.mapToOriginalLocation);
148591             };
148592             Session.prototype.getOccurrences = function (args) {
148593                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148594                 var position = this.getPositionInFile(args, file);
148595                 var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position);
148596                 return occurrences ?
148597                     occurrences.map(function (occurrence) {
148598                         var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan, isInString = occurrence.isInString, contextSpan = occurrence.contextSpan;
148599                         var scriptInfo = project.getScriptInfo(fileName);
148600                         return __assign(__assign(__assign({}, toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo)), { file: fileName, isWriteAccess: isWriteAccess }), (isInString ? { isInString: isInString } : undefined));
148601                     }) :
148602                     server.emptyArray;
148603             };
148604             Session.prototype.getSyntacticDiagnosticsSync = function (args) {
148605                 var configFile = this.getConfigFileAndProject(args).configFile;
148606                 if (configFile) {
148607                     // all the config file errors are reported as part of semantic check so nothing to report here
148608                     return server.emptyArray;
148609                 }
148610                 return this.getDiagnosticsWorker(args, /*isSemantic*/ false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition);
148611             };
148612             Session.prototype.getSemanticDiagnosticsSync = function (args) {
148613                 var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project;
148614                 if (configFile) {
148615                     return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); // TODO: GH#18217
148616                 }
148617                 return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file).filter(function (d) { return !!d.file; }); }, !!args.includeLinePosition);
148618             };
148619             Session.prototype.getSuggestionDiagnosticsSync = function (args) {
148620                 var configFile = this.getConfigFileAndProject(args).configFile;
148621                 if (configFile) {
148622                     // Currently there are no info diagnostics for config files.
148623                     return server.emptyArray;
148624                 }
148625                 // isSemantic because we don't want to info diagnostics in declaration files for JS-only users
148626                 return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition);
148627             };
148628             Session.prototype.getJsxClosingTag = function (args) {
148629                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148630                 var position = this.getPositionInFile(args, file);
148631                 var tag = project.getLanguageService().getJsxClosingTagAtPosition(file, position);
148632                 return tag === undefined ? undefined : { newText: tag.newText, caretOffset: 0 };
148633             };
148634             Session.prototype.getDocumentHighlights = function (args, simplifiedResult) {
148635                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148636                 var position = this.getPositionInFile(args, file);
148637                 var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch);
148638                 if (!documentHighlights)
148639                     return server.emptyArray;
148640                 if (!simplifiedResult)
148641                     return documentHighlights;
148642                 return documentHighlights.map(function (_a) {
148643                     var fileName = _a.fileName, highlightSpans = _a.highlightSpans;
148644                     var scriptInfo = project.getScriptInfo(fileName);
148645                     return {
148646                         file: fileName,
148647                         highlightSpans: highlightSpans.map(function (_a) {
148648                             var textSpan = _a.textSpan, kind = _a.kind, contextSpan = _a.contextSpan;
148649                             return (__assign(__assign({}, toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo)), { kind: kind }));
148650                         })
148651                     };
148652                 });
148653             };
148654             Session.prototype.setCompilerOptionsForInferredProjects = function (args) {
148655                 this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath);
148656             };
148657             Session.prototype.getProjectInfo = function (args) {
148658                 return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, /*excludeConfigFiles*/ false);
148659             };
148660             Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) {
148661                 var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project;
148662                 server.updateProjectIfDirty(project);
148663                 var projectInfo = {
148664                     configFileName: project.getProjectName(),
148665                     languageServiceDisabled: !project.languageServiceEnabled,
148666                     fileNames: needFileNameList ? project.getFileNames(/*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles) : undefined
148667                 };
148668                 return projectInfo;
148669             };
148670             Session.prototype.getRenameInfo = function (args) {
148671                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148672                 var position = this.getPositionInFile(args, file);
148673                 return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath });
148674             };
148675             Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) {
148676                 var _a;
148677                 var projects;
148678                 var symLinkedProjects;
148679                 if (args.projectFileName) {
148680                     var project = this.getProject(args.projectFileName);
148681                     if (project) {
148682                         projects = [project];
148683                     }
148684                 }
148685                 else {
148686                     var scriptInfo = getScriptInfoEnsuringProjectsUptoDate ?
148687                         this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) :
148688                         this.projectService.getScriptInfo(args.file);
148689                     if (!scriptInfo) {
148690                         if (ignoreNoProjectError)
148691                             return server.emptyArray;
148692                         this.projectService.logErrorForScriptInfoNotFound(args.file);
148693                         return server.Errors.ThrowNoProject();
148694                     }
148695                     projects = scriptInfo.containingProjects;
148696                     symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo);
148697                 }
148698                 // filter handles case when 'projects' is undefined
148699                 projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); });
148700                 if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) {
148701                     this.projectService.logErrorForScriptInfoNotFound((_a = args.file) !== null && _a !== void 0 ? _a : args.projectFileName);
148702                     return server.Errors.ThrowNoProject();
148703                 }
148704                 return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217
148705             };
148706             Session.prototype.getDefaultProject = function (args) {
148707                 if (args.projectFileName) {
148708                     var project = this.getProject(args.projectFileName);
148709                     if (project) {
148710                         return project;
148711                     }
148712                     if (!args.file) {
148713                         return server.Errors.ThrowNoProject();
148714                     }
148715                 }
148716                 var info = this.projectService.getScriptInfo(args.file);
148717                 return info.getDefaultProject();
148718             };
148719             Session.prototype.getRenameLocations = function (args, simplifiedResult) {
148720                 var file = server.toNormalizedPath(args.file);
148721                 var position = this.getPositionInFile(args, file);
148722                 var projects = this.getProjects(args);
148723                 var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file));
148724                 if (!simplifiedResult)
148725                     return locations;
148726                 var defaultProject = this.getDefaultProject(args);
148727                 var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), ts.Debug.checkDefined(this.projectService.getScriptInfo(file)));
148728                 return { info: renameInfo, locs: this.toSpanGroups(locations) };
148729             };
148730             Session.prototype.mapRenameInfo = function (info, scriptInfo) {
148731                 if (info.canRename) {
148732                     var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan;
148733                     return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) });
148734                 }
148735                 else {
148736                     return info;
148737                 }
148738             };
148739             Session.prototype.toSpanGroups = function (locations) {
148740                 var map = ts.createMap();
148741                 for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) {
148742                     var _a = locations_1[_i];
148743                     var fileName = _a.fileName, textSpan = _a.textSpan, contextSpan = _a.contextSpan, _2 = _a.originalContextSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "contextSpan", "originalContextSpan", "originalTextSpan", "originalFileName"]);
148744                     var group_1 = map.get(fileName);
148745                     if (!group_1)
148746                         map.set(fileName, group_1 = { file: fileName, locs: [] });
148747                     var scriptInfo = ts.Debug.checkDefined(this.projectService.getScriptInfo(fileName));
148748                     group_1.locs.push(__assign(__assign({}, toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo)), prefixSuffixText));
148749                 }
148750                 return ts.arrayFrom(map.values());
148751             };
148752             Session.prototype.getReferences = function (args, simplifiedResult) {
148753                 var _this = this;
148754                 var file = server.toNormalizedPath(args.file);
148755                 var projects = this.getProjects(args);
148756                 var position = this.getPositionInFile(args, file);
148757                 var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, pos: position });
148758                 if (!simplifiedResult)
148759                     return references;
148760                 var defaultProject = this.getDefaultProject(args);
148761                 var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file);
148762                 var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position);
148763                 var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : "";
148764                 var nameSpan = nameInfo && nameInfo.textSpan;
148765                 var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0;
148766                 var symbolName = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : "";
148767                 var refs = ts.flatMap(references, function (referencedSymbol) {
148768                     return referencedSymbol.references.map(function (_a) {
148769                         var fileName = _a.fileName, textSpan = _a.textSpan, contextSpan = _a.contextSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition;
148770                         var scriptInfo = ts.Debug.checkDefined(_this.projectService.getScriptInfo(fileName));
148771                         var span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo);
148772                         var lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1);
148773                         var lineText = scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, "");
148774                         return __assign(__assign({ file: fileName }, span), { lineText: lineText,
148775                             isWriteAccess: isWriteAccess,
148776                             isDefinition: isDefinition });
148777                     });
148778                 });
148779                 return { refs: refs, symbolName: symbolName, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString };
148780             };
148781             /**
148782              * @param fileName is the name of the file to be opened
148783              * @param fileContent is a version of the file content that is known to be more up to date than the one on disk
148784              */
148785             Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) {
148786                 this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath);
148787             };
148788             Session.prototype.getPosition = function (args, scriptInfo) {
148789                 return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset);
148790             };
148791             Session.prototype.getPositionInFile = function (args, file) {
148792                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
148793                 return this.getPosition(args, scriptInfo);
148794             };
148795             Session.prototype.getFileAndProject = function (args) {
148796                 return this.getFileAndProjectWorker(args.file, args.projectFileName);
148797             };
148798             Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) {
148799                 // Since this is syntactic operation, there should always be project for the file
148800                 // we wouldnt have to ensure project but rather throw if we dont get project
148801                 var file = server.toNormalizedPath(args.file);
148802                 var project = this.getProject(args.projectFileName) || this.projectService.tryGetDefaultProjectForFile(file);
148803                 if (!project) {
148804                     return server.Errors.ThrowNoProject();
148805                 }
148806                 return {
148807                     file: file,
148808                     languageService: project.getLanguageService(/*ensureSynchronized*/ false)
148809                 };
148810             };
148811             Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) {
148812                 var file = server.toNormalizedPath(uncheckedFileName);
148813                 var project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file);
148814                 return { file: file, project: project };
148815             };
148816             Session.prototype.getOutliningSpans = function (args, simplifiedResult) {
148817                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148818                 var spans = languageService.getOutliningSpans(file);
148819                 if (simplifiedResult) {
148820                     var scriptInfo_1 = this.projectService.getScriptInfoForNormalizedPath(file);
148821                     return spans.map(function (s) { return ({
148822                         textSpan: toProtocolTextSpan(s.textSpan, scriptInfo_1),
148823                         hintSpan: toProtocolTextSpan(s.hintSpan, scriptInfo_1),
148824                         bannerText: s.bannerText,
148825                         autoCollapse: s.autoCollapse,
148826                         kind: s.kind
148827                     }); });
148828                 }
148829                 else {
148830                     return spans;
148831                 }
148832             };
148833             Session.prototype.getTodoComments = function (args) {
148834                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148835                 return project.getLanguageService().getTodoComments(file, args.descriptors);
148836             };
148837             Session.prototype.getDocCommentTemplate = function (args) {
148838                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148839                 var position = this.getPositionInFile(args, file);
148840                 return languageService.getDocCommentTemplateAtPosition(file, position);
148841             };
148842             Session.prototype.getSpanOfEnclosingComment = function (args) {
148843                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148844                 var onlyMultiLine = args.onlyMultiLine;
148845                 var position = this.getPositionInFile(args, file);
148846                 return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine);
148847             };
148848             Session.prototype.getIndentation = function (args) {
148849                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148850                 var position = this.getPositionInFile(args, file);
148851                 var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file);
148852                 var indentation = languageService.getIndentationAtPosition(file, position, options);
148853                 return { position: position, indentation: indentation };
148854             };
148855             Session.prototype.getBreakpointStatement = function (args) {
148856                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148857                 var position = this.getPositionInFile(args, file);
148858                 return languageService.getBreakpointStatementAtPosition(file, position);
148859             };
148860             Session.prototype.getNameOrDottedNameSpan = function (args) {
148861                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148862                 var position = this.getPositionInFile(args, file);
148863                 return languageService.getNameOrDottedNameSpan(file, position, position);
148864             };
148865             Session.prototype.isValidBraceCompletion = function (args) {
148866                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148867                 var position = this.getPositionInFile(args, file);
148868                 return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0));
148869             };
148870             Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) {
148871                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148872                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
148873                 var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo));
148874                 if (!quickInfo) {
148875                     return undefined;
148876                 }
148877                 if (simplifiedResult) {
148878                     var displayString = ts.displayPartsToString(quickInfo.displayParts);
148879                     var docString = ts.displayPartsToString(quickInfo.documentation);
148880                     return {
148881                         kind: quickInfo.kind,
148882                         kindModifiers: quickInfo.kindModifiers,
148883                         start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start),
148884                         end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)),
148885                         displayString: displayString,
148886                         documentation: docString,
148887                         tags: quickInfo.tags || []
148888                     };
148889                 }
148890                 else {
148891                     return quickInfo;
148892                 }
148893             };
148894             Session.prototype.getFormattingEditsForRange = function (args) {
148895                 var _this = this;
148896                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148897                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
148898                 var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset);
148899                 var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
148900                 // TODO: avoid duplicate code (with formatonkey)
148901                 var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file));
148902                 if (!edits) {
148903                     return undefined;
148904                 }
148905                 return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); });
148906             };
148907             Session.prototype.getFormattingEditsForRangeFull = function (args) {
148908                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148909                 var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file);
148910                 return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); // TODO: GH#18217
148911             };
148912             Session.prototype.getFormattingEditsForDocumentFull = function (args) {
148913                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148914                 var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file);
148915                 return languageService.getFormattingEditsForDocument(file, options);
148916             };
148917             Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) {
148918                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148919                 var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file);
148920                 return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); // TODO: GH#18217
148921             };
148922             Session.prototype.getFormattingEditsAfterKeystroke = function (args) {
148923                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
148924                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
148925                 var position = scriptInfo.lineOffsetToPosition(args.line, args.offset);
148926                 var formatOptions = this.getFormatOptions(file);
148927                 var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions);
148928                 // Check whether we should auto-indent. This will be when
148929                 // the position is on a line containing only whitespace.
148930                 // This should leave the edits returned from
148931                 // getFormattingEditsAfterKeystroke either empty or pertaining
148932                 // only to the previous line.  If all this is true, then
148933                 // add edits necessary to properly indent the current line.
148934                 if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
148935                     var _b = scriptInfo.getAbsolutePositionAndLineText(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition;
148936                     if (lineText && lineText.search("\\S") < 0) {
148937                         var preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions);
148938                         var hasIndent = 0;
148939                         var i = void 0, len = void 0;
148940                         for (i = 0, len = lineText.length; i < len; i++) {
148941                             if (lineText.charAt(i) === " ") {
148942                                 hasIndent++;
148943                             }
148944                             else if (lineText.charAt(i) === "\t") {
148945                                 hasIndent += formatOptions.tabSize; // TODO: GH#18217
148946                             }
148947                             else {
148948                                 break;
148949                             }
148950                         }
148951                         // i points to the first non whitespace character
148952                         if (preferredIndent !== hasIndent) {
148953                             var firstNoWhiteSpacePosition = absolutePosition + i;
148954                             edits.push({
148955                                 span: ts.createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition),
148956                                 newText: ts.formatting.getIndentationString(preferredIndent, formatOptions)
148957                             });
148958                         }
148959                     }
148960                 }
148961                 if (!edits) {
148962                     return undefined;
148963                 }
148964                 return edits.map(function (edit) {
148965                     return {
148966                         start: scriptInfo.positionToLineOffset(edit.span.start),
148967                         end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)),
148968                         newText: edit.newText ? edit.newText : ""
148969                     };
148970                 });
148971             };
148972             Session.prototype.getCompletions = function (args, kind) {
148973                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
148974                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
148975                 var position = this.getPosition(args, scriptInfo);
148976                 var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign(__assign({}, server.convertUserPreferences(this.getPreferences(file))), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions }));
148977                 if (completions === undefined)
148978                     return undefined;
148979                 if (kind === "completions-full" /* CompletionsFull */)
148980                     return completions;
148981                 var prefix = args.prefix || "";
148982                 var entries = ts.mapDefined(completions.entries, function (entry) {
148983                     if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
148984                         var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended;
148985                         var convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : undefined;
148986                         // Use `hasAction || undefined` to avoid serializing `false`.
148987                         return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended };
148988                     }
148989                 }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); });
148990                 if (kind === "completions" /* Completions */) {
148991                     if (completions.metadata)
148992                         entries.metadata = completions.metadata;
148993                     return entries;
148994                 }
148995                 var res = __assign(__assign({}, completions), { entries: entries });
148996                 return res;
148997             };
148998             Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) {
148999                 var _this = this;
149000                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149001                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
149002                 var position = this.getPosition(args, scriptInfo);
149003                 var formattingOptions = project.projectService.getFormatCodeOptions(file);
149004                 var result = ts.mapDefined(args.entryNames, function (entryName) {
149005                     var _a = typeof entryName === "string" ? { name: entryName, source: undefined } : entryName, name = _a.name, source = _a.source;
149006                     return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file));
149007                 });
149008                 return simplifiedResult
149009                     ? result.map(function (details) { return (__assign(__assign({}, details), { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }) })); })
149010                     : result;
149011             };
149012             Session.prototype.getCompileOnSaveAffectedFileList = function (args) {
149013                 var _this = this;
149014                 var projects = this.getProjects(args, /*getScriptInfoEnsuringProjectsUptoDate*/ true, /*ignoreNoProjectError*/ true);
149015                 var info = this.projectService.getScriptInfo(args.file);
149016                 if (!info) {
149017                     return server.emptyArray;
149018                 }
149019                 return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, projects, function (project, info) {
149020                     if (!project.compileOnSaveEnabled || !project.languageServiceEnabled || project.isOrphan()) {
149021                         return undefined;
149022                     }
149023                     var compilationSettings = project.getCompilationSettings();
149024                     if (!!compilationSettings.noEmit || ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */) && !dtsChangeCanAffectEmit(compilationSettings)) {
149025                         // avoid triggering emit when a change is made in a .d.ts when declaration emit and decorator metadata emit are disabled
149026                         return undefined;
149027                     }
149028                     return {
149029                         projectFileName: project.getProjectName(),
149030                         fileNames: project.getCompileOnSaveAffectedFileList(info),
149031                         projectUsesOutFile: !!compilationSettings.outFile || !!compilationSettings.out
149032                     };
149033                 });
149034             };
149035             Session.prototype.emitFile = function (args) {
149036                 var _this = this;
149037                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149038                 if (!project) {
149039                     server.Errors.ThrowNoProject();
149040                 }
149041                 if (!project.languageServiceEnabled) {
149042                     return args.richResponse ? { emitSkipped: true, diagnostics: [] } : false;
149043                 }
149044                 var scriptInfo = project.getScriptInfo(file);
149045                 var _b = project.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }), emitSkipped = _b.emitSkipped, diagnostics = _b.diagnostics;
149046                 return args.richResponse ?
149047                     {
149048                         emitSkipped: emitSkipped,
149049                         diagnostics: args.includeLinePosition ?
149050                             this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) :
149051                             diagnostics.map(function (d) { return formatDiagnosticToProtocol(d, /*includeFileName*/ true); })
149052                     } :
149053                     !emitSkipped;
149054             };
149055             Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) {
149056                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149057                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
149058                 var position = this.getPosition(args, scriptInfo);
149059                 var helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args);
149060                 if (!helpItems) {
149061                     return undefined;
149062                 }
149063                 if (simplifiedResult) {
149064                     var span = helpItems.applicableSpan;
149065                     return {
149066                         items: helpItems.items,
149067                         applicableSpan: {
149068                             start: scriptInfo.positionToLineOffset(span.start),
149069                             end: scriptInfo.positionToLineOffset(span.start + span.length)
149070                         },
149071                         selectedItemIndex: helpItems.selectedItemIndex,
149072                         argumentIndex: helpItems.argumentIndex,
149073                         argumentCount: helpItems.argumentCount,
149074                     };
149075                 }
149076                 else {
149077                     return helpItems;
149078                 }
149079             };
149080             Session.prototype.toPendingErrorCheck = function (uncheckedFileName) {
149081                 var fileName = server.toNormalizedPath(uncheckedFileName);
149082                 var project = this.projectService.tryGetDefaultProjectForFile(fileName);
149083                 return project && { fileName: fileName, project: project };
149084             };
149085             Session.prototype.getDiagnostics = function (next, delay, fileNames) {
149086                 if (this.suppressDiagnosticEvents) {
149087                     return;
149088                 }
149089                 if (fileNames.length > 0) {
149090                     this.updateErrorCheck(next, fileNames, delay);
149091                 }
149092             };
149093             Session.prototype.change = function (args) {
149094                 var scriptInfo = this.projectService.getScriptInfo(args.file);
149095                 ts.Debug.assert(!!scriptInfo);
149096                 var start = scriptInfo.lineOffsetToPosition(args.line, args.offset);
149097                 var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
149098                 if (start >= 0) {
149099                     this.changeSeq++;
149100                     this.projectService.applyChangesToFile(scriptInfo, ts.singleIterator({
149101                         span: { start: start, length: end - start },
149102                         newText: args.insertString // TODO: GH#18217
149103                     }));
149104                 }
149105             };
149106             Session.prototype.reload = function (args, reqSeq) {
149107                 var file = server.toNormalizedPath(args.file);
149108                 var tempFileName = args.tmpfile === undefined ? undefined : server.toNormalizedPath(args.tmpfile);
149109                 var info = this.projectService.getScriptInfoForNormalizedPath(file);
149110                 if (info) {
149111                     this.changeSeq++;
149112                     // make sure no changes happen before this one is finished
149113                     if (info.reloadFromFile(tempFileName)) {
149114                         this.doOutput(/*info*/ undefined, server.CommandNames.Reload, reqSeq, /*success*/ true);
149115                     }
149116                 }
149117             };
149118             Session.prototype.saveToTmp = function (fileName, tempFileName) {
149119                 var scriptInfo = this.projectService.getScriptInfo(fileName);
149120                 if (scriptInfo) {
149121                     scriptInfo.saveTo(tempFileName);
149122                 }
149123             };
149124             Session.prototype.closeClientFile = function (fileName) {
149125                 if (!fileName) {
149126                     return;
149127                 }
149128                 var file = ts.normalizePath(fileName);
149129                 this.projectService.closeClientFile(file);
149130             };
149131             Session.prototype.mapLocationNavigationBarItems = function (items, scriptInfo) {
149132                 var _this = this;
149133                 return ts.map(items, function (item) { return ({
149134                     text: item.text,
149135                     kind: item.kind,
149136                     kindModifiers: item.kindModifiers,
149137                     spans: item.spans.map(function (span) { return toProtocolTextSpan(span, scriptInfo); }),
149138                     childItems: _this.mapLocationNavigationBarItems(item.childItems, scriptInfo),
149139                     indent: item.indent
149140                 }); });
149141             };
149142             Session.prototype.getNavigationBarItems = function (args, simplifiedResult) {
149143                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
149144                 var items = languageService.getNavigationBarItems(file);
149145                 return !items
149146                     ? undefined
149147                     : simplifiedResult
149148                         ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file))
149149                         : items;
149150             };
149151             Session.prototype.toLocationNavigationTree = function (tree, scriptInfo) {
149152                 var _this = this;
149153                 return {
149154                     text: tree.text,
149155                     kind: tree.kind,
149156                     kindModifiers: tree.kindModifiers,
149157                     spans: tree.spans.map(function (span) { return toProtocolTextSpan(span, scriptInfo); }),
149158                     nameSpan: tree.nameSpan && toProtocolTextSpan(tree.nameSpan, scriptInfo),
149159                     childItems: ts.map(tree.childItems, function (item) { return _this.toLocationNavigationTree(item, scriptInfo); })
149160                 };
149161             };
149162             Session.prototype.getNavigationTree = function (args, simplifiedResult) {
149163                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
149164                 var tree = languageService.getNavigationTree(file);
149165                 return !tree
149166                     ? undefined
149167                     : simplifiedResult
149168                         ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file))
149169                         : tree;
149170             };
149171             Session.prototype.getNavigateToItems = function (args, simplifiedResult) {
149172                 var _this = this;
149173                 var full = this.getFullNavigateToItems(args);
149174                 return !simplifiedResult ? full : full.map(function (navItem) {
149175                     var _a = _this.getFileAndProject({ file: navItem.fileName }), file = _a.file, project = _a.project;
149176                     var scriptInfo = project.getScriptInfo(file);
149177                     var bakedItem = {
149178                         name: navItem.name,
149179                         kind: navItem.kind,
149180                         isCaseSensitive: navItem.isCaseSensitive,
149181                         matchKind: navItem.matchKind,
149182                         file: navItem.fileName,
149183                         start: scriptInfo.positionToLineOffset(navItem.textSpan.start),
149184                         end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan))
149185                     };
149186                     if (navItem.kindModifiers && (navItem.kindModifiers !== "")) {
149187                         bakedItem.kindModifiers = navItem.kindModifiers;
149188                     }
149189                     if (navItem.containerName && (navItem.containerName.length > 0)) {
149190                         bakedItem.containerName = navItem.containerName;
149191                     }
149192                     if (navItem.containerKind && (navItem.containerKind.length > 0)) {
149193                         bakedItem.containerKind = navItem.containerKind;
149194                     }
149195                     return bakedItem;
149196                 });
149197             };
149198             Session.prototype.getFullNavigateToItems = function (args) {
149199                 var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount, projectFileName = args.projectFileName;
149200                 if (currentFileOnly) {
149201                     ts.Debug.assertDefined(args.file);
149202                     var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149203                     return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file);
149204                 }
149205                 else if (!args.file && !projectFileName) {
149206                     return combineProjectOutputFromEveryProject(this.projectService, function (project) { return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*filename*/ undefined, /*excludeDts*/ project.isNonTsProject()); }, navigateToItemIsEqualTo);
149207                 }
149208                 var fileArgs = args;
149209                 return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(fileArgs), this.getDefaultProject(fileArgs), function (project) { return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()); }, documentSpanLocation, navigateToItemIsEqualTo);
149210                 function navigateToItemIsEqualTo(a, b) {
149211                     if (a === b) {
149212                         return true;
149213                     }
149214                     if (!a || !b) {
149215                         return false;
149216                     }
149217                     return a.containerKind === b.containerKind &&
149218                         a.containerName === b.containerName &&
149219                         a.fileName === b.fileName &&
149220                         a.isCaseSensitive === b.isCaseSensitive &&
149221                         a.kind === b.kind &&
149222                         a.kindModifiers === b.kindModifiers &&
149223                         a.matchKind === b.matchKind &&
149224                         a.name === b.name &&
149225                         a.textSpan.start === b.textSpan.start &&
149226                         a.textSpan.length === b.textSpan.length;
149227                 }
149228             };
149229             Session.prototype.getSupportedCodeFixes = function () {
149230                 return ts.getSupportedCodeFixes();
149231             };
149232             Session.prototype.isLocation = function (locationOrSpan) {
149233                 return locationOrSpan.line !== undefined;
149234             };
149235             Session.prototype.extractPositionOrRange = function (args, scriptInfo) {
149236                 var position;
149237                 var textRange;
149238                 if (this.isLocation(args)) {
149239                     position = getPosition(args);
149240                 }
149241                 else {
149242                     var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition;
149243                     textRange = { pos: startPosition, end: endPosition };
149244                 }
149245                 return ts.Debug.checkDefined(position === undefined ? textRange : position);
149246                 function getPosition(loc) {
149247                     return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset);
149248                 }
149249             };
149250             Session.prototype.getApplicableRefactors = function (args) {
149251                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149252                 var scriptInfo = project.getScriptInfoForNormalizedPath(file);
149253                 return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file));
149254             };
149255             Session.prototype.getEditsForRefactor = function (args, simplifiedResult) {
149256                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149257                 var scriptInfo = project.getScriptInfoForNormalizedPath(file);
149258                 var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file));
149259                 if (result === undefined) {
149260                     return {
149261                         edits: []
149262                     };
149263                 }
149264                 if (simplifiedResult) {
149265                     var renameFilename = result.renameFilename, renameLocation = result.renameLocation, edits = result.edits;
149266                     var mappedRenameLocation = void 0;
149267                     if (renameFilename !== undefined && renameLocation !== undefined) {
149268                         var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename));
149269                         mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits);
149270                     }
149271                     return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(edits) };
149272                 }
149273                 else {
149274                     return result;
149275                 }
149276             };
149277             Session.prototype.organizeImports = function (_a, simplifiedResult) {
149278                 var scope = _a.scope;
149279                 ts.Debug.assert(scope.type === "file");
149280                 var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project;
149281                 var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file));
149282                 if (simplifiedResult) {
149283                     return this.mapTextChangesToCodeEdits(changes);
149284                 }
149285                 else {
149286                     return changes;
149287                 }
149288             };
149289             Session.prototype.getEditsForFileRename = function (args, simplifiedResult) {
149290                 var _this = this;
149291                 var oldPath = server.toNormalizedPath(args.oldFilePath);
149292                 var newPath = server.toNormalizedPath(args.newFilePath);
149293                 var formatOptions = this.getHostFormatOptions();
149294                 var preferences = this.getHostPreferences();
149295                 var changes = combineProjectOutputFromEveryProject(this.projectService, function (project) { return project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); }, function (a, b) { return a.fileName === b.fileName; });
149296                 return simplifiedResult ? changes.map(function (c) { return _this.mapTextChangeToCodeEdit(c); }) : changes;
149297             };
149298             Session.prototype.getCodeFixes = function (args, simplifiedResult) {
149299                 var _this = this;
149300                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149301                 var scriptInfo = project.getScriptInfoForNormalizedPath(file);
149302                 var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition;
149303                 var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file));
149304                 return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(codeAction); }) : codeActions;
149305             };
149306             Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) {
149307                 var scope = _a.scope, fixId = _a.fixId;
149308                 ts.Debug.assert(scope.type === "file");
149309                 var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project;
149310                 var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, this.getFormatOptions(file), this.getPreferences(file));
149311                 if (simplifiedResult) {
149312                     return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands };
149313                 }
149314                 else {
149315                     return res;
149316                 }
149317             };
149318             Session.prototype.applyCodeActionCommand = function (args) {
149319                 var commands = args.command; // They should be sending back the command we sent them.
149320                 for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) {
149321                     var command = _a[_i];
149322                     var _b = this.getFileAndProject(command), file = _b.file, project = _b.project;
149323                     project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { });
149324                 }
149325                 return {};
149326             };
149327             Session.prototype.getStartAndEndPosition = function (args, scriptInfo) {
149328                 var startPosition, endPosition;
149329                 if (args.startPosition !== undefined) {
149330                     startPosition = args.startPosition;
149331                 }
149332                 else {
149333                     startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
149334                     // save the result so we don't always recompute
149335                     args.startPosition = startPosition;
149336                 }
149337                 if (args.endPosition !== undefined) {
149338                     endPosition = args.endPosition;
149339                 }
149340                 else {
149341                     endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
149342                     args.endPosition = endPosition;
149343                 }
149344                 return { startPosition: startPosition, endPosition: endPosition };
149345             };
149346             Session.prototype.mapCodeAction = function (_a) {
149347                 var description = _a.description, changes = _a.changes, commands = _a.commands;
149348                 return { description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands };
149349             };
149350             Session.prototype.mapCodeFixAction = function (_a) {
149351                 var fixName = _a.fixName, description = _a.description, changes = _a.changes, commands = _a.commands, fixId = _a.fixId, fixAllDescription = _a.fixAllDescription;
149352                 return { fixName: fixName, description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands, fixId: fixId, fixAllDescription: fixAllDescription };
149353             };
149354             Session.prototype.mapTextChangesToCodeEdits = function (textChanges) {
149355                 var _this = this;
149356                 return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(change); });
149357             };
149358             Session.prototype.mapTextChangeToCodeEdit = function (textChanges) {
149359                 var scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName);
149360                 if (!!textChanges.isNewFile === !!scriptInfo) {
149361                     if (!scriptInfo) { // and !isNewFile
149362                         this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName);
149363                     }
149364                     ts.Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo }));
149365                 }
149366                 return scriptInfo
149367                     ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) }
149368                     : convertNewFileTextChangeToCodeEdit(textChanges);
149369             };
149370             Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) {
149371                 return {
149372                     start: scriptInfo.positionToLineOffset(change.span.start),
149373                     end: scriptInfo.positionToLineOffset(change.span.start + change.span.length),
149374                     newText: change.newText ? change.newText : ""
149375                 };
149376             };
149377             Session.prototype.getBraceMatching = function (args, simplifiedResult) {
149378                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
149379                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
149380                 var position = this.getPosition(args, scriptInfo);
149381                 var spans = languageService.getBraceMatchingAtPosition(file, position);
149382                 return !spans
149383                     ? undefined
149384                     : simplifiedResult
149385                         ? spans.map(function (span) { return toProtocolTextSpan(span, scriptInfo); })
149386                         : spans;
149387             };
149388             Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) {
149389                 if (this.suppressDiagnosticEvents) {
149390                     return;
149391                 }
149392                 var _a = this.getProjectInfoWorker(fileName, /*projectFileName*/ undefined, /*needFileNameList*/ true, /*excludeConfigFiles*/ true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
149393                 if (languageServiceDisabled) {
149394                     return;
149395                 }
149396                 // No need to analyze lib.d.ts
149397                 var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); // TODO: GH#18217
149398                 if (fileNamesInProject.length === 0) {
149399                     return;
149400                 }
149401                 // Sort the file name list to make the recently touched files come first
149402                 var highPriorityFiles = [];
149403                 var mediumPriorityFiles = [];
149404                 var lowPriorityFiles = [];
149405                 var veryLowPriorityFiles = [];
149406                 var normalizedFileName = server.toNormalizedPath(fileName);
149407                 var project = this.projectService.ensureDefaultProjectForFile(normalizedFileName);
149408                 for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) {
149409                     var fileNameInProject = fileNamesInProject_1[_i];
149410                     if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) {
149411                         highPriorityFiles.push(fileNameInProject);
149412                     }
149413                     else {
149414                         var info = this.projectService.getScriptInfo(fileNameInProject); // TODO: GH#18217
149415                         if (!info.isScriptOpen()) {
149416                             if (ts.fileExtensionIs(fileNameInProject, ".d.ts" /* Dts */)) {
149417                                 veryLowPriorityFiles.push(fileNameInProject);
149418                             }
149419                             else {
149420                                 lowPriorityFiles.push(fileNameInProject);
149421                             }
149422                         }
149423                         else {
149424                             mediumPriorityFiles.push(fileNameInProject);
149425                         }
149426                     }
149427                 }
149428                 var sortedFiles = __spreadArrays(highPriorityFiles, mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles);
149429                 var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); });
149430                 // Project level error analysis runs on background files too, therefore
149431                 // doesn't require the file to be opened
149432                 this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false);
149433             };
149434             Session.prototype.configurePlugin = function (args) {
149435                 this.projectService.configurePlugin(args);
149436             };
149437             Session.prototype.getSmartSelectionRange = function (args, simplifiedResult) {
149438                 var _this = this;
149439                 var locations = args.locations;
149440                 var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
149441                 var scriptInfo = ts.Debug.checkDefined(this.projectService.getScriptInfo(file));
149442                 return ts.map(locations, function (location) {
149443                     var pos = _this.getPosition(location, scriptInfo);
149444                     var selectionRange = languageService.getSmartSelectionRange(file, pos);
149445                     return simplifiedResult ? _this.mapSelectionRange(selectionRange, scriptInfo) : selectionRange;
149446                 });
149447             };
149448             Session.prototype.mapSelectionRange = function (selectionRange, scriptInfo) {
149449                 var result = {
149450                     textSpan: toProtocolTextSpan(selectionRange.textSpan, scriptInfo),
149451                 };
149452                 if (selectionRange.parent) {
149453                     result.parent = this.mapSelectionRange(selectionRange.parent, scriptInfo);
149454                 }
149455                 return result;
149456             };
149457             Session.prototype.getScriptInfoFromProjectService = function (file) {
149458                 var normalizedFile = server.toNormalizedPath(file);
149459                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(normalizedFile);
149460                 if (!scriptInfo) {
149461                     this.projectService.logErrorForScriptInfoNotFound(normalizedFile);
149462                     return server.Errors.ThrowNoProject();
149463                 }
149464                 return scriptInfo;
149465             };
149466             Session.prototype.toProtocolCallHierarchyItem = function (item) {
149467                 var scriptInfo = this.getScriptInfoFromProjectService(item.file);
149468                 return {
149469                     name: item.name,
149470                     kind: item.kind,
149471                     file: item.file,
149472                     span: toProtocolTextSpan(item.span, scriptInfo),
149473                     selectionSpan: toProtocolTextSpan(item.selectionSpan, scriptInfo)
149474                 };
149475             };
149476             Session.prototype.toProtocolCallHierarchyIncomingCall = function (incomingCall) {
149477                 var scriptInfo = this.getScriptInfoFromProjectService(incomingCall.from.file);
149478                 return {
149479                     from: this.toProtocolCallHierarchyItem(incomingCall.from),
149480                     fromSpans: incomingCall.fromSpans.map(function (fromSpan) { return toProtocolTextSpan(fromSpan, scriptInfo); })
149481                 };
149482             };
149483             Session.prototype.toProtocolCallHierarchyOutgoingCall = function (outgoingCall, scriptInfo) {
149484                 return {
149485                     to: this.toProtocolCallHierarchyItem(outgoingCall.to),
149486                     fromSpans: outgoingCall.fromSpans.map(function (fromSpan) { return toProtocolTextSpan(fromSpan, scriptInfo); })
149487                 };
149488             };
149489             Session.prototype.prepareCallHierarchy = function (args) {
149490                 var _this = this;
149491                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149492                 var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
149493                 if (scriptInfo) {
149494                     var position = this.getPosition(args, scriptInfo);
149495                     var result = project.getLanguageService().prepareCallHierarchy(file, position);
149496                     return result && ts.mapOneOrMany(result, function (item) { return _this.toProtocolCallHierarchyItem(item); });
149497                 }
149498                 return undefined;
149499             };
149500             Session.prototype.provideCallHierarchyIncomingCalls = function (args) {
149501                 var _this = this;
149502                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149503                 var scriptInfo = this.getScriptInfoFromProjectService(file);
149504                 var incomingCalls = project.getLanguageService().provideCallHierarchyIncomingCalls(file, this.getPosition(args, scriptInfo));
149505                 return incomingCalls.map(function (call) { return _this.toProtocolCallHierarchyIncomingCall(call); });
149506             };
149507             Session.prototype.provideCallHierarchyOutgoingCalls = function (args) {
149508                 var _this = this;
149509                 var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
149510                 var scriptInfo = this.getScriptInfoFromProjectService(file);
149511                 var outgoingCalls = project.getLanguageService().provideCallHierarchyOutgoingCalls(file, this.getPosition(args, scriptInfo));
149512                 return outgoingCalls.map(function (call) { return _this.toProtocolCallHierarchyOutgoingCall(call, scriptInfo); });
149513             };
149514             Session.prototype.getCanonicalFileName = function (fileName) {
149515                 var name = this.host.useCaseSensitiveFileNames ? fileName : ts.toFileNameLowerCase(fileName);
149516                 return ts.normalizePath(name);
149517             };
149518             Session.prototype.exit = function () { };
149519             Session.prototype.notRequired = function () {
149520                 return { responseRequired: false };
149521             };
149522             Session.prototype.requiredResponse = function (response) {
149523                 return { response: response, responseRequired: true };
149524             };
149525             Session.prototype.addProtocolHandler = function (command, handler) {
149526                 if (this.handlers.has(command)) {
149527                     throw new Error("Protocol handler already exists for command \"" + command + "\"");
149528                 }
149529                 this.handlers.set(command, handler);
149530             };
149531             Session.prototype.setCurrentRequest = function (requestId) {
149532                 ts.Debug.assert(this.currentRequestId === undefined);
149533                 this.currentRequestId = requestId;
149534                 this.cancellationToken.setRequest(requestId);
149535             };
149536             Session.prototype.resetCurrentRequest = function (requestId) {
149537                 ts.Debug.assert(this.currentRequestId === requestId);
149538                 this.currentRequestId = undefined; // TODO: GH#18217
149539                 this.cancellationToken.resetRequest(requestId);
149540             };
149541             Session.prototype.executeWithRequestId = function (requestId, f) {
149542                 try {
149543                     this.setCurrentRequest(requestId);
149544                     return f();
149545                 }
149546                 finally {
149547                     this.resetCurrentRequest(requestId);
149548                 }
149549             };
149550             Session.prototype.executeCommand = function (request) {
149551                 var handler = this.handlers.get(request.command);
149552                 if (handler) {
149553                     return this.executeWithRequestId(request.seq, function () { return handler(request); });
149554                 }
149555                 else {
149556                     this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err);
149557                     this.doOutput(/*info*/ undefined, server.CommandNames.Unknown, request.seq, /*success*/ false, "Unrecognized JSON command: " + request.command);
149558                     return { responseRequired: false };
149559                 }
149560             };
149561             Session.prototype.onMessage = function (message) {
149562                 this.gcTimer.scheduleCollect();
149563                 this.updateGraphDurationMs = undefined;
149564                 var start;
149565                 if (this.logger.hasLevel(server.LogLevel.requestTime)) {
149566                     start = this.hrtime();
149567                     if (this.logger.hasLevel(server.LogLevel.verbose)) {
149568                         this.logger.info("request:" + server.indent(message));
149569                     }
149570                 }
149571                 var request;
149572                 var relevantFile;
149573                 try {
149574                     request = JSON.parse(message);
149575                     relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined;
149576                     ts.perfLogger.logStartCommand("" + request.command, message.substring(0, 100));
149577                     var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired;
149578                     if (this.logger.hasLevel(server.LogLevel.requestTime)) {
149579                         var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4);
149580                         if (responseRequired) {
149581                             this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime);
149582                         }
149583                         else {
149584                             this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime);
149585                         }
149586                     }
149587                     // Note: Log before writing the response, else the editor can complete its activity before the server does
149588                     ts.perfLogger.logStopCommand("" + request.command, "Success");
149589                     if (response) {
149590                         this.doOutput(response, request.command, request.seq, /*success*/ true);
149591                     }
149592                     else if (responseRequired) {
149593                         this.doOutput(/*info*/ undefined, request.command, request.seq, /*success*/ false, "No content available.");
149594                     }
149595                 }
149596                 catch (err) {
149597                     if (err instanceof ts.OperationCanceledException) {
149598                         // Handle cancellation exceptions
149599                         ts.perfLogger.logStopCommand("" + (request && request.command), "Canceled: " + err);
149600                         this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true);
149601                         return;
149602                     }
149603                     this.logErrorWorker(err, message, relevantFile);
149604                     ts.perfLogger.logStopCommand("" + (request && request.command), "Error: " + err);
149605                     this.doOutput(
149606                     /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, 
149607                     /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack);
149608                 }
149609             };
149610             Session.prototype.getFormatOptions = function (file) {
149611                 return this.projectService.getFormatCodeOptions(file);
149612             };
149613             Session.prototype.getPreferences = function (file) {
149614                 return this.projectService.getPreferences(file);
149615             };
149616             Session.prototype.getHostFormatOptions = function () {
149617                 return this.projectService.getHostFormatCodeOptions();
149618             };
149619             Session.prototype.getHostPreferences = function () {
149620                 return this.projectService.getHostPreferences();
149621             };
149622             return Session;
149623         }());
149624         server.Session = Session;
149625         function toProtocolTextSpan(textSpan, scriptInfo) {
149626             return {
149627                 start: scriptInfo.positionToLineOffset(textSpan.start),
149628                 end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan))
149629             };
149630         }
149631         function toProtocolTextSpanWithContext(span, contextSpan, scriptInfo) {
149632             var textSpan = toProtocolTextSpan(span, scriptInfo);
149633             var contextTextSpan = contextSpan && toProtocolTextSpan(contextSpan, scriptInfo);
149634             return contextTextSpan ? __assign(__assign({}, textSpan), { contextStart: contextTextSpan.start, contextEnd: contextTextSpan.end }) :
149635                 textSpan;
149636         }
149637         function convertTextChangeToCodeEdit(change, scriptInfo) {
149638             return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, ts.textSpanEnd(change.span)), newText: change.newText };
149639         }
149640         function positionToLineOffset(info, position) {
149641             return server.isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position);
149642         }
149643         function locationFromLineAndCharacter(lc) {
149644             return { line: lc.line + 1, offset: lc.character + 1 };
149645         }
149646         function convertNewFileTextChangeToCodeEdit(textChanges) {
149647             ts.Debug.assert(textChanges.textChanges.length === 1);
149648             var change = ts.first(textChanges.textChanges);
149649             ts.Debug.assert(change.span.start === 0 && change.span.length === 0);
149650             return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] };
149651         }
149652         /* @internal */ // Exported only for tests
149653         function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) {
149654             var newText = applyEdits(oldText, renameFilename, edits);
149655             var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character;
149656             return { line: line + 1, offset: character + 1 };
149657         }
149658         server.getLocationInNewDocument = getLocationInNewDocument;
149659         function applyEdits(text, textFilename, edits) {
149660             for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
149661                 var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
149662                 if (fileName !== textFilename) {
149663                     continue;
149664                 }
149665                 for (var i = textChanges_1.length - 1; i >= 0; i--) {
149666                     var _b = textChanges_1[i], newText = _b.newText, _c = _b.span, start = _c.start, length_1 = _c.length;
149667                     text = text.slice(0, start) + newText + text.slice(start + length_1);
149668                 }
149669             }
149670             return text;
149671         }
149672     })(server = ts.server || (ts.server = {}));
149673 })(ts || (ts = {}));
149674 /*@internal*/
149675 var ts;
149676 (function (ts) {
149677     var server;
149678     (function (server) {
149679         var lineCollectionCapacity = 4;
149680         var CharRangeSection;
149681         (function (CharRangeSection) {
149682             CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart";
149683             CharRangeSection[CharRangeSection["Start"] = 1] = "Start";
149684             CharRangeSection[CharRangeSection["Entire"] = 2] = "Entire";
149685             CharRangeSection[CharRangeSection["Mid"] = 3] = "Mid";
149686             CharRangeSection[CharRangeSection["End"] = 4] = "End";
149687             CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd";
149688         })(CharRangeSection || (CharRangeSection = {}));
149689         var EditWalker = /** @class */ (function () {
149690             function EditWalker() {
149691                 this.goSubtree = true;
149692                 this.lineIndex = new LineIndex();
149693                 this.endBranch = [];
149694                 this.state = 2 /* Entire */;
149695                 this.initialText = "";
149696                 this.trailingText = "";
149697                 this.lineIndex.root = new LineNode();
149698                 this.startPath = [this.lineIndex.root];
149699                 this.stack = [this.lineIndex.root];
149700             }
149701             Object.defineProperty(EditWalker.prototype, "done", {
149702                 get: function () { return false; },
149703                 enumerable: false,
149704                 configurable: true
149705             });
149706             EditWalker.prototype.insertLines = function (insertedText, suppressTrailingText) {
149707                 if (suppressTrailingText) {
149708                     this.trailingText = "";
149709                 }
149710                 if (insertedText) {
149711                     insertedText = this.initialText + insertedText + this.trailingText;
149712                 }
149713                 else {
149714                     insertedText = this.initialText + this.trailingText;
149715                 }
149716                 var lm = LineIndex.linesFromText(insertedText);
149717                 var lines = lm.lines;
149718                 if (lines.length > 1) {
149719                     if (lines[lines.length - 1] === "") {
149720                         lines.pop();
149721                     }
149722                 }
149723                 var branchParent;
149724                 var lastZeroCount;
149725                 for (var k = this.endBranch.length - 1; k >= 0; k--) {
149726                     this.endBranch[k].updateCounts();
149727                     if (this.endBranch[k].charCount() === 0) {
149728                         lastZeroCount = this.endBranch[k];
149729                         if (k > 0) {
149730                             branchParent = this.endBranch[k - 1];
149731                         }
149732                         else {
149733                             branchParent = this.branchNode;
149734                         }
149735                     }
149736                 }
149737                 if (lastZeroCount) {
149738                     branchParent.remove(lastZeroCount);
149739                 }
149740                 // path at least length two (root and leaf)
149741                 var leafNode = this.startPath[this.startPath.length - 1];
149742                 if (lines.length > 0) {
149743                     leafNode.text = lines[0];
149744                     if (lines.length > 1) {
149745                         var insertedNodes = new Array(lines.length - 1);
149746                         var startNode = leafNode;
149747                         for (var i = 1; i < lines.length; i++) {
149748                             insertedNodes[i - 1] = new LineLeaf(lines[i]);
149749                         }
149750                         var pathIndex = this.startPath.length - 2;
149751                         while (pathIndex >= 0) {
149752                             var insertionNode = this.startPath[pathIndex];
149753                             insertedNodes = insertionNode.insertAt(startNode, insertedNodes);
149754                             pathIndex--;
149755                             startNode = insertionNode;
149756                         }
149757                         var insertedNodesLen = insertedNodes.length;
149758                         while (insertedNodesLen > 0) {
149759                             var newRoot = new LineNode();
149760                             newRoot.add(this.lineIndex.root);
149761                             insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes);
149762                             insertedNodesLen = insertedNodes.length;
149763                             this.lineIndex.root = newRoot;
149764                         }
149765                         this.lineIndex.root.updateCounts();
149766                     }
149767                     else {
149768                         for (var j = this.startPath.length - 2; j >= 0; j--) {
149769                             this.startPath[j].updateCounts();
149770                         }
149771                     }
149772                 }
149773                 else {
149774                     var insertionNode = this.startPath[this.startPath.length - 2];
149775                     // no content for leaf node, so delete it
149776                     insertionNode.remove(leafNode);
149777                     for (var j = this.startPath.length - 2; j >= 0; j--) {
149778                         this.startPath[j].updateCounts();
149779                     }
149780                 }
149781                 return this.lineIndex;
149782             };
149783             EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) {
149784                 // have visited the path for start of range, now looking for end
149785                 // if range is on single line, we will never make this state transition
149786                 if (lineCollection === this.lineCollectionAtBranch) {
149787                     this.state = 4 /* End */;
149788                 }
149789                 // always pop stack because post only called when child has been visited
149790                 this.stack.pop();
149791             };
149792             EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) {
149793                 // currentNode corresponds to parent, but in the new tree
149794                 var currentNode = this.stack[this.stack.length - 1];
149795                 if ((this.state === 2 /* Entire */) && (nodeType === 1 /* Start */)) {
149796                     // if range is on single line, we will never make this state transition
149797                     this.state = 1 /* Start */;
149798                     this.branchNode = currentNode;
149799                     this.lineCollectionAtBranch = lineCollection;
149800                 }
149801                 var child;
149802                 function fresh(node) {
149803                     if (node.isLeaf()) {
149804                         return new LineLeaf("");
149805                     }
149806                     else
149807                         return new LineNode();
149808                 }
149809                 switch (nodeType) {
149810                     case 0 /* PreStart */:
149811                         this.goSubtree = false;
149812                         if (this.state !== 4 /* End */) {
149813                             currentNode.add(lineCollection);
149814                         }
149815                         break;
149816                     case 1 /* Start */:
149817                         if (this.state === 4 /* End */) {
149818                             this.goSubtree = false;
149819                         }
149820                         else {
149821                             child = fresh(lineCollection);
149822                             currentNode.add(child);
149823                             this.startPath.push(child);
149824                         }
149825                         break;
149826                     case 2 /* Entire */:
149827                         if (this.state !== 4 /* End */) {
149828                             child = fresh(lineCollection);
149829                             currentNode.add(child);
149830                             this.startPath.push(child);
149831                         }
149832                         else {
149833                             if (!lineCollection.isLeaf()) {
149834                                 child = fresh(lineCollection);
149835                                 currentNode.add(child);
149836                                 this.endBranch.push(child);
149837                             }
149838                         }
149839                         break;
149840                     case 3 /* Mid */:
149841                         this.goSubtree = false;
149842                         break;
149843                     case 4 /* End */:
149844                         if (this.state !== 4 /* End */) {
149845                             this.goSubtree = false;
149846                         }
149847                         else {
149848                             if (!lineCollection.isLeaf()) {
149849                                 child = fresh(lineCollection);
149850                                 currentNode.add(child);
149851                                 this.endBranch.push(child);
149852                             }
149853                         }
149854                         break;
149855                     case 5 /* PostEnd */:
149856                         this.goSubtree = false;
149857                         if (this.state !== 1 /* Start */) {
149858                             currentNode.add(lineCollection);
149859                         }
149860                         break;
149861                 }
149862                 if (this.goSubtree) {
149863                     this.stack.push(child);
149864                 }
149865             };
149866             // just gather text from the leaves
149867             EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) {
149868                 if (this.state === 1 /* Start */) {
149869                     this.initialText = ll.text.substring(0, relativeStart);
149870                 }
149871                 else if (this.state === 2 /* Entire */) {
149872                     this.initialText = ll.text.substring(0, relativeStart);
149873                     this.trailingText = ll.text.substring(relativeStart + relativeLength);
149874                 }
149875                 else {
149876                     // state is CharRangeSection.End
149877                     this.trailingText = ll.text.substring(relativeStart + relativeLength);
149878                 }
149879             };
149880             return EditWalker;
149881         }());
149882         // text change information
149883         var TextChange = /** @class */ (function () {
149884             function TextChange(pos, deleteLen, insertedText) {
149885                 this.pos = pos;
149886                 this.deleteLen = deleteLen;
149887                 this.insertedText = insertedText;
149888             }
149889             TextChange.prototype.getTextChangeRange = function () {
149890                 return ts.createTextChangeRange(ts.createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0);
149891             };
149892             return TextChange;
149893         }());
149894         var ScriptVersionCache = /** @class */ (function () {
149895             function ScriptVersionCache() {
149896                 this.changes = [];
149897                 this.versions = new Array(ScriptVersionCache.maxVersions);
149898                 this.minVersion = 0; // no versions earlier than min version will maintain change history
149899                 this.currentVersion = 0;
149900             }
149901             ScriptVersionCache.prototype.versionToIndex = function (version) {
149902                 if (version < this.minVersion || version > this.currentVersion) {
149903                     return undefined;
149904                 }
149905                 return version % ScriptVersionCache.maxVersions;
149906             };
149907             ScriptVersionCache.prototype.currentVersionToIndex = function () {
149908                 return this.currentVersion % ScriptVersionCache.maxVersions;
149909             };
149910             // REVIEW: can optimize by coalescing simple edits
149911             ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) {
149912                 this.changes.push(new TextChange(pos, deleteLen, insertedText));
149913                 if (this.changes.length > ScriptVersionCache.changeNumberThreshold ||
149914                     deleteLen > ScriptVersionCache.changeLengthThreshold ||
149915                     insertedText && insertedText.length > ScriptVersionCache.changeLengthThreshold) {
149916                     this.getSnapshot();
149917                 }
149918             };
149919             ScriptVersionCache.prototype.getSnapshot = function () { return this._getSnapshot(); };
149920             ScriptVersionCache.prototype._getSnapshot = function () {
149921                 var snap = this.versions[this.currentVersionToIndex()];
149922                 if (this.changes.length > 0) {
149923                     var snapIndex = snap.index;
149924                     for (var _i = 0, _a = this.changes; _i < _a.length; _i++) {
149925                         var change = _a[_i];
149926                         snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText);
149927                     }
149928                     snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes);
149929                     this.currentVersion = snap.version;
149930                     this.versions[this.currentVersionToIndex()] = snap;
149931                     this.changes = [];
149932                     if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) {
149933                         this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1;
149934                     }
149935                 }
149936                 return snap;
149937             };
149938             ScriptVersionCache.prototype.getSnapshotVersion = function () {
149939                 return this._getSnapshot().version;
149940             };
149941             ScriptVersionCache.prototype.getAbsolutePositionAndLineText = function (oneBasedLine) {
149942                 return this._getSnapshot().index.lineNumberToInfo(oneBasedLine);
149943             };
149944             ScriptVersionCache.prototype.lineOffsetToPosition = function (line, column) {
149945                 return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1);
149946             };
149947             ScriptVersionCache.prototype.positionToLineOffset = function (position) {
149948                 return this._getSnapshot().index.positionToLineOffset(position);
149949             };
149950             ScriptVersionCache.prototype.lineToTextSpan = function (line) {
149951                 var index = this._getSnapshot().index;
149952                 var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition;
149953                 var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition;
149954                 return ts.createTextSpan(absolutePosition, len);
149955             };
149956             ScriptVersionCache.prototype.getTextChangesBetweenVersions = function (oldVersion, newVersion) {
149957                 if (oldVersion < newVersion) {
149958                     if (oldVersion >= this.minVersion) {
149959                         var textChangeRanges = [];
149960                         for (var i = oldVersion + 1; i <= newVersion; i++) {
149961                             var snap = this.versions[this.versionToIndex(i)]; // TODO: GH#18217
149962                             for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) {
149963                                 var textChange = _a[_i];
149964                                 textChangeRanges.push(textChange.getTextChangeRange());
149965                             }
149966                         }
149967                         return ts.collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges);
149968                     }
149969                     else {
149970                         return undefined;
149971                     }
149972                 }
149973                 else {
149974                     return ts.unchangedTextChangeRange;
149975                 }
149976             };
149977             ScriptVersionCache.prototype.getLineCount = function () {
149978                 return this._getSnapshot().index.getLineCount();
149979             };
149980             ScriptVersionCache.fromString = function (script) {
149981                 var svc = new ScriptVersionCache();
149982                 var snap = new LineIndexSnapshot(0, svc, new LineIndex());
149983                 svc.versions[svc.currentVersion] = snap;
149984                 var lm = LineIndex.linesFromText(script);
149985                 snap.index.load(lm.lines);
149986                 return svc;
149987             };
149988             ScriptVersionCache.changeNumberThreshold = 8;
149989             ScriptVersionCache.changeLengthThreshold = 256;
149990             ScriptVersionCache.maxVersions = 8;
149991             return ScriptVersionCache;
149992         }());
149993         server.ScriptVersionCache = ScriptVersionCache;
149994         var LineIndexSnapshot = /** @class */ (function () {
149995             function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) {
149996                 if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; }
149997                 this.version = version;
149998                 this.cache = cache;
149999                 this.index = index;
150000                 this.changesSincePreviousVersion = changesSincePreviousVersion;
150001             }
150002             LineIndexSnapshot.prototype.getText = function (rangeStart, rangeEnd) {
150003                 return this.index.getText(rangeStart, rangeEnd - rangeStart);
150004             };
150005             LineIndexSnapshot.prototype.getLength = function () {
150006                 return this.index.getLength();
150007             };
150008             LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) {
150009                 if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) {
150010                     if (this.version <= oldSnapshot.version) {
150011                         return ts.unchangedTextChangeRange;
150012                     }
150013                     else {
150014                         return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version);
150015                     }
150016                 }
150017             };
150018             return LineIndexSnapshot;
150019         }());
150020         var LineIndex = /** @class */ (function () {
150021             function LineIndex() {
150022                 // set this to true to check each edit for accuracy
150023                 this.checkEdits = false;
150024             }
150025             LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) {
150026                 return this.lineNumberToInfo(oneBasedLine).absolutePosition;
150027             };
150028             LineIndex.prototype.positionToLineOffset = function (position) {
150029                 var _a = this.root.charOffsetToLineInfo(1, position), oneBasedLine = _a.oneBasedLine, zeroBasedColumn = _a.zeroBasedColumn;
150030                 return { line: oneBasedLine, offset: zeroBasedColumn + 1 };
150031             };
150032             LineIndex.prototype.positionToColumnAndLineText = function (position) {
150033                 return this.root.charOffsetToLineInfo(1, position);
150034             };
150035             LineIndex.prototype.getLineCount = function () {
150036                 return this.root.lineCount();
150037             };
150038             LineIndex.prototype.lineNumberToInfo = function (oneBasedLine) {
150039                 var lineCount = this.getLineCount();
150040                 if (oneBasedLine <= lineCount) {
150041                     var _a = this.root.lineNumberToInfo(oneBasedLine, 0), position = _a.position, leaf = _a.leaf;
150042                     return { absolutePosition: position, lineText: leaf && leaf.text };
150043                 }
150044                 else {
150045                     return { absolutePosition: this.root.charCount(), lineText: undefined };
150046                 }
150047             };
150048             LineIndex.prototype.load = function (lines) {
150049                 if (lines.length > 0) {
150050                     var leaves = [];
150051                     for (var i = 0; i < lines.length; i++) {
150052                         leaves[i] = new LineLeaf(lines[i]);
150053                     }
150054                     this.root = LineIndex.buildTreeFromBottom(leaves);
150055                 }
150056                 else {
150057                     this.root = new LineNode();
150058                 }
150059             };
150060             LineIndex.prototype.walk = function (rangeStart, rangeLength, walkFns) {
150061                 this.root.walk(rangeStart, rangeLength, walkFns);
150062             };
150063             LineIndex.prototype.getText = function (rangeStart, rangeLength) {
150064                 var accum = "";
150065                 if ((rangeLength > 0) && (rangeStart < this.root.charCount())) {
150066                     this.walk(rangeStart, rangeLength, {
150067                         goSubtree: true,
150068                         done: false,
150069                         leaf: function (relativeStart, relativeLength, ll) {
150070                             accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength));
150071                         }
150072                     });
150073                 }
150074                 return accum;
150075             };
150076             LineIndex.prototype.getLength = function () {
150077                 return this.root.charCount();
150078             };
150079             LineIndex.prototype.every = function (f, rangeStart, rangeEnd) {
150080                 if (!rangeEnd) {
150081                     rangeEnd = this.root.charCount();
150082                 }
150083                 var walkFns = {
150084                     goSubtree: true,
150085                     done: false,
150086                     leaf: function (relativeStart, relativeLength, ll) {
150087                         if (!f(ll, relativeStart, relativeLength)) {
150088                             this.done = true;
150089                         }
150090                     }
150091                 };
150092                 this.walk(rangeStart, rangeEnd - rangeStart, walkFns);
150093                 return !walkFns.done;
150094             };
150095             LineIndex.prototype.edit = function (pos, deleteLength, newText) {
150096                 if (this.root.charCount() === 0) {
150097                     ts.Debug.assert(deleteLength === 0); // Can't delete from empty document
150098                     if (newText !== undefined) {
150099                         this.load(LineIndex.linesFromText(newText).lines);
150100                         return this;
150101                     }
150102                     return undefined; // TODO: GH#18217
150103                 }
150104                 else {
150105                     var checkText = void 0;
150106                     if (this.checkEdits) {
150107                         var source = this.getText(0, this.root.charCount());
150108                         checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength);
150109                     }
150110                     var walker = new EditWalker();
150111                     var suppressTrailingText = false;
150112                     if (pos >= this.root.charCount()) {
150113                         // insert at end
150114                         pos = this.root.charCount() - 1;
150115                         var endString = this.getText(pos, 1);
150116                         if (newText) {
150117                             newText = endString + newText;
150118                         }
150119                         else {
150120                             newText = endString;
150121                         }
150122                         deleteLength = 0;
150123                         suppressTrailingText = true;
150124                     }
150125                     else if (deleteLength > 0) {
150126                         // check whether last characters deleted are line break
150127                         var e = pos + deleteLength;
150128                         var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText;
150129                         if (zeroBasedColumn === 0) {
150130                             // move range end just past line that will merge with previous line
150131                             deleteLength += lineText.length; // TODO: GH#18217
150132                             // store text by appending to end of insertedText
150133                             newText = newText ? newText + lineText : lineText;
150134                         }
150135                     }
150136                     this.root.walk(pos, deleteLength, walker);
150137                     walker.insertLines(newText, suppressTrailingText);
150138                     if (this.checkEdits) {
150139                         var updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength());
150140                         ts.Debug.assert(checkText === updatedText, "buffer edit mismatch");
150141                     }
150142                     return walker.lineIndex;
150143                 }
150144             };
150145             LineIndex.buildTreeFromBottom = function (nodes) {
150146                 if (nodes.length < lineCollectionCapacity) {
150147                     return new LineNode(nodes);
150148                 }
150149                 var interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity));
150150                 var nodeIndex = 0;
150151                 for (var i = 0; i < interiorNodes.length; i++) {
150152                     var end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length);
150153                     interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end));
150154                     nodeIndex = end;
150155                 }
150156                 return this.buildTreeFromBottom(interiorNodes);
150157             };
150158             LineIndex.linesFromText = function (text) {
150159                 var lineMap = ts.computeLineStarts(text);
150160                 if (lineMap.length === 0) {
150161                     return { lines: [], lineMap: lineMap };
150162                 }
150163                 var lines = new Array(lineMap.length);
150164                 var lc = lineMap.length - 1;
150165                 for (var lmi = 0; lmi < lc; lmi++) {
150166                     lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]);
150167                 }
150168                 var endText = text.substring(lineMap[lc]);
150169                 if (endText.length > 0) {
150170                     lines[lc] = endText;
150171                 }
150172                 else {
150173                     lines.pop();
150174                 }
150175                 return { lines: lines, lineMap: lineMap };
150176             };
150177             return LineIndex;
150178         }());
150179         server.LineIndex = LineIndex;
150180         var LineNode = /** @class */ (function () {
150181             function LineNode(children) {
150182                 if (children === void 0) { children = []; }
150183                 this.children = children;
150184                 this.totalChars = 0;
150185                 this.totalLines = 0;
150186                 if (children.length)
150187                     this.updateCounts();
150188             }
150189             LineNode.prototype.isLeaf = function () {
150190                 return false;
150191             };
150192             LineNode.prototype.updateCounts = function () {
150193                 this.totalChars = 0;
150194                 this.totalLines = 0;
150195                 for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
150196                     var child = _a[_i];
150197                     this.totalChars += child.charCount();
150198                     this.totalLines += child.lineCount();
150199                 }
150200             };
150201             LineNode.prototype.execWalk = function (rangeStart, rangeLength, walkFns, childIndex, nodeType) {
150202                 if (walkFns.pre) {
150203                     walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType);
150204                 }
150205                 if (walkFns.goSubtree) {
150206                     this.children[childIndex].walk(rangeStart, rangeLength, walkFns);
150207                     if (walkFns.post) {
150208                         walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType);
150209                     }
150210                 }
150211                 else {
150212                     walkFns.goSubtree = true;
150213                 }
150214                 return walkFns.done;
150215             };
150216             LineNode.prototype.skipChild = function (relativeStart, relativeLength, childIndex, walkFns, nodeType) {
150217                 if (walkFns.pre && (!walkFns.done)) {
150218                     walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType);
150219                     walkFns.goSubtree = true;
150220                 }
150221             };
150222             LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) {
150223                 // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars)
150224                 var childIndex = 0;
150225                 var childCharCount = this.children[childIndex].charCount();
150226                 // find sub-tree containing start
150227                 var adjustedStart = rangeStart;
150228                 while (adjustedStart >= childCharCount) {
150229                     this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */);
150230                     adjustedStart -= childCharCount;
150231                     childIndex++;
150232                     childCharCount = this.children[childIndex].charCount();
150233                 }
150234                 // Case I: both start and end of range in same subtree
150235                 if ((adjustedStart + rangeLength) <= childCharCount) {
150236                     if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) {
150237                         return;
150238                     }
150239                 }
150240                 else {
150241                     // Case II: start and end of range in different subtrees (possibly with subtrees in the middle)
150242                     if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) {
150243                         return;
150244                     }
150245                     var adjustedLength = rangeLength - (childCharCount - adjustedStart);
150246                     childIndex++;
150247                     var child = this.children[childIndex];
150248                     childCharCount = child.charCount();
150249                     while (adjustedLength > childCharCount) {
150250                         if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) {
150251                             return;
150252                         }
150253                         adjustedLength -= childCharCount;
150254                         childIndex++;
150255                         childCharCount = this.children[childIndex].charCount();
150256                     }
150257                     if (adjustedLength > 0) {
150258                         if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) {
150259                             return;
150260                         }
150261                     }
150262                 }
150263                 // Process any subtrees after the one containing range end
150264                 if (walkFns.pre) {
150265                     var clen = this.children.length;
150266                     if (childIndex < (clen - 1)) {
150267                         for (var ej = childIndex + 1; ej < clen; ej++) {
150268                             this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */);
150269                         }
150270                     }
150271                 }
150272             };
150273             // Input position is relative to the start of this node.
150274             // Output line number is absolute.
150275             LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) {
150276                 if (this.children.length === 0) {
150277                     // Root node might have no children if this is an empty document.
150278                     return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined };
150279                 }
150280                 for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
150281                     var child = _a[_i];
150282                     if (child.charCount() > relativePosition) {
150283                         if (child.isLeaf()) {
150284                             return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text };
150285                         }
150286                         else {
150287                             return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition);
150288                         }
150289                     }
150290                     else {
150291                         relativePosition -= child.charCount();
150292                         lineNumberAccumulator += child.lineCount();
150293                     }
150294                 }
150295                 // Skipped all children
150296                 var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf;
150297                 return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf ? leaf.charCount() : 0, lineText: undefined };
150298             };
150299             /**
150300              * Input line number is relative to the start of this node.
150301              * Output line number is relative to the child.
150302              * positionAccumulator will be an absolute position once relativeLineNumber reaches 0.
150303              */
150304             LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) {
150305                 for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
150306                     var child = _a[_i];
150307                     var childLineCount = child.lineCount();
150308                     if (childLineCount >= relativeOneBasedLine) {
150309                         return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator);
150310                     }
150311                     else {
150312                         relativeOneBasedLine -= childLineCount;
150313                         positionAccumulator += child.charCount();
150314                     }
150315                 }
150316                 return { position: positionAccumulator, leaf: undefined };
150317             };
150318             LineNode.prototype.splitAfter = function (childIndex) {
150319                 var splitNode;
150320                 var clen = this.children.length;
150321                 childIndex++;
150322                 var endLength = childIndex;
150323                 if (childIndex < clen) {
150324                     splitNode = new LineNode();
150325                     while (childIndex < clen) {
150326                         splitNode.add(this.children[childIndex]);
150327                         childIndex++;
150328                     }
150329                     splitNode.updateCounts();
150330                 }
150331                 this.children.length = endLength;
150332                 return splitNode;
150333             };
150334             LineNode.prototype.remove = function (child) {
150335                 var childIndex = this.findChildIndex(child);
150336                 var clen = this.children.length;
150337                 if (childIndex < (clen - 1)) {
150338                     for (var i = childIndex; i < (clen - 1); i++) {
150339                         this.children[i] = this.children[i + 1];
150340                     }
150341                 }
150342                 this.children.pop();
150343             };
150344             LineNode.prototype.findChildIndex = function (child) {
150345                 var childIndex = this.children.indexOf(child);
150346                 ts.Debug.assert(childIndex !== -1);
150347                 return childIndex;
150348             };
150349             LineNode.prototype.insertAt = function (child, nodes) {
150350                 var childIndex = this.findChildIndex(child);
150351                 var clen = this.children.length;
150352                 var nodeCount = nodes.length;
150353                 // if child is last and there is more room and only one node to place, place it
150354                 if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) {
150355                     this.add(nodes[0]);
150356                     this.updateCounts();
150357                     return [];
150358                 }
150359                 else {
150360                     var shiftNode = this.splitAfter(childIndex);
150361                     var nodeIndex = 0;
150362                     childIndex++;
150363                     while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) {
150364                         this.children[childIndex] = nodes[nodeIndex];
150365                         childIndex++;
150366                         nodeIndex++;
150367                     }
150368                     var splitNodes = [];
150369                     var splitNodeCount = 0;
150370                     if (nodeIndex < nodeCount) {
150371                         splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity);
150372                         splitNodes = new Array(splitNodeCount);
150373                         var splitNodeIndex = 0;
150374                         for (var i = 0; i < splitNodeCount; i++) {
150375                             splitNodes[i] = new LineNode();
150376                         }
150377                         var splitNode = splitNodes[0];
150378                         while (nodeIndex < nodeCount) {
150379                             splitNode.add(nodes[nodeIndex]);
150380                             nodeIndex++;
150381                             if (splitNode.children.length === lineCollectionCapacity) {
150382                                 splitNodeIndex++;
150383                                 splitNode = splitNodes[splitNodeIndex];
150384                             }
150385                         }
150386                         for (var i = splitNodes.length - 1; i >= 0; i--) {
150387                             if (splitNodes[i].children.length === 0) {
150388                                 splitNodes.pop();
150389                             }
150390                         }
150391                     }
150392                     if (shiftNode) {
150393                         splitNodes.push(shiftNode);
150394                     }
150395                     this.updateCounts();
150396                     for (var i = 0; i < splitNodeCount; i++) {
150397                         splitNodes[i].updateCounts();
150398                     }
150399                     return splitNodes;
150400                 }
150401             };
150402             // assume there is room for the item; return true if more room
150403             LineNode.prototype.add = function (collection) {
150404                 this.children.push(collection);
150405                 ts.Debug.assert(this.children.length <= lineCollectionCapacity);
150406             };
150407             LineNode.prototype.charCount = function () {
150408                 return this.totalChars;
150409             };
150410             LineNode.prototype.lineCount = function () {
150411                 return this.totalLines;
150412             };
150413             return LineNode;
150414         }());
150415         var LineLeaf = /** @class */ (function () {
150416             function LineLeaf(text) {
150417                 this.text = text;
150418             }
150419             LineLeaf.prototype.isLeaf = function () {
150420                 return true;
150421             };
150422             LineLeaf.prototype.walk = function (rangeStart, rangeLength, walkFns) {
150423                 walkFns.leaf(rangeStart, rangeLength, this);
150424             };
150425             LineLeaf.prototype.charCount = function () {
150426                 return this.text.length;
150427             };
150428             LineLeaf.prototype.lineCount = function () {
150429                 return 1;
150430             };
150431             return LineLeaf;
150432         }());
150433     })(server = ts.server || (ts.server = {}));
150434 })(ts || (ts = {}));
150435 var ts;
150436 (function (ts) {
150437     var server;
150438     (function (server) {
150439         var childProcess = require("child_process");
150440         var os = require("os");
150441         var net = require("net");
150442         function getGlobalTypingsCacheLocation() {
150443             switch (process.platform) {
150444                 case "win32": {
150445                     var basePath = process.env.LOCALAPPDATA ||
150446                         process.env.APPDATA ||
150447                         (os.homedir && os.homedir()) ||
150448                         process.env.USERPROFILE ||
150449                         (process.env.HOMEDRIVE && process.env.HOMEPATH && ts.normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH)) ||
150450                         os.tmpdir();
150451                     return ts.combinePaths(ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"), ts.versionMajorMinor);
150452                 }
150453                 case "openbsd":
150454                 case "freebsd":
150455                 case "netbsd":
150456                 case "darwin":
150457                 case "linux":
150458                 case "android": {
150459                     var cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin");
150460                     return ts.combinePaths(ts.combinePaths(cacheLocation, "typescript"), ts.versionMajorMinor);
150461                 }
150462                 default:
150463                     return ts.Debug.fail("unsupported platform '" + process.platform + "'");
150464             }
150465         }
150466         function getNonWindowsCacheLocation(platformIsDarwin) {
150467             if (process.env.XDG_CACHE_HOME) {
150468                 return process.env.XDG_CACHE_HOME;
150469             }
150470             var usersDir = platformIsDarwin ? "Users" : "home";
150471             var homePath = (os.homedir && os.homedir()) ||
150472                 process.env.HOME ||
150473                 ((process.env.LOGNAME || process.env.USER) && "/" + usersDir + "/" + (process.env.LOGNAME || process.env.USER)) ||
150474                 os.tmpdir();
150475             var cacheFolder = platformIsDarwin
150476                 ? "Library/Caches"
150477                 : ".cache";
150478             return ts.combinePaths(ts.normalizeSlashes(homePath), cacheFolder);
150479         }
150480         var readline = require("readline");
150481         var fs = require("fs");
150482         var rl = readline.createInterface({
150483             input: process.stdin,
150484             output: process.stdout,
150485             terminal: false,
150486         });
150487         var Logger = /** @class */ (function () {
150488             function Logger(logFilename, traceToConsole, level) {
150489                 this.logFilename = logFilename;
150490                 this.traceToConsole = traceToConsole;
150491                 this.level = level;
150492                 this.fd = -1;
150493                 this.seq = 0;
150494                 this.inGroup = false;
150495                 this.firstInGroup = true;
150496                 if (this.logFilename) {
150497                     try {
150498                         this.fd = fs.openSync(this.logFilename, "w");
150499                     }
150500                     catch (_) {
150501                         // swallow the error and keep logging disabled if file cannot be opened
150502                     }
150503                 }
150504             }
150505             Logger.padStringRight = function (str, padding) {
150506                 return (str + padding).slice(0, padding.length);
150507             };
150508             Logger.prototype.close = function () {
150509                 if (this.fd >= 0) {
150510                     fs.close(this.fd, ts.noop);
150511                 }
150512             };
150513             Logger.prototype.getLogFileName = function () {
150514                 return this.logFilename;
150515             };
150516             Logger.prototype.perftrc = function (s) {
150517                 this.msg(s, server.Msg.Perf);
150518             };
150519             Logger.prototype.info = function (s) {
150520                 this.msg(s, server.Msg.Info);
150521             };
150522             Logger.prototype.err = function (s) {
150523                 this.msg(s, server.Msg.Err);
150524             };
150525             Logger.prototype.startGroup = function () {
150526                 this.inGroup = true;
150527                 this.firstInGroup = true;
150528             };
150529             Logger.prototype.endGroup = function () {
150530                 this.inGroup = false;
150531             };
150532             Logger.prototype.loggingEnabled = function () {
150533                 return !!this.logFilename || this.traceToConsole;
150534             };
150535             Logger.prototype.hasLevel = function (level) {
150536                 return this.loggingEnabled() && this.level >= level;
150537             };
150538             Logger.prototype.msg = function (s, type) {
150539                 if (type === void 0) { type = server.Msg.Err; }
150540                 switch (type) {
150541                     case server.Msg.Info:
150542                         ts.perfLogger.logInfoEvent(s);
150543                         break;
150544                     case server.Msg.Perf:
150545                         ts.perfLogger.logPerfEvent(s);
150546                         break;
150547                     default: // Msg.Err
150548                         ts.perfLogger.logErrEvent(s);
150549                         break;
150550                 }
150551                 if (!this.canWrite)
150552                     return;
150553                 s = "[" + server.nowString() + "] " + s + "\n";
150554                 if (!this.inGroup || this.firstInGroup) {
150555                     var prefix = Logger.padStringRight(type + " " + this.seq.toString(), "          ");
150556                     s = prefix + s;
150557                 }
150558                 this.write(s);
150559                 if (!this.inGroup) {
150560                     this.seq++;
150561                 }
150562             };
150563             Object.defineProperty(Logger.prototype, "canWrite", {
150564                 get: function () {
150565                     return this.fd >= 0 || this.traceToConsole;
150566                 },
150567                 enumerable: false,
150568                 configurable: true
150569             });
150570             Logger.prototype.write = function (s) {
150571                 if (this.fd >= 0) {
150572                     var buf = sys.bufferFrom(s);
150573                     // eslint-disable-next-line no-null/no-null
150574                     fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null); // TODO: GH#18217
150575                 }
150576                 if (this.traceToConsole) {
150577                     console.warn(s);
150578                 }
150579             };
150580             return Logger;
150581         }());
150582         var NodeTypingsInstaller = /** @class */ (function () {
150583             function NodeTypingsInstaller(telemetryEnabled, logger, host, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, event) {
150584                 this.telemetryEnabled = telemetryEnabled;
150585                 this.logger = logger;
150586                 this.host = host;
150587                 this.globalTypingsCacheLocation = globalTypingsCacheLocation;
150588                 this.typingSafeListLocation = typingSafeListLocation;
150589                 this.typesMapLocation = typesMapLocation;
150590                 this.npmLocation = npmLocation;
150591                 this.validateDefaultNpmLocation = validateDefaultNpmLocation;
150592                 this.event = event;
150593                 this.activeRequestCount = 0;
150594                 this.requestQueue = [];
150595                 this.requestMap = ts.createMap(); // Maps operation ID to newest requestQueue entry with that ID
150596                 /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */
150597                 this.requestedRegistry = false;
150598             }
150599             NodeTypingsInstaller.prototype.isKnownTypesPackageName = function (name) {
150600                 // We want to avoid looking this up in the registry as that is expensive. So first check that it's actually an NPM package.
150601                 var validationResult = ts.JsTyping.validatePackageName(name);
150602                 if (validationResult !== 0 /* Ok */) {
150603                     return false;
150604                 }
150605                 if (this.requestedRegistry) {
150606                     return !!this.typesRegistryCache && this.typesRegistryCache.has(name);
150607                 }
150608                 this.requestedRegistry = true;
150609                 this.send({ kind: "typesRegistry" });
150610                 return false;
150611             };
150612             NodeTypingsInstaller.prototype.installPackage = function (options) {
150613                 var _this = this;
150614                 this.send(__assign({ kind: "installPackage" }, options));
150615                 ts.Debug.assert(this.packageInstalledPromise === undefined);
150616                 return new Promise(function (resolve, reject) {
150617                     _this.packageInstalledPromise = { resolve: resolve, reject: reject };
150618                 });
150619             };
150620             NodeTypingsInstaller.prototype.attach = function (projectService) {
150621                 var _this = this;
150622                 this.projectService = projectService;
150623                 if (this.logger.hasLevel(server.LogLevel.requestTime)) {
150624                     this.logger.info("Binding...");
150625                 }
150626                 var args = [server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation];
150627                 if (this.telemetryEnabled) {
150628                     args.push(server.Arguments.EnableTelemetry);
150629                 }
150630                 if (this.logger.loggingEnabled() && this.logger.getLogFileName()) {
150631                     args.push(server.Arguments.LogFile, ts.combinePaths(ts.getDirectoryPath(ts.normalizeSlashes(this.logger.getLogFileName())), "ti-" + process.pid + ".log"));
150632                 }
150633                 if (this.typingSafeListLocation) {
150634                     args.push(server.Arguments.TypingSafeListLocation, this.typingSafeListLocation);
150635                 }
150636                 if (this.typesMapLocation) {
150637                     args.push(server.Arguments.TypesMapLocation, this.typesMapLocation);
150638                 }
150639                 if (this.npmLocation) {
150640                     args.push(server.Arguments.NpmLocation, this.npmLocation);
150641                 }
150642                 if (this.validateDefaultNpmLocation) {
150643                     args.push(server.Arguments.ValidateDefaultNpmLocation);
150644                 }
150645                 var execArgv = [];
150646                 for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) {
150647                     var arg = _a[_i];
150648                     var match = /^--((?:debug|inspect)(?:-brk)?)(?:=(\d+))?$/.exec(arg);
150649                     if (match) {
150650                         // if port is specified - use port + 1
150651                         // otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1
150652                         var currentPort = match[2] !== undefined
150653                             ? +match[2]
150654                             : match[1].charAt(0) === "d" ? 5858 : 9229;
150655                         execArgv.push("--" + match[1] + "=" + (currentPort + 1));
150656                         break;
150657                     }
150658                 }
150659                 this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv });
150660                 this.installer.on("message", function (m) { return _this.handleMessage(m); });
150661                 this.event({ pid: this.installer.pid }, "typingsInstallerPid");
150662                 process.on("exit", function () {
150663                     _this.installer.kill();
150664                 });
150665             };
150666             NodeTypingsInstaller.prototype.onProjectClosed = function (p) {
150667                 this.send({ projectName: p.getProjectName(), kind: "closeProject" });
150668             };
150669             NodeTypingsInstaller.prototype.send = function (rq) {
150670                 this.installer.send(rq);
150671             };
150672             NodeTypingsInstaller.prototype.enqueueInstallTypingsRequest = function (project, typeAcquisition, unresolvedImports) {
150673                 var _this = this;
150674                 var request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
150675                 if (this.logger.hasLevel(server.LogLevel.verbose)) {
150676                     if (this.logger.hasLevel(server.LogLevel.verbose)) {
150677                         this.logger.info("Scheduling throttled operation:" + server.stringifyIndented(request));
150678                     }
150679                 }
150680                 var operationId = project.getProjectName();
150681                 var operation = function () {
150682                     if (_this.logger.hasLevel(server.LogLevel.verbose)) {
150683                         _this.logger.info("Sending request:" + server.stringifyIndented(request));
150684                     }
150685                     _this.send(request);
150686                 };
150687                 var queuedRequest = { operationId: operationId, operation: operation };
150688                 if (this.activeRequestCount < NodeTypingsInstaller.maxActiveRequestCount) {
150689                     this.scheduleRequest(queuedRequest);
150690                 }
150691                 else {
150692                     if (this.logger.hasLevel(server.LogLevel.verbose)) {
150693                         this.logger.info("Deferring request for: " + operationId);
150694                     }
150695                     this.requestQueue.push(queuedRequest);
150696                     this.requestMap.set(operationId, queuedRequest);
150697                 }
150698             };
150699             NodeTypingsInstaller.prototype.handleMessage = function (response) {
150700                 if (this.logger.hasLevel(server.LogLevel.verbose)) {
150701                     this.logger.info("Received response:" + server.stringifyIndented(response));
150702                 }
150703                 switch (response.kind) {
150704                     case server.EventTypesRegistry:
150705                         this.typesRegistryCache = ts.createMapFromTemplate(response.typesRegistry);
150706                         break;
150707                     case server.ActionPackageInstalled: {
150708                         var success = response.success, message = response.message;
150709                         if (success) {
150710                             this.packageInstalledPromise.resolve({ successMessage: message });
150711                         }
150712                         else {
150713                             this.packageInstalledPromise.reject(message);
150714                         }
150715                         this.packageInstalledPromise = undefined;
150716                         this.projectService.updateTypingsForProject(response);
150717                         // The behavior is the same as for setTypings, so send the same event.
150718                         this.event(response, "setTypings");
150719                         break;
150720                     }
150721                     case server.EventInitializationFailed: {
150722                         var body = {
150723                             message: response.message
150724                         };
150725                         var eventName = "typesInstallerInitializationFailed";
150726                         this.event(body, eventName);
150727                         break;
150728                     }
150729                     case server.EventBeginInstallTypes: {
150730                         var body = {
150731                             eventId: response.eventId,
150732                             packages: response.packagesToInstall,
150733                         };
150734                         var eventName = "beginInstallTypes";
150735                         this.event(body, eventName);
150736                         break;
150737                     }
150738                     case server.EventEndInstallTypes: {
150739                         if (this.telemetryEnabled) {
150740                             var body_1 = {
150741                                 telemetryEventName: "typingsInstalled",
150742                                 payload: {
150743                                     installedPackages: response.packagesToInstall.join(","),
150744                                     installSuccess: response.installSuccess,
150745                                     typingsInstallerVersion: response.typingsInstallerVersion
150746                                 }
150747                             };
150748                             var eventName_1 = "telemetry";
150749                             this.event(body_1, eventName_1);
150750                         }
150751                         var body = {
150752                             eventId: response.eventId,
150753                             packages: response.packagesToInstall,
150754                             success: response.installSuccess,
150755                         };
150756                         var eventName = "endInstallTypes";
150757                         this.event(body, eventName);
150758                         break;
150759                     }
150760                     case server.ActionInvalidate: {
150761                         this.projectService.updateTypingsForProject(response);
150762                         break;
150763                     }
150764                     case server.ActionSet: {
150765                         if (this.activeRequestCount > 0) {
150766                             this.activeRequestCount--;
150767                         }
150768                         else {
150769                             ts.Debug.fail("Received too many responses");
150770                         }
150771                         while (this.requestQueue.length > 0) {
150772                             var queuedRequest = this.requestQueue.shift();
150773                             if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) {
150774                                 this.requestMap.delete(queuedRequest.operationId);
150775                                 this.scheduleRequest(queuedRequest);
150776                                 break;
150777                             }
150778                             if (this.logger.hasLevel(server.LogLevel.verbose)) {
150779                                 this.logger.info("Skipping defunct request for: " + queuedRequest.operationId);
150780                             }
150781                         }
150782                         this.projectService.updateTypingsForProject(response);
150783                         this.event(response, "setTypings");
150784                         break;
150785                     }
150786                     default:
150787                         ts.assertType(response);
150788                 }
150789             };
150790             NodeTypingsInstaller.prototype.scheduleRequest = function (request) {
150791                 if (this.logger.hasLevel(server.LogLevel.verbose)) {
150792                     this.logger.info("Scheduling request for: " + request.operationId);
150793                 }
150794                 this.activeRequestCount++;
150795                 this.host.setTimeout(request.operation, NodeTypingsInstaller.requestDelayMillis);
150796             };
150797             // This number is essentially arbitrary.  Processing more than one typings request
150798             // at a time makes sense, but having too many in the pipe results in a hang
150799             // (see https://github.com/nodejs/node/issues/7657).
150800             // It would be preferable to base our limit on the amount of space left in the
150801             // buffer, but we have yet to find a way to retrieve that value.
150802             NodeTypingsInstaller.maxActiveRequestCount = 10;
150803             NodeTypingsInstaller.requestDelayMillis = 100;
150804             return NodeTypingsInstaller;
150805         }());
150806         var IOSession = /** @class */ (function (_super) {
150807             __extends(IOSession, _super);
150808             function IOSession() {
150809                 var _this = this;
150810                 var event = function (body, eventName) {
150811                     if (_this.constructed) {
150812                         _this.event(body, eventName);
150813                     }
150814                     else {
150815                         // It is unsafe to dereference `this` before initialization completes,
150816                         // so we defer until the next tick.
150817                         //
150818                         // Construction should finish before the next tick fires, so we do not need to do this recursively.
150819                         // eslint-disable-next-line no-restricted-globals
150820                         setImmediate(function () { return _this.event(body, eventName); });
150821                     }
150822                 };
150823                 var host = sys;
150824                 var typingsInstaller = disableAutomaticTypingAcquisition
150825                     ? undefined
150826                     : new NodeTypingsInstaller(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, event);
150827                 _this = _super.call(this, {
150828                     host: host,
150829                     cancellationToken: cancellationToken,
150830                     useSingleInferredProject: useSingleInferredProject,
150831                     useInferredProjectPerProjectRoot: useInferredProjectPerProjectRoot,
150832                     typingsInstaller: typingsInstaller || server.nullTypingsInstaller,
150833                     byteLength: Buffer.byteLength,
150834                     hrtime: process.hrtime,
150835                     logger: logger,
150836                     canUseEvents: true,
150837                     suppressDiagnosticEvents: suppressDiagnosticEvents,
150838                     syntaxOnly: syntaxOnly,
150839                     noGetErrOnBackgroundUpdate: noGetErrOnBackgroundUpdate,
150840                     globalPlugins: globalPlugins,
150841                     pluginProbeLocations: pluginProbeLocations,
150842                     allowLocalPluginLoads: allowLocalPluginLoads,
150843                     typesMapLocation: typesMapLocation,
150844                 }) || this;
150845                 _this.eventPort = eventPort;
150846                 if (_this.canUseEvents && _this.eventPort) {
150847                     var s_1 = net.connect({ port: _this.eventPort }, function () {
150848                         _this.eventSocket = s_1;
150849                         if (_this.socketEventQueue) {
150850                             // flush queue.
150851                             for (var _i = 0, _a = _this.socketEventQueue; _i < _a.length; _i++) {
150852                                 var event_1 = _a[_i];
150853                                 _this.writeToEventSocket(event_1.body, event_1.eventName);
150854                             }
150855                             _this.socketEventQueue = undefined;
150856                         }
150857                     });
150858                 }
150859                 _this.constructed = true;
150860                 return _this;
150861             }
150862             IOSession.prototype.event = function (body, eventName) {
150863                 ts.Debug.assert(!!this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession");
150864                 if (this.canUseEvents && this.eventPort) {
150865                     if (!this.eventSocket) {
150866                         if (this.logger.hasLevel(server.LogLevel.verbose)) {
150867                             this.logger.info("eventPort: event \"" + eventName + "\" queued, but socket not yet initialized");
150868                         }
150869                         (this.socketEventQueue || (this.socketEventQueue = [])).push({ body: body, eventName: eventName });
150870                         return;
150871                     }
150872                     else {
150873                         ts.Debug.assert(this.socketEventQueue === undefined);
150874                         this.writeToEventSocket(body, eventName);
150875                     }
150876                 }
150877                 else {
150878                     _super.prototype.event.call(this, body, eventName);
150879                 }
150880             };
150881             IOSession.prototype.writeToEventSocket = function (body, eventName) {
150882                 this.eventSocket.write(server.formatMessage(server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8");
150883             };
150884             IOSession.prototype.exit = function () {
150885                 this.logger.info("Exiting...");
150886                 this.projectService.closeLog();
150887                 process.exit(0);
150888             };
150889             IOSession.prototype.listen = function () {
150890                 var _this = this;
150891                 rl.on("line", function (input) {
150892                     var message = input.trim();
150893                     _this.onMessage(message);
150894                 });
150895                 rl.on("close", function () {
150896                     _this.exit();
150897                 });
150898             };
150899             return IOSession;
150900         }(server.Session));
150901         function parseLoggingEnvironmentString(logEnvStr) {
150902             if (!logEnvStr) {
150903                 return {};
150904             }
150905             var logEnv = { logToFile: true };
150906             var args = logEnvStr.split(" ");
150907             var len = args.length - 1;
150908             for (var i = 0; i < len; i += 2) {
150909                 var option = args[i];
150910                 var _a = getEntireValue(i + 1), value = _a.value, extraPartCounter = _a.extraPartCounter;
150911                 i += extraPartCounter;
150912                 if (option && value) {
150913                     switch (option) {
150914                         case "-file":
150915                             logEnv.file = value;
150916                             break;
150917                         case "-level":
150918                             var level = getLogLevel(value);
150919                             logEnv.detailLevel = level !== undefined ? level : server.LogLevel.normal;
150920                             break;
150921                         case "-traceToConsole":
150922                             logEnv.traceToConsole = value.toLowerCase() === "true";
150923                             break;
150924                         case "-logToFile":
150925                             logEnv.logToFile = value.toLowerCase() === "true";
150926                             break;
150927                     }
150928                 }
150929             }
150930             return logEnv;
150931             function getEntireValue(initialIndex) {
150932                 var pathStart = args[initialIndex];
150933                 var extraPartCounter = 0;
150934                 if (pathStart.charCodeAt(0) === 34 /* doubleQuote */ &&
150935                     pathStart.charCodeAt(pathStart.length - 1) !== 34 /* doubleQuote */) {
150936                     for (var i = initialIndex + 1; i < args.length; i++) {
150937                         pathStart += " ";
150938                         pathStart += args[i];
150939                         extraPartCounter++;
150940                         if (pathStart.charCodeAt(pathStart.length - 1) === 34 /* doubleQuote */)
150941                             break;
150942                     }
150943                 }
150944                 return { value: ts.stripQuotes(pathStart), extraPartCounter: extraPartCounter };
150945             }
150946         }
150947         function getLogLevel(level) {
150948             if (level) {
150949                 var l = level.toLowerCase();
150950                 for (var name in server.LogLevel) {
150951                     if (isNaN(+name) && l === name.toLowerCase()) {
150952                         return server.LogLevel[name];
150953                     }
150954                 }
150955             }
150956             return undefined;
150957         }
150958         // TSS_LOG "{ level: "normal | verbose | terse", file?: string}"
150959         function createLogger() {
150960             var cmdLineLogFileName = server.findArgument("--logFile");
150961             var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity"));
150962             var envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG);
150963             var unsubstitutedLogFileName = cmdLineLogFileName
150964                 ? ts.stripQuotes(cmdLineLogFileName)
150965                 : envLogOptions.logToFile
150966                     ? envLogOptions.file || (__dirname + "/.log" + process.pid.toString())
150967                     : undefined;
150968             var substitutedLogFileName = unsubstitutedLogFileName
150969                 ? unsubstitutedLogFileName.replace("PID", process.pid.toString())
150970                 : undefined;
150971             var logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel;
150972             return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217
150973         }
150974         // This places log file in the directory containing editorServices.js
150975         // TODO: check that this location is writable
150976         // average async stat takes about 30 microseconds
150977         // set chunk size to do 30 files in < 1 millisecond
150978         function createPollingWatchedFileSet(interval, chunkSize) {
150979             if (interval === void 0) { interval = 2500; }
150980             if (chunkSize === void 0) { chunkSize = 30; }
150981             var watchedFiles = [];
150982             var nextFileToCheck = 0;
150983             return { getModifiedTime: getModifiedTime, poll: poll, startWatchTimer: startWatchTimer, addFile: addFile, removeFile: removeFile };
150984             function getModifiedTime(fileName) {
150985                 return fs.statSync(fileName).mtime;
150986             }
150987             function poll(checkedIndex) {
150988                 var watchedFile = watchedFiles[checkedIndex];
150989                 if (!watchedFile) {
150990                     return;
150991                 }
150992                 fs.stat(watchedFile.fileName, function (err, stats) {
150993                     if (err) {
150994                         if (err.code === "ENOENT") {
150995                             if (watchedFile.mtime.getTime() !== 0) {
150996                                 watchedFile.mtime = ts.missingFileModifiedTime;
150997                                 watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Deleted);
150998                             }
150999                         }
151000                         else {
151001                             watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Changed);
151002                         }
151003                     }
151004                     else {
151005                         ts.onWatchedFileStat(watchedFile, stats.mtime);
151006                     }
151007                 });
151008             }
151009             // this implementation uses polling and
151010             // stat due to inconsistencies of fs.watch
151011             // and efficiency of stat on modern filesystems
151012             function startWatchTimer() {
151013                 // eslint-disable-next-line no-restricted-globals
151014                 setInterval(function () {
151015                     var count = 0;
151016                     var nextToCheck = nextFileToCheck;
151017                     var firstCheck = -1;
151018                     while ((count < chunkSize) && (nextToCheck !== firstCheck)) {
151019                         poll(nextToCheck);
151020                         if (firstCheck < 0) {
151021                             firstCheck = nextToCheck;
151022                         }
151023                         nextToCheck++;
151024                         if (nextToCheck === watchedFiles.length) {
151025                             nextToCheck = 0;
151026                         }
151027                         count++;
151028                     }
151029                     nextFileToCheck = nextToCheck;
151030                 }, interval);
151031             }
151032             function addFile(fileName, callback) {
151033                 var file = {
151034                     fileName: fileName,
151035                     callback: callback,
151036                     mtime: sys.fileExists(fileName)
151037                         ? getModifiedTime(fileName)
151038                         : ts.missingFileModifiedTime // Any subsequent modification will occur after this time
151039                 };
151040                 watchedFiles.push(file);
151041                 if (watchedFiles.length === 1) {
151042                     startWatchTimer();
151043                 }
151044                 return file;
151045             }
151046             function removeFile(file) {
151047                 ts.unorderedRemoveItem(watchedFiles, file);
151048             }
151049         }
151050         // REVIEW: for now this implementation uses polling.
151051         // The advantage of polling is that it works reliably
151052         // on all os and with network mounted files.
151053         // For 90 referenced files, the average time to detect
151054         // changes is 2*msInterval (by default 5 seconds).
151055         // The overhead of this is .04 percent (1/2500) with
151056         // average pause of < 1 millisecond (and max
151057         // pause less than 1.5 milliseconds); question is
151058         // do we anticipate reference sets in the 100s and
151059         // do we care about waiting 10-20 seconds to detect
151060         // changes for large reference sets? If so, do we want
151061         // to increase the chunk size or decrease the interval
151062         // time dynamically to match the large reference set?
151063         var pollingWatchedFileSet = createPollingWatchedFileSet();
151064         var pending = [];
151065         var canWrite = true;
151066         function writeMessage(buf) {
151067             if (!canWrite) {
151068                 pending.push(buf);
151069             }
151070             else {
151071                 canWrite = false;
151072                 process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary);
151073             }
151074         }
151075         function setCanWriteFlagAndWriteMessageIfNecessary() {
151076             canWrite = true;
151077             if (pending.length) {
151078                 writeMessage(pending.shift());
151079             }
151080         }
151081         function extractWatchDirectoryCacheKey(path, currentDriveKey) {
151082             path = ts.normalizeSlashes(path);
151083             if (isUNCPath(path)) {
151084                 // UNC path: extract server name
151085                 // //server/location
151086                 //         ^ <- from 0 to this position
151087                 var firstSlash = path.indexOf(ts.directorySeparator, 2);
151088                 return firstSlash !== -1 ? ts.toFileNameLowerCase(path.substring(0, firstSlash)) : path;
151089             }
151090             var rootLength = ts.getRootLength(path);
151091             if (rootLength === 0) {
151092                 // relative path - assume file is on the current drive
151093                 return currentDriveKey;
151094             }
151095             if (path.charCodeAt(1) === 58 /* colon */ && path.charCodeAt(2) === 47 /* slash */) {
151096                 // rooted path that starts with c:/... - extract drive letter
151097                 return ts.toFileNameLowerCase(path.charAt(0));
151098             }
151099             if (path.charCodeAt(0) === 47 /* slash */ && path.charCodeAt(1) !== 47 /* slash */) {
151100                 // rooted path that starts with slash - /somename - use key for current drive
151101                 return currentDriveKey;
151102             }
151103             // do not cache any other cases
151104             return undefined;
151105         }
151106         function isUNCPath(s) {
151107             return s.length > 2 && s.charCodeAt(0) === 47 /* slash */ && s.charCodeAt(1) === 47 /* slash */;
151108         }
151109         var logger = createLogger();
151110         var sys = ts.sys;
151111         var nodeVersion = ts.getNodeMajorVersion();
151112         // use watchGuard process on Windows when node version is 4 or later
151113         var useWatchGuard = process.platform === "win32" && nodeVersion >= 4;
151114         var originalWatchDirectory = sys.watchDirectory.bind(sys);
151115         var noopWatcher = { close: ts.noop };
151116         // This is the function that catches the exceptions when watching directory, and yet lets project service continue to function
151117         // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point
151118         function watchDirectorySwallowingException(path, callback, recursive, options) {
151119             try {
151120                 return originalWatchDirectory(path, callback, recursive, options);
151121             }
151122             catch (e) {
151123                 logger.info("Exception when creating directory watcher: " + e.message);
151124                 return noopWatcher;
151125             }
151126         }
151127         if (useWatchGuard) {
151128             var currentDrive_1 = extractWatchDirectoryCacheKey(sys.resolvePath(sys.getCurrentDirectory()), /*currentDriveKey*/ undefined);
151129             var statusCache_1 = ts.createMap();
151130             sys.watchDirectory = function (path, callback, recursive, options) {
151131                 var cacheKey = extractWatchDirectoryCacheKey(path, currentDrive_1);
151132                 var status = cacheKey && statusCache_1.get(cacheKey);
151133                 if (status === undefined) {
151134                     if (logger.hasLevel(server.LogLevel.verbose)) {
151135                         logger.info(cacheKey + " for path " + path + " not found in cache...");
151136                     }
151137                     try {
151138                         var args = [ts.combinePaths(__dirname, "watchGuard.js"), path];
151139                         if (logger.hasLevel(server.LogLevel.verbose)) {
151140                             logger.info("Starting " + process.execPath + " with args:" + server.stringifyIndented(args));
151141                         }
151142                         childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } });
151143                         status = true;
151144                         if (logger.hasLevel(server.LogLevel.verbose)) {
151145                             logger.info("WatchGuard for path " + path + " returned: OK");
151146                         }
151147                     }
151148                     catch (e) {
151149                         status = false;
151150                         if (logger.hasLevel(server.LogLevel.verbose)) {
151151                             logger.info("WatchGuard for path " + path + " returned: " + e.message);
151152                         }
151153                     }
151154                     if (cacheKey) {
151155                         statusCache_1.set(cacheKey, status);
151156                     }
151157                 }
151158                 else if (logger.hasLevel(server.LogLevel.verbose)) {
151159                     logger.info("watchDirectory for " + path + " uses cached drive information.");
151160                 }
151161                 if (status) {
151162                     // this drive is safe to use - call real 'watchDirectory'
151163                     return watchDirectorySwallowingException(path, callback, recursive, options);
151164                 }
151165                 else {
151166                     // this drive is unsafe - return no-op watcher
151167                     return noopWatcher;
151168                 }
151169             };
151170         }
151171         else {
151172             sys.watchDirectory = watchDirectorySwallowingException;
151173         }
151174         // Override sys.write because fs.writeSync is not reliable on Node 4
151175         sys.write = function (s) { return writeMessage(sys.bufferFrom(s, "utf8")); };
151176         sys.watchFile = function (fileName, callback) {
151177             var watchedFile = pollingWatchedFileSet.addFile(fileName, callback);
151178             return {
151179                 close: function () { return pollingWatchedFileSet.removeFile(watchedFile); }
151180             };
151181         };
151182         /* eslint-disable no-restricted-globals */
151183         sys.setTimeout = setTimeout;
151184         sys.clearTimeout = clearTimeout;
151185         sys.setImmediate = setImmediate;
151186         sys.clearImmediate = clearImmediate;
151187         /* eslint-enable no-restricted-globals */
151188         if (typeof global !== "undefined" && global.gc) {
151189             sys.gc = function () { return global.gc(); };
151190         }
151191         sys.require = function (initialDir, moduleName) {
151192             try {
151193                 return { module: require(ts.resolveJSModule(moduleName, initialDir, sys)), error: undefined };
151194             }
151195             catch (error) {
151196                 return { module: undefined, error: error };
151197             }
151198         };
151199         var cancellationToken;
151200         try {
151201             var factory = require("./cancellationToken");
151202             cancellationToken = factory(sys.args);
151203         }
151204         catch (e) {
151205             cancellationToken = server.nullCancellationToken;
151206         }
151207         function parseEventPort(eventPortStr) {
151208             var eventPort = eventPortStr === undefined ? undefined : parseInt(eventPortStr);
151209             return eventPort !== undefined && !isNaN(eventPort) ? eventPort : undefined;
151210         }
151211         var eventPort = parseEventPort(server.findArgument("--eventPort"));
151212         var localeStr = server.findArgument("--locale");
151213         if (localeStr) {
151214             ts.validateLocaleAndSetLanguage(localeStr, sys);
151215         }
151216         ts.setStackTraceLimit();
151217         var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); // TODO: GH#18217
151218         var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(ts.getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json");
151219         var npmLocation = server.findArgument(server.Arguments.NpmLocation);
151220         var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
151221         function parseStringArray(argName) {
151222             var arg = server.findArgument(argName);
151223             if (arg === undefined) {
151224                 return server.emptyArray;
151225             }
151226             return arg.split(",").filter(function (name) { return name !== ""; });
151227         }
151228         var globalPlugins = parseStringArray("--globalPlugins");
151229         var pluginProbeLocations = parseStringArray("--pluginProbeLocations");
151230         var allowLocalPluginLoads = server.hasArgument("--allowLocalPluginLoads");
151231         var useSingleInferredProject = server.hasArgument("--useSingleInferredProject");
151232         var useInferredProjectPerProjectRoot = server.hasArgument("--useInferredProjectPerProjectRoot");
151233         var disableAutomaticTypingAcquisition = server.hasArgument("--disableAutomaticTypingAcquisition");
151234         var suppressDiagnosticEvents = server.hasArgument("--suppressDiagnosticEvents");
151235         var syntaxOnly = server.hasArgument("--syntaxOnly");
151236         var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry);
151237         var noGetErrOnBackgroundUpdate = server.hasArgument("--noGetErrOnBackgroundUpdate");
151238         logger.info("Starting TS Server");
151239         logger.info("Version: " + ts.version);
151240         logger.info("Arguments: " + process.argv.join(" "));
151241         logger.info("Platform: " + os.platform() + " NodeVersion: " + nodeVersion + " CaseSensitive: " + sys.useCaseSensitiveFileNames);
151242         var ioSession = new IOSession();
151243         process.on("uncaughtException", function (err) {
151244             ioSession.logError(err, "unknown");
151245         });
151246         // See https://github.com/Microsoft/TypeScript/issues/11348
151247         process.noAsar = true;
151248         // Start listening
151249         ioSession.listen();
151250         if (ts.Debug.isDebugging) {
151251             ts.Debug.enableDebugInfo();
151252         }
151253         if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) {
151254             ts.sys.tryEnableSourceMapsForHost();
151255         }
151256         // Overwrites the current console messages to instead write to
151257         // the log. This is so that language service plugins which use
151258         // console.log don't break the message passing between tsserver
151259         // and the client
151260         console.log = function () {
151261             var args = [];
151262             for (var _i = 0; _i < arguments.length; _i++) {
151263                 args[_i] = arguments[_i];
151264             }
151265             return logger.msg(args.length === 1 ? args[0] : args.join(", "), server.Msg.Info);
151266         };
151267         console.warn = function () {
151268             var args = [];
151269             for (var _i = 0; _i < arguments.length; _i++) {
151270                 args[_i] = arguments[_i];
151271             }
151272             return logger.msg(args.length === 1 ? args[0] : args.join(", "), server.Msg.Err);
151273         };
151274         console.error = function () {
151275             var args = [];
151276             for (var _i = 0; _i < arguments.length; _i++) {
151277                 args[_i] = arguments[_i];
151278             }
151279             return logger.msg(args.length === 1 ? args[0] : args.join(", "), server.Msg.Err);
151280         };
151281     })(server = ts.server || (ts.server = {}));
151282 })(ts || (ts = {}));
151283 //# sourceMappingURL=tsserver.js.map